<template>
  <div class="tenant">
    <div class="content">
      <byTable
        :source="sourceList.data"
        :pagination="sourceList.pagination"
        :config="config"
        :loading="loading"
        highlight-current-row
        :action-list="[
          {
            text: '添加账户',
            action: () => openModal('add'),
          },
        ]"
        @get-list="getList">
      </byTable>
    </div>

    <el-dialog :title="modalType == 'add' ? '添加账户' : '编辑账户'" v-if="dialogVisible" v-model="dialogVisible" width="600" v-loading="loadingDialog">
      <byForm :formConfig="formConfig" :formOption="formOption" v-model="formData.data" :rules="rules" ref="submit">
        <template #balance>
          <div style="width: 100%">
            <el-button type="primary" @click="clickBalance">添加</el-button>
            <el-table :data="formData.data.accountRemainderList" style="width: 100%; margin-top: 16px">
              <el-table-column label="币种">
                <template #default="{ row, $index }">
                  <el-form-item :prop="'accountRemainderList.' + $index + '.currency'" :rules="rules.currency" :inline-message="true">
                    <el-select v-model="row.currency" placeholder="请选择币种" style="width: 100%" :disabled="row.id">
                      <el-option v-for="item in accountCurrency" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey" />
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="余额">
                <template #default="{ row, $index }">
                  <el-form-item :prop="'accountRemainderList.' + $index + '.remainder'" :rules="rules.remainder" :inline-message="true">
                    <el-input-number
                      onmousewheel="return false;"
                      v-model="row.remainder"
                      placeholder="请输入余额"
                      style="width: 100%"
                      :precision="2"
                      :controls="false"
                      :min="0"
                      :disabled="row.id" />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80">
                <template #default="{ row, $index }">
                  <el-button type="primary" link @click="handleRemove($index)" v-if="!row.id">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </template>
      </byForm>
      <template #footer>
        <el-button @click="dialogVisible = false" size="large">取 消</el-button>
        <el-button type="primary" @click="submitForm()" size="large">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { computed, ref } from "vue";
import byTable from "@/components/byTable/index";
import byForm from "@/components/byForm/index";
import useUserStore from "@/store/modules/user";
import { ElMessage, ElMessageBox } from "element-plus";

