<template>
  <div class="tenant">
    <!-- <Banner /> -->
    <div class="content">
      <byTable
        :source="sourceList.data"
        :pagination="sourceList.pagination"
        :config="config"
        :loading="loading"
        highlight-current-row
        :selectConfig="selectConfig"
        :table-events="{
          //element talbe事件都能传
          select: select,
        }"
        :action-list="[]"
        @get-list="getList"
      >
        <template #money="{ item }">
          {{ item.currency }} {{ moneyFormat(item.amount) }}
        </template>
      </byTable>
    </div>
    <el-dialog
      title="认领"
      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="4"
                      :controls="false"
                      :min="0"
                    />
                  </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"
          @click="submitForm('byform')"
          size="large"
          :loading="submitLoading"
        >
          确 定
        </el-button>
      </template>
    </el-dialog>

    <el-dialog
      title="合同选择"
      v-model="dialogVisibleOne"
      width="80%"
      v-loading="loading"
      destroy-on-close
    >
      <ContractSelect
        @handleSelectContrct="handleSelectContrct"
      ></ContractSelect>
    </el-dialog>
  </div>
</template>
  
<script setup>
/* eslint-disable vue/no-unused-components */
import { ElMessage, ElMessageBox } from "element-plus";
import byTable from "@/components/byTable/index";
import byForm from "@/components/byForm/index";
import { computed, defineComponent, ref } from "vue";
import useUserStore from "@/store/modules/user";
import { getToken } from "@/utils/auth";

import ContractSelect from "@/views/salesMange/saleContract/contractSelect/index";

const headers = ref({ Authorization: "Bearer " + getToken() });
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 { proxy } = getCurrentInstance();
const selectConfig = reactive([
  {
    label: "认领状态",
    prop: "isClaim",
    data: [
      {
        label: "未认领",
        value: "0",
      },
      {
        label: "已认领",
        value: "1",
      },
    ],
  },
]);
const inboundType = ref([
  {
    label: "未入库",
    value: "0",
  },
  {
    label: "部分入库",
    value: "1",
  },
  {
    label: "入库完成",
    value: "2",
  },
]);
const config = computed(() => {
  return [
    {
      attrs: {
        label: "账户名称",
        prop: "accountManagementName",
      },
      // render(type) {
      //   return proxy.dictDataEcho(type, warehouseType.value);
      // },
    },
    {
      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: "认领状态",
        prop: "isClaim",
      },
      render(isClaim) {
        return isClaim == 1 ? "已认领" : isClaim == 0 ? "未认领" : "";
      },
    },
    {
      attrs: {
        label: "操作",
        width: "100",
        align: "right",
      },
      // 渲染 el-button，一般用在最后一列。
      renderHTML(row) {
        return [
          row.isClaim == 0
            ? {
                attrs: {
                  label: "认领",
                  type: "primary",
                  text: true,
                  bg: true,
                  disabled: false,
                },
                el: "button",
                click() {
                  getDtl(row);
                },
              }
            : {},
          row.isClaim == 1
            ? {
                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: {},
  treeData: [],
});
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
});
const byform = ref(null);
const treeData = ref([]);
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: "amount",
    selectProp: "currency",
    label: " ",
    itemWidth: 70,
    disabled: true,
  },

  // {
  //   type: "select",
  //   prop: "warehouseId",
  //   label: "仓库名称",
  //   itemWidth: 33,
  //   isLoad: {
  //     url: "/warehouse/page",
  //     req: {
  //       pageNum: 1,
  //       pageSize: 9999,
  //     },
  //     labelKey: "name",
  //     labelVal: "id",
  //     method: "post",
  //     resUrl: "rows",
  //   },
  // },
  {
    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) => {
      console.log(message);
      sourceList.value.data = message.rows;
      // .map((x) => ({
      //   ...x,
      //   ...JSON.parse(x.victoriatouristJson),
      // }));
      sourceList.value.pagination.total = message.total;
      setTimeout(() => {
        loading.value = false;
      }, 200);
    });
};
const openModal = () => {
  dialogVisible.value = true;
  modalType.value = "add";
  formData.data = {};
};

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 (Number(formData.data.amount) !== total) {
      return ElMessage({
        message: "认领金额总合和交易金额需一致！",
        type: "info",
      });
    }
    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 getDtl = (row) => {
  modalType.value = "edit";
  dialogVisible.value = true;
  formData.data = {
    businessId: row.id,
    status: row.status + "",
    currency: row.currency,
    amount: row.amount,
    accountManagementId: row.accountManagementId,
    accountManagementName: row.accountManagementName,
    claimTime: proxy.parseTime(new Date()),
    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,
  });
  return ElMessage({
    message: "选择成功",
    type: "success",
  });
};

getList();
getDict();
onMounted(() => {});
</script>
  
<style lang="scss" scoped>
.tenant {
  padding: 20px;
}
</style>