<template>
  <div class="tenant">
    <byTable
      :source="sourceList.data"
      :pagination="sourceList.pagination"
      :config="config"
      :loading="loading"
      highlight-current-row
      :selectConfig="selectConfig"
      :action-list="[]"
      @get-list="getList">
      <template #money="{ item }"> {{ item.currency }} {{ moneyFormat(item.amount) }} </template>
      <template #isClaim="{ item }">
        <div style="width: 100%">
          <span v-if="item.isClaim == 0">未认领</span>
          <a style="color: #409eff; cursor: pointer" @click="clickRecord(item)" v-else-if="item.isClaim == 1">已认领</a>
          <a style="color: #409eff; cursor: pointer" @click="clickRecord(item)" v-else>部分认领</a>
        </div>
      </template>
    </byTable>

    <el-dialog title="认领" v-if="dialogVisible" v-model="dialogVisible" width="500" v-loading="loading">
      <byForm :formConfig="formConfig" :formOption="formOption" v-model="formData.data" :rules="rules" ref="byform">
        <template #detail>
          <div style="width: 100%">
            <el-button type="primary" style="margin-bottom: 10px" @click="dialogVisibleOne = true">选择合同</el-button>
            <el-table :data="formData.data.claimContractList">
              <el-table-column prop="contractCode" label="合同编码" />
              <el-table-column prop="money" label="关联金额" min-width="150">
                <template #default="{ row, $index }">
                  <el-form-item :prop="'claimContractList.' + $index + '.money'" :rules="rules.money" :inline-message="true">
                    <el-input-number v-model="row.money" :precision="2" :controls="false" :min="0" onmousewheel="return false;" />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column prop="zip" label="操作" width="100">
                <template #default="{ $index }">
                  <el-button type="primary" link @click="handleRemove($index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </template>
        <template #fileSlot>
          <div>
            <el-upload
              v-model:fileList="fileList"
              :show-file-list="false"
              class="upload-demo"
              action="https://winfaster.obs.cn-south-1.myhuaweicloud.com"
              :data="uploadData"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              :before-upload="handleBeforeUpload">
              <el-button type="primary">选择</el-button>
            </el-upload>
            <div>
              <div style="margin-top: 15px">
                <el-tag
                  style="margin-right: 10px"
                  class="ml-2"
                  type="info"
                  v-for="(item, index) in fileListCopy"
                  :key="index"
                  closable
                  @close="handleClose(index)">
                  {{ item.fileName }}
                </el-tag>
              </div>
            </div>
          </div>
        </template>
      </byForm>
      <template #footer>
        <el-button @click="dialogVisible = false" size="large">取 消</el-button>
        <el-button type="primary" v-no-double-click="submitForm" size="large" :loading="submitLoading"> 确 定 </el-button>
      </template>
    </el-dialog>

    <el-dialog title="合同选择" v-if="dialogVisibleOne" v-model="dialogVisibleOne" width="80%" v-loading="loading" destroy-on-close>
      <ContractSelect @handleSelectContrct="handleSelectContrct"></ContractSelect>
    </el-dialog>

    <el-dialog title="认领记录" v-if="openRecord" v-model="openRecord" width="500">
      <byForm :formConfig="formRecordConfig" :formOption="formOption" v-model="rowData.data">
        <template #recordList>
          <div>
            <div style="width: 100%" v-if="rowData.data.recordList && rowData.data.recordList.length > 0">
              <div v-for="(item, index) in rowData.data.recordList" :key="index">
                <div style="color: #ccc">{{ item.createTime }}</div>
                <div>认领人: {{ item.claimUserName }}</div>
                <div>合同编号: {{ item.contractCode }}</div>
                <div>认领金额: {{ item.currency }}{{ item.money }}</div>
                <br />
              </div>
            </div>
            <div v-else>无</div>
          </div>
        </template>
      </byForm>
      <template #footer>
        <el-button @click="openRecord = false" size="large">取 消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

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

