<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="[]"
        @moreSearch="moreSearch"
        @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-if="dialogVisible" 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"
              :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="高级检索" v-if="openSearch" v-model="openSearch" width="600" :before-close="cancelSearch">
      <byForm :formConfig="formSearchConfig" :formOption="formOption" v-model="sourceList.pagination">
        <template #departmentId>
          <div>
            <el-tree-select
              v-model="sourceList.pagination.departmentId"
              :data="deptTreeData"
              check-strictly
              :render-after-expand="false"
              node-key="deptId"
              style="width: 100%"
              :props="defaultProps"
              clearable />
          </div>
        </template>
        <template #time>
          <div style="width: 100%">
            <el-row :gutter="10">
              <el-col :span="11">
                <el-date-picker
                  v-model="sourceList.pagination.beginCreateTime"
                  type="datetime"
                  placeholder="请选择"
                  style="width: 100%"
                  value-format="YYYY-MM-DD HH:mm:ss" />
              </el-col>
              <el-col :span="2" style="text-align: center">到</el-col>
              <el-col :span="11">
                <el-date-picker
                  v-model="sourceList.pagination.endCreateTime"
                  type="datetime"
                  placeholder="请选择"
                  style="width: 100%"
                  value-format="YYYY-MM-DD HH:mm:ss" />
              </el-col>
            </el-row>
          </div>
        </template>
        <template #timeTwo>
          <div style="width: 100%">
            <el-row :gutter="10">
              <el-col :span="11">
                <el-date-picker
                  v-model="sourceList.pagination.beginTime"
                  type="datetime"
                  placeholder="请选择"
                  style="width: 100%"
                  value-format="YYYY-MM-DD HH:mm:ss" />
              </el-col>
              <el-col :span="2" style="text-align: center">到</el-col>
              <el-col :span="11">
                <el-date-picker
                  v-model="sourceList.pagination.endTime"
                  type="datetime"
                  placeholder="请选择"
                  style="width: 100%"
                  value-format="YYYY-MM-DD HH:mm:ss" />
              </el-col>
            </el-row>
          </div>
        </template>
        <template #money>
          <div style="width: 100%">
            <el-row :gutter="10">
              <el-col :span="11">
                <el-input-number
                  onmousewheel="return false;"
                  v-model="sourceList.pagination.startAmount"
                  placeholder="请输入"
                  style="width: 100%"
                  :precision="2"
                  :controls="false"
                  :min="0" />
              </el-col>
              <el-col :span="2" style="text-align: center">到</el-col>
              <el-col :span="11">
                <el-input-number
                  onmousewheel="return false;"
                  v-model="sourceList.pagination.endAmount"
                  placeholder="请输入"
                  style="width: 100%"
                  :precision="2"
                  :controls="false"
                  :min="0" />
              </el-col>
            </el-row>
          </div>
        </template>
      </byForm>
      <template #footer>
        <el-button @click="cancelSearch()" size="large">取 消</el-button>
        <el-button type="primary" @click="submitSearch()" size="large">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

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