const { proxy } = getCurrentInstance();
const accountCurrency = ref([]);
const sourceList = ref({
  data: [],
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 10,
    keyword: "",
  },
});
const loading = ref(false);
const config = computed(() => {
  return [
    {
      attrs: {
        label: "归属公司",
        prop: "corporationName",
      },
    },
    {
      attrs: {
        label: "账户别名",
        prop: "alias",
      },
    },
    {
      attrs: {
        label: "开户银行",
        prop: "openingBank",
      },
    },
    {
      attrs: {
        label: "账户名",
        prop: "name",
      },
    },
    {
      attrs: {
        label: "账号",
        prop: "accountOpening",
      },
    },
    {
      attrs: {
        label: "联行号",
        prop: "interbankNumber",
      },
    },
    {
      attrs: {
        label: "操作",
        width: "120",
        align: "center",
      },
      renderHTML(row) {
        return [
          {
            attrs: {
              label: "修改",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              update(row);
            },
          },
          {
            attrs: {
              label: "删除",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              ElMessageBox.confirm("此操作将永久删除该数据, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              }).then(() => {
                proxy
                  .post("/accountManagement/delete", {
                    id: row.id,
                  })
                  .then(() => {
                    ElMessage({
                      message: "删除成功",
                      type: "success",
                    });
                    getList();
                  });
              });
            },
          },
        ];
      },
    },
  ];
});
const corporationList = ref([]);
const getDict = () => {
  proxy
    .post("/dictTenantData/page", {
      pageNum: 1,
      pageSize: 999,
      dictCode: "account_currency",
      tenantId: useUserStore().user.tenantId,
    })
    .then((res) => {
      if (res.rows && res.rows.length > 0) {
        accountCurrency.value = res.rows;
      }
    });
  proxy.post("/corporation/page", { pageNum: 1, pageSize: 9999 }).then((res) => {
    corporationList.value = res.rows.map((item) => {
      return {
        ...item,
        label: item.name,
        value: item.id,
      };
    });
  });
};
const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy.post("/accountManagement/page", sourceList.value.pagination).then((res) => {
    sourceList.value.data = res.rows;
    sourceList.value.pagination.total = res.total;
    setTimeout(() => {
      loading.value = false;
    }, 200);
  });
};
getDict();
getList();
const modalType = ref("add");
const dialogVisible = ref(false);
const loadingDialog = ref(false);
const submit = ref(null);
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
});
const formConfig = computed(() => {
  return [
    {
      type: "title",
      title: "基本信息",
      label: "",
    },
    {
      type: "select",
      prop: "corporationId",
      label: "归属公司",
      data: corporationList.value,
    },
    {
      type: "input",
      prop: "alias",
      label: "账户别名",
      required: true,
      itemWidth: 100,
      itemType: "text",
    },
    {
      type: "input",
      prop: "openingBank",
      label: "开户银行",
      required: true,
      itemWidth: 100,
      itemType: "text",
    },
    {
      type: "input",
      prop: "name",
      label: "账户名",
      required: true,
      itemWidth: 100,
      itemType: "text",
    },
    {
      type: "input",
      prop: "accountOpening",
      label: "账号",
      required: true,
      itemWidth: 100,
      itemType: "text",
    },
    {
      type: "input",
      prop: "interbankNumber",
      label: "联行号",
      required: true,
      itemWidth: 100,
      itemType: "text",
    },
    {
      type: "title",
      title: "外汇信息",
      label: "",
    },
    {
      type: "input",
      prop: "beneficiaryName",
      label: "Beneficiary Name",
      required: true,
      itemType: "text",
    },
    {
      type: "input",
      prop: "beneficiaryBank",
      label: "Beneficiary Bank",
      required: true,
      itemType: "text",
    },
    {
      type: "input",
      prop: "beneficiaryBankAddress",
      label: "Beneficiary Bank Address",
      required: true,
      itemType: "text",
    },
    {
      type: "input",
      prop: "beneficiaryAccountNumber",
      label: "Beneficiary Account Number",
      required: true,
      itemType: "text",
    },
    {
      type: "input",
      prop: "swiftCode",
      label: "Swift Code",
      required: true,
      itemType: "text",
    },
    {
      type: "input",
      prop: "beneficiaryAddress",
      label: "Beneficiary Address",
      required: true,
      itemType: "text",
    },
    {
      type: "slot",
      slotName: "balance",
      label: "账户余额",
    },
  ];
});
const rules = ref({
  alias: [{ required: true, message: "请输入账户别名", trigger: "blur" }],
  openingBank: [{ required: true, message: "请输入开户银行", trigger: "blur" }],
  name: [{ required: true, message: "请输入账户名", trigger: "blur" }],
  accountOpening: [{ required: true, message: "请输入账号", trigger: "blur" }],
  currency: [{ required: true, message: "请选择币种", trigger: "change" }],
  remainder: [{ required: true, message: "请输入账户余额", trigger: "blur" }],
  corporationId: [{ required: true, message: "请选择归属公司", trigger: "change" }],
});
const formData = reactive({
  data: {
    accountRemainderList: [{ currency: "", remainder: undefined }],
  },
});
const openModal = (val) => {
  modalType.value = val;
  formData.data = {
    accountRemainderList: [{ currency: "", remainder: undefined }],
  };
  loadingDialog.value = false;
  dialogVisible.value = true;
};
const clickBalance = () => {
  if (formData.data.accountRemainderList && formData.data.accountRemainderList.length > 0) {
    formData.data.accountRemainderList.push({
      currency: "",
      remainder: undefined,
    });
  } else {
    formData.data.accountRemainderList = [{ currency: "", remainder: undefined }];
  }
};
const handleRemove = (index) => {
  formData.data.accountRemainderList.splice(index, 1);
};
const isRepeat = (arr) => {
  var hash = {};
  for (var i in arr) {
    if (hash[arr[i].currency]) return true;
    hash[arr[i].currency] = true;
  }
  return false;
};
const submitForm = () => {
  submit.value.handleSubmit(() => {
    if (formData.data.accountRemainderList && formData.data.accountRemainderList.length > 0) {
      if (isRepeat(formData.data.accountRemainderList)) {
        return ElMessage("请勿重复添加货币余额");
      } else {
        loadingDialog.value = true;
        proxy.post("/accountManagement/" + modalType.value, formData.data).then(
          () => {
            ElMessage({
              message: modalType.value == "add" ? "添加成功" : "编辑成功",
              type: "success",
            });
            dialogVisible.value = false;
            getList();
          },
          (err) => {
            console.log(err);
            loadingDialog.value = false;
          }
        );
      }
    } else {
      return ElMessage("请添加至少一条账户余额");
    }
  });
};
const update = (row) => {
  modalType.value = "edit";
  loadingDialog.value = true;
  proxy.post("/accountManagement/detail", { id: row.id }).then((res) => {
    res.accountRemainderList = res.accountRemainderList.map((item) => {
      return {
        id: item.id,
        currency: item.currency,
        remainder: item.remainder,
      };
    });
    formData.data = res;
    loadingDialog.value = false;
  });
  dialogVisible.value = true;
};
</script>

<style lang="scss" scoped>
.tenant {
  padding: 20px;
}
::v-deep(.el-input-number .el-input__inner) {
  text-align: left;
}
</style>