const { proxy } = getCurrentInstance();
const uploadData = ref({});
let fileList = ref([]);
let fileListCopy = ref([]);
const loading = ref(false);
const submitLoading = ref(false);
const sourceList = ref({
  data: [],
  pagination: {
    total: 3,
    pageNum: 1,
    pageSize: 10,
    type: 1,
    dataType: "1",
  },
});
let dialogVisible = ref(false);
let dialogVisibleOne = ref(false);
let modalType = ref("add");
let rules = ref({
  money: [{ required: true, message: "请输入关联金额", trigger: "blur" }],
});
const claim = ref([
  {
    label: "未认领",
    value: "0",
  },
  {
    label: "已认领",
    value: "1",
  },
  {
    label: "部分认领",
    value: "2",
  },
]);
const selectConfig = reactive([
  {
    label: "认领状态",
    prop: "isClaim",
    data: claim.value,
  },
]);
const config = computed(() => {
  return [
    {
      attrs: {
        label: "账户名称",
        prop: "accountManagementName",
      },
    },
    {
      attrs: {
        label: "到账金额",
        prop: "amount",
        slot: "money",
      },
    },

    {
      attrs: {
        label: "到账时间",
        prop: "transactionTime",
      },
    },
    {
      attrs: {
        label: "对方账户名称",
        prop: "name",
      },
    },
    {
      attrs: {
        label: "对方开户银行",
        prop: "openingBank",
      },
    },
    {
      attrs: {
        label: "对方账号",
        prop: "accountOpening",
      },
    },
    {
      attrs: {
        label: "摘要",
        prop: "remarks",
      },
    },
    {
      attrs: {
        label: "认领状态",
        slot: "isClaim",
        width: 120,
      },
    },
    {
      attrs: {
        label: "操作",
        width: "140",
        align: "right",
      },
      renderHTML(row) {
        return [
          row.isClaim != 1
            ? {
                attrs: {
                  label: "认领",
                  type: "primary",
                  text: true,
                  bg: true,
                  disabled: false,
                },
                el: "button",
                click() {
                  getDtl(row);
                },
              }
            : {},
          row.isClaim != 0
            ? {
                attrs: {
                  label: "取消认领",
                  text: true,
                  bg: true,
                  type: "primary",
                  disabled: false,
                  style: {
                    color: "#e6a23c",
                  },
                },
                el: "button",
                click() {
                  ElMessageBox.confirm("是否确定取消认领?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                  }).then(() => {
                    // 删除
                    proxy
                      .post("/claim/delete", {
                        id: row.id,
                      })
                      .then((res) => {
                        ElMessage({
                          message: "操作成功",
                          type: "success",
                        });
                        getList();
                      });
                  });
                },
              }
            : {},
        ];
      },
    },
  ];
});

let formData = reactive({
  data: {},
});
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
});
const byform = ref(null);
const formConfig = reactive([
  {
    type: "title",
    title: "账户信息",
  },
  {
    type: "select",
    prop: "accountManagementName",
    label: "选择账户",
    required: true,
    disabled: true,
  },
  {
    type: "title",
    title: "交易信息",
  },
  {
    type: "date",
    itemType: "datetime",
    prop: "claimTime",
    label: "交易时间",
    disabled: true,
  },
  {
    type: "select",
    prop: "status",
    label: "交易金额",
    itemWidth: 30,
    disabled: true,
    data: [
      {
        label: "收入",
        value: "10",
      },
      {
        label: "支出",
        value: "20",
      },
    ],
  },
  {
    type: "selectInput",
    prop: "waitAmount",
    selectProp: "currency",
    label: " ",
    itemWidth: 70,
    disabled: true,
  },
  {
    type: "title",
    title: "认领信息",
  },
  {
    type: "slot",
    slotName: "detail",
    label: "",
  },
  {
    type: "slot",
    slotName: "fileSlot",
    label: "上传附件",
  },
]);
const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy.post("/accountRunningWater/page", sourceList.value.pagination).then((message) => {
    sourceList.value.data = message.rows;
    sourceList.value.pagination.total = message.total;
    setTimeout(() => {
      loading.value = false;
    }, 200);
  });
};
const submitForm = () => {
  byform.value.handleSubmit((valid) => {
    const list = formData.data.claimContractList;
    if (!(list.length > 0)) {
      return ElMessage({
        message: `请添加认领信息！`,
        type: "info",
      });
    }
    for (let i = 0; i < list.length; i++) {
      const e = list[i];
      if (!(e.money > 0)) {
        return ElMessage({
          message: "关联金额不能为0！",
          type: "info",
        });
      }
    }
    const total = list.reduce((total, x) => (total += Number(x.money)), 0);
    if (total > Number(formData.data.waitAmount)) {
      return ElMessage({
        message: "认领金额总合不能大于交易金额！",
        type: "info",
      });
    }
    formData.data.amount = total;
    formData.data.fileList =
      fileListCopy.value.map((x) => ({
        id: x.id,
        fileName: x.fileName,
      })) || [];
    submitLoading.value = true;
    proxy.post("/claim/add", formData.data).then(
      (res) => {
        ElMessage({
          message: "操作成功",
          type: "success",
        });
        dialogVisible.value = false;
        submitLoading.value = false;
        getList();
      },
      (err) => (submitLoading.value = false)
    );
  });
};
const rowCurrency = ref("");
const getDtl = (row) => {
  rowCurrency.value = row.currency;
  proxy.get(`/claim/sumClaimMoney?businessId=${row.id}`).then((res) => {
    modalType.value = "edit";
    dialogVisible.value = true;
    formData.data = {
      businessId: row.id,
      rate: row.rate,
      status: row.status + "",
      currency: row.currency,
      waitAmount: Number(row.amount) - Number(res.data),
      accountManagementId: row.accountManagementId,
      accountManagementName: row.accountManagementName,
      claimTime: row.transactionTime,
      claimContractList: [],
    };
    dialogVisible.value = true;
  });
};

