<template>
  <div class="user">
    <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 #pic="{ item }">
          <div v-if="item.fileList.length > 0">
            <img
              :src="item.fileList[0].fileUrl"
              class="pic"
              @click="handleClickFile(item.fileList[0])"
            />
          </div>
          <div v-else></div>
        </template>
      </byTable>
    </div>
    <el-dialog
      :title="modalType == 'add' ? '打款' : '打款'"
      v-model="dialogVisible"
      width="500"
      v-loading="loading"
    >
      <byForm
        :formConfig="formConfig"
        :formOption="formOption"
        v-model="formData.data"
        :rules="rules"
        ref="byform"
      >
        <template #productPic>
          <div>
            <el-upload
              v-model:fileList="fileList"
              action="https://winfaster.obs.cn-south-1.myhuaweicloud.com"
              :data="uploadData"
              list-type="picture-card"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              :before-upload="handleBeforeUpload"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
          </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="Excel导入"
      v-model="openExcelDialog"
      width="400"
      v-loading="loading"
    >
      <template #footer>
        <el-button @click="openExcelDialog = false" size="large"
          >取 消</el-button
        >
        <el-button
          type="primary"
          @click="submitExcel()"
          size="large"
          :loading="submitLoading"
        >
          确 定
        </el-button>
      </template>
    </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 Cookies from "js-cookie";
import { computed, defineComponent, ref } from "vue";
const loading = ref(false);
const submitLoading = ref(false);
const sourceList = ref({
  data: [],
  pagination: {
    total: 3,
    pageNum: 1,
    pageSize: 10,
    type: "",
    productClassifyId: "",
    keyword: "",
    definition: "2",
  },
});
let dialogVisible = ref(false);
let openExcelDialog = ref(false);

let modalType = ref("add");
let rules = ref({
  productClassifyId: [
    { required: true, message: "请选择物料分类", trigger: "change" },
  ],
  type: [{ required: true, message: "请选择物料类型", trigger: "change" }],
  // name: [{ required: true, message: "请输入物料名称", trigger: "blur" }],
  // unit: [{ required: true, message: "请选择单位", trigger: "change" }],
});
const { proxy } = getCurrentInstance();
const selectConfig = computed(() => {
  return [
    {
      label: "打款状态",
      prop: "paymentStatus",
      data: paymentType.value,
    },
  ];
});
const config = computed(() => {
  return [
    {
      attrs: {
        label: "归属公司",
        prop: "corporationName",
      },
    },
    {
      attrs: {
        label: "归属部门",
        prop: "deptName",
      },
    },
    {
      attrs: {
        label: "付款类型",
        prop: "type",
      },
      render(type) {
        return proxy.dictDataEcho(type, dictsData.payment_status);
      },
    },
    {
      attrs: {
        label: "申请人",
        prop: "userName",
      },
    },
    {
      attrs: {
        label: "申请时间",
        prop: "createTime",
      },
    },
    {
      attrs: {
        label: "用款时间",
        prop: "paymentTime",
      },
    },
    {
      attrs: {
        label: "金额",
        prop: "amount",
      },
    },
    {
      attrs: {
        label: "款项说明",
        prop: "paymentRemark",
      },
    },
    {
      attrs: {
        label: "打款状态",
        prop: "status",
      },
      render(status) {
        return proxy.dictValueLabel(status, paymentType.value);
      },
    },
    {
      attrs: {
        label: "操作",
        width: "200",
        align: "right",
      },
      // 渲染 el-button，一般用在最后一列。
      renderHTML(row) {
        return [
          {
            attrs: {
              label: "打款",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              formOption.disabled = false;
              getDtl(row);
            },
          },
          {
            attrs: {
              label: "查看",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              formOption.disabled = true;
              getDtl(row);
            },
          },
        ];
      },
    },
  ];
});

let formData = reactive({
  data: {},
});
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
  disabled: false,
});
const byform = ref(null);
const treeListData = ref([]);
const formConfig = computed(() => {
  return [
    {
      type: "title",
      label: "请款信息",
    },
    {
      type: "input",
      prop: "businessManagementName",
      label: "付款账户",
      disabled: true,
    },
    {
      type: "input",
      prop: "incomeAmount",
      label: "请款金额",
      disabled: true,
    },
    {
      type: "input",
      prop: "paymentMethod",
      label: "付款方式",
      disabled: true,
    },
    {
      type: "input",
      prop: "name",
      label: "户名",
      disabled: true,
    },
    {
      type: "input",
      prop: "accountOpening",
      label: "银行账号",
      disabled: true,
    },
    {
      type: "input",
      prop: "openingBank",
      label: "开户银行",
      disabled: true,
    },
    {
      type: "input",
      prop: "interbankNumber",
      label: "联行号 / SWIFT Code",
      disabled: true,
    },
    {
      type: "input",
      prop: "remark",
      label: "摘要",
      disabled: true,
    },
    {
      type: "title",
      title: "付款信息",
    },
    {
      type: "select",
      prop: "accountManagementId",
      label: "付款账户",
      required: true,
      isLoad: {
        url: "/accountManagement/page",
        req: {
          pageNum: 1,
          pageSize: 9999,
        },
        labelKey: "name",
        labelVal: "id",
        method: "post",
        resUrl: "rows",
      },
    },
    {
      type: "selectInput",
      label: "付款金额",
      itemWidth: 60,
      prop: "amount",
      data: [],
      placeholder: "请输入",
      selectPlaceholder: "币种",
      selectProp: "currency",
      disabled: true,
    },
    {
      type: "date",
      itemType: "datetime",
      prop: "expensesTime",
      label: "打款时间",
      format: "YYYY-MM-DD HH:mm:ss",
    },
    {
      type: "input",
      prop: "remark",
      label: "摘要",
    },
    // {
    // 	type: 'upload',
    // 	prop: 'upload',
    // 	label: '摘要',
    // },
    // {
    // 	type: 'slot',
    // 	slotName: 'productPic',
    // 	prop: 'fileList',
    // 	label: '上传附件',
    // },
  ];
});
const newPassword = () => {
  formData.data.password = generatePassword();
};
const generatePassword = () => {
  var length = 12,
    charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
    password = "";
  for (var i = 0, n = charset.length; i < length; ++i) {
    password += charset.charAt(Math.floor(Math.random() * n));
  }
  return password;
};
const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy
    .post("/accountPayment/page", sourceList.value.pagination)
    .then((message) => {
      console.log(message);
      sourceList.value.data = message.rows;
      sourceList.value.pagination.total = message.total;
      setTimeout(() => {
        loading.value = false;
      }, 200);
    });
};
const uploadData = ref({});
const fileList = ref([]);
const paymentType = ref([
  {
    label: "已打款",
    value: 10,
  },
  {
    label: "未打款",
    value: 20,
  },
]);
const fileListCopy = ref([]);
let dictsData = reactive({
  payment_status: [],
  account_currency: [],
});
proxy.getDict(["payment_status", "account_currency"]).then((res) => {
  dictsData = res;
  formConfig.value[11].data = res.account_currency.map((item) => {
    return {
      label: item.dictValue,
      value: item.dictKey,
    };
  });
  console.log(formConfig.value[11].data);
});
const openModal = () => {
  dialogVisible.value = true;
  modalType.value = "add";
  formData.data = {
    definition: "2",
    fileList: [],
    type: "1",
  };
  fileList.value = [];
  fileListCopy.value = [];
};

const openExcel = () => {
  openExcelDialog.value = true;
};
const submitExcel = () => {
  openExcelDialog.value = false;
};
const selection = ref({
  data: [],
});
const select = (_selection, row) => {
  selection.value.data = _selection;
  console.log(_selection.length);
};

const submitForm = () => {
  console.log(fileList);

  byform.value.handleSubmit((valid) => {
    submitLoading.value = true;
    proxy.post("/accountPayment/add", formData.data).then(
      (res) => {
        ElMessage({
          message: "打款成功",
          type: "success",
        });
        dialogVisible.value = false;
        submitLoading.value = false;
        getList();
      },
      (err) => {
        submitLoading.value = false;
      }
    );
  });
};

const getTreeList = () => {
  proxy
    .post("/productClassify/tree", {
      parentId: "",
      name: "",
      definition: "2",
    })
    .then((message) => {
      treeListData.value = message;
      formConfig.value[0].data = message;
    });
};

const getDtl = (row) => {
  modalType.value = "edit";
  proxy.post("/accountPayment/detail", { id: row.id }).then((res) => {
    formData.data = res;
    formData.data.amount = formData.data.incomeAmount;
    dialogVisible.value = true;
  });
};
getTreeList();
getList();
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 handleSuccess = (res, file, files) => {
  // 查当前file的index值去赋值对应的copy变量的值
  // let uid = file.uid;
  // const index = fileList.value.findIndex((x) => x.uid === uid);
  // fileListCopy.value[index].uid = uid;
};

const handleRemove = (file) => {
  const index = fileListCopy.value.findIndex(
    (x) => x.uid === file.uid || x.id === file.id
  );
  fileListCopy.value.splice(index, 1);
};

const handleClickFile = (file) => {
  window.open(file.fileUrl, "_blank");
};
</script>

<style lang="scss" scoped>
.user {
  padding: 20px;
}
.pic {
  object-fit: contain;
  width: 50px;
  height: 50px;
  cursor: pointer;
  vertical-align: middle;
}
</style>