const loading = ref(false);
const submitLoading = ref(false);
const sourceList = ref({
  data: [],
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 10,
    keyword: "",
    corporationId: "",
    departmentId: "",
    createUser: "",
    beginCreateTime: "",
    endCreateTime: "",
    beginTime: "",
    endTime: "",
    currency: "",
    startAmount: undefined,
    endAmount: undefined,
    paymentStatus: "",
    paymentRemark: "",
    type: "",
  },
});
let dialogVisible = ref(false);
let modalType = ref("add");
let rules = ref({
  productClassifyId: [{ required: true, message: "请选择物料分类", trigger: "change" }],
  type: [{ required: true, message: "请选择物料类型", trigger: "change" }],
});
const accountCurrency = ref([]);
const accountList = ref([]);
const companyData = ref([]);
const deptTreeData = ref([]);
const userList = ref([]);
const fundsType = ref([]);
const fundsPaymentMethod = ref([]);
const { proxy } = getCurrentInstance();
const selectConfig = computed(() => {
  return [
    {
      label: "打款状态",
      prop: "paymentStatus",
      data: paymentType.value,
    },
  ];
});
const config = computed(() => {
  return [
    {
      attrs: {
        label: "归属公司",
        prop: "corporationName",
        width: 160,
      },
    },
    {
      attrs: {
        label: "归属部门",
        prop: "deptName",
        width: 160,
      },
    },
    {
      attrs: {
        label: "付款类型",
        prop: "type",
        width: 130,
      },
      render(type) {
        if (type != "20") {
          return "请款: " + proxy.dictValueLabel(type, fundsType.value);
        } else {
          return "采购付款 - 申请";
        }
      },
    },
    {
      attrs: {
        label: "申请人",
        prop: "userName",
        width: 140,
      },
    },
    {
      attrs: {
        label: "申请时间",
        prop: "createTime",
        width: 160,
      },
    },
    {
      attrs: {
        label: "用款时间",
        prop: "paymentTime",
        width: 160,
      },
    },
    {
      attrs: {
        label: "金额",
        prop: "amount",
        width: 120,
      },
    },
    {
      attrs: {
        label: "款项说明",
        prop: "paymentRemark",
        "min-width": 200,
      },
    },
    {
      attrs: {
        label: "打款状态",
        prop: "status",
        width: 120,
      },
      render(status) {
        return proxy.dictValueLabel(status, paymentType.value);
      },
    },
    {
      attrs: {
        label: "操作",
        width: "120",
        align: "center",
        fixed: "right",
      },
      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: "select",
      prop: "paymentMethod",
      label: "付款方式",
      disabled: true,
      data: fundsPaymentMethod.value,
    },
    {
      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: "paymentRemark",
      label: "摘要",
      disabled: true,
      itemType: "textarea",
    },
    {
      type: "title",
      title: "付款信息",
    },
    {
      type: "select",
      prop: "accountManagementId",
      label: "付款账户",
      required: true,
      data: accountList.value,
    },
    {
      type: "selectInput",
      label: "付款金额",
      itemWidth: 60,
      prop: "amount",
      data: accountCurrency.value,
      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: "摘要",
      itemType: "textarea",
    },
  ];
});
const recursive = (data) => {
  data.map((item) => {
    item.label = item.deptName;
    item.id = item.corporationId;
    if (item.children) {
      recursive(item.children);
    } else {
      item.children = [];
    }
  });
};
const getDict = () => {
  proxy.getDict(["account_currency", "founds_type", "funds_payment_method"]).then((res) => {
    accountCurrency.value = res.account_currency.map((item) => {
      return {
        label: item.dictValue,
        value: item.dictKey,
      };
    });
    fundsType.value = res.founds_type.map((item) => {
      return {
        label: item.dictValue,
        value: item.dictKey,
      };
    });
    fundsPaymentMethod.value = res.funds_payment_method.map((item) => {
      return {
        label: item.dictValue,
        value: item.dictKey,
      };
    });
  });
  proxy.post("/accountManagement/page", { pageNum: 1, pageSize: 9999 }).then((res) => {
    if (res.rows && res.rows.length > 0) {
      accountList.value = res.rows.map((item) => {
        return {
          label: item.alias + " (" + item.name + ")",
          value: item.id,
        };
      });
    }
  });
  proxy.post("/corporation/page", { pageNum: 1, pageSize: 9999 }).then((res) => {
    if (res.rows && res.rows.length > 0) {
      companyData.value = res.rows.map((item) => {
        return {
          label: item.name,
          value: item.id,
        };
      });
    }
  });
  proxy
    .get("/tenantDept/list", {
      pageNum: 1,
      pageSize: 9999,
      tenantId: useUserStore().user.tenantId,
    })
    .then((message) => {
      recursive(message.data);
      deptTreeData.value = [];
      let data = proxy.handleTree(message.data, "deptId");
      if (data && data.length > 0) {
        for (let i = 0; i < data.length; i++) {
          if (data[i].children && data[i].children.length > 0) {
            deptTreeData.value = deptTreeData.value.concat(data[i].children);
          }
        }
      }
    });
  proxy
    .get("/tenantUser/list", {
      pageNum: 1,
      pageSize: 10000,
      tenantId: useUserStore().user.tenantId,
    })
    .then((res) => {
      if (res.rows && res.rows.length > 0) {
        userList.value = res.rows.map((item) => {
          return {
            deptId: item.deptId,
            label: item.nickName,
            value: item.userId,
          };
        });
      }
    });
};
getDict();
const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy.post("/accountPayment/page", sourceList.value.pagination).then((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([]);
const selection = ref({
  data: [],
});
const select = (_selection, row) => {
  selection.value.data = _selection;
};

const submitForm = () => {
  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.expensesTime = moment().format("yyyy-MM-DD HH:mm:ss");
    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 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");
};
const openSearch = ref(false);
const formSearchConfig = computed(() => {
  return [
    {
      type: "select",
      prop: "corporationId",
      label: "归属公司",
      data: companyData.value,
      clearable: true,
    },
    {
      type: "slot",
      slotName: "departmentId",
      label: "归属部门",
    },
    {
      type: "select",
      prop: "createUser",
      label: "请款人",
      data: userList.value,
      clearable: true,
    },
    {
      type: "select",
      prop: "type",
      label: "付款类型",
      data: fundsType.value,
      clearable: true,
    },
    {
      type: "slot",
      slotName: "time",
      label: "请款时间",
    },
    {
      type: "slot",
      slotName: "timeTwo",
      label: "用款时间",
    },
    {
      type: "select",
      prop: "currency",
      label: "币种",
      data: accountCurrency.value,
      clearable: true,
    },
    {
      type: "slot",
      slotName: "money",
      label: "交易金额",
    },
    {
      type: "select",
      prop: "paymentStatus",
      label: "打款状态",
      data: paymentType.value,
      clearable: true,
    },
    {
      type: "input",
      itemType: "textarea",
      prop: "paymentRemark",
      label: "款项说明",
    },
  ];
});
let copySearch = ref({});
const moreSearch = () => {
  copySearch.value = proxy.deepClone(sourceList.value.pagination);
  openSearch.value = true;
};
const cancelSearch = () => {
  sourceList.value.pagination = copySearch.value;
  openSearch.value = false;
};
const submitSearch = () => {
  if (
    sourceList.value.pagination.startAmount &&
    sourceList.value.pagination.endAmount &&
    Number(sourceList.value.pagination.startAmount) > Number(sourceList.value.pagination.endAmount)
  ) {
    return ElMessage("交易金额输入错误");
  }
  if (
    sourceList.value.pagination.beginCreateTime &&
    sourceList.value.pagination.endCreateTime &&
    sourceList.value.pagination.beginCreateTime > sourceList.value.pagination.endCreateTime
  ) {
    return ElMessage("开始时间不能大于结束时间");
  }
  if (
    sourceList.value.pagination.beginTime &&
    sourceList.value.pagination.endTime &&
    sourceList.value.pagination.beginTime > sourceList.value.pagination.endTime
  ) {
    return ElMessage("开始时间不能大于结束时间");
  }
  openSearch.value = false;
  sourceList.value.pagination.pageNum = 1;
  getList();
};
</script>

<style lang="scss" scoped>
.user {
  padding: 20px;
}
.pic {
  object-fit: contain;
  width: 50px;
  height: 50px;
  cursor: pointer;
  vertical-align: middle;
}
::v-deep(.el-input-number .el-input__inner) {
  text-align: left;
}
</style>