const warehouseType = ref([]);
const getDict = () => {
  proxy
    .post("/dictTenantData/page", {
      pageNum: 1,
      pageSize: 999,
      tenantId: useUserStore().user.tenantId,
      dictCode: "warehouse_type",
    })
    .then((res) => {
      warehouseType.value = res.rows;
      formConfig[0].data = res.rows.map((x) => ({
        label: x.dictValue,
        value: x.dictKey,
      }));
    });
};
const handleBeforeUpload = async (file) => {
  const res = await proxy.post("/fileInfo/getSing", { fileName: file.name });
  uploadData.value = res.uploadBody;
  fileListCopy.value.push({
    id: res.id,
    fileName: res.fileName,
    path: res.fileUrl,
    url: res.fileUrl,
    uid: file.uid,
  });
};
const handleClose = (index) => {
  // if (fileListCopy.value.length === 1) {
  //   return ElMessage({
  //     message: "最后一个附件啦！",
  //     type: "info",
  //   });
  // }
  fileList.value.splice(index, 1);
  fileListCopy.value.splice(index, 1);
};
const handleRemove = (index) => {
  formData.data.claimContractList.splice(index, 1);
  return ElMessage({
    message: "删除成功",
    type: "success",
  });
};
const handleSelectContrct = (row) => {
  const flag = formData.data.claimContractList.some((x) => x.contractId === row.id);
  if (flag)
    return ElMessage({
      message: "该合同已选择",
      type: "info",
    });
  formData.data.claimContractList.push({
    contractId: row.id,
    contractCode: row.code,
    money: 0,
    currency: rowCurrency.value,
  });
  return ElMessage({
    message: "选择成功",
    type: "success",
  });
};
getList();
getDict();
onMounted(() => {});
const openRecord = ref(false);
const rowData = reactive({
  data: {},
});
const formRecordConfig = reactive([
  {
    type: "title",
    title: "账户信息",
    label: "",
  },
  {
    type: "select",
    prop: "accountManagementName",
    label: "选择账户",
    required: true,
    disabled: true,
  },
  {
    type: "title",
    title: "交易信息",
    label: "",
  },
  {
    type: "date",
    itemType: "datetime",
    prop: "claimTime",
    label: "交易时间",
    disabled: true,
  },
  {
    type: "select",
    prop: "status",
    label: "交易金额",
    itemWidth: 30,
    disabled: true,
    data: [
      {
        label: "收入",
        value: "10",
      },
      {
        label: "支出",
        value: "20",
      },
    ],
  },
  {
    type: "selectInput",
    prop: "waitAmount",
    selectProp: "currency",
    label: " ",
    itemWidth: 70,
    disabled: true,
  },
  {
    type: "slot",
    slotName: "recordList",
    label: "认领记录",
  },
]);
const clickRecord = (row) => {
  rowData.data = {
    businessId: row.id,
    status: row.status + "",
    currency: row.currency,
    waitAmount: Number(row.amount),
    accountManagementId: row.accountManagementId,
    accountManagementName: row.accountManagementName,
    claimTime: row.transactionTime,
    recordList: [],
  };
  openRecord.value = true;
  proxy.post("/claim/claimRecord", { businessId: row.id }).then((res) => {
    rowData.data.recordList = res;
  });
};
</script>

<style lang="scss" scoped>
.tenant {
  padding: 20px;
}
</style>
