<template>
  <div class="pageIndexClass">
    <div class="content">
      <byTable :source="sourceList.data" :pagination="sourceList.pagination" :config="config" :loading="loading" highlight-current-row
               :selectConfig="selectConfig" :action-list="[
          {
            text: '发起请款',
            action: () => openModal(),
          },
        ]" @moreSearch="moreSearch" @get-list="getList">
        <template #total="{ item }">
          <div style="width: 100%">
            <a style="color: #409eff; cursor: pointer" @click="pushProcessApproval(item)">{{ item.currency }}{{ item.total }}</a>
          </div>
        </template>
        <template #type="{ item }">
          <div style="width: 100%">
            <span>
              {{ dictValueLabel(item.type, fundsType) }}
            </span>
            <span v-if="item.type == 1">（<span v-if="item.writeOffStatus == 0">未核销</span><span v-if="item.writeOffStatus == 1">已核销</span>）</span>
          </div>
        </template>
        <template #file="{ item }">
          <div style="width: 100%">
            <el-button type="primary" text @click="handleOpenFile(item)">查看</el-button>
          </div>
        </template>
      </byTable>
    </div>

    <el-dialog title="打印" v-if="openPrint" v-model="openPrint" width="840px">
      <FundsPDF :rowData="rowData"></FundsPDF>
      <template #footer>
        <el-button @click="openPrint = false" size="default">取消</el-button>
        <el-button type="primary" v-print="printObj" size="default">打印</el-button>
        <el-button type="primary" @click="clickDownload()" size="default">下载PDF</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.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.minAdvanceAmounts" 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.maxAdvanceAmounts" placeholder="请输入" style="width: 100%"
                                 :precision="2" :controls="false" :min="0" />
              </el-col>
            </el-row>
          </div>
        </template>
      </byForm>
      <template #footer>
        <el-button @click="cancelSearch()" size="default">取 消</el-button>
        <el-button type="primary" @click="submitSearch()" size="default">确 定</el-button>
      </template>
    </el-dialog>

    <el-dialog title="关联附件" v-if="openFileDialog" v-model="openFileDialog" width="500">
      <byForm :formConfig="fileConfig" :formOption="formOption" v-model="fileData.data">
        <template #businessFile>
          <div style="width: 100%" v-if="fileData.data && fileData.data.fileList.length > 0">
            <div v-for="(item, index) in fileData.data.fileList" :key="index">
              <div style="cursor: pointer; color: #409eff" @click="openFile(item)">
                {{ item.fileName }}
              </div>
            </div>
          </div>
          <div v-else>暂无关联</div>
        </template>
        <template #fundsFile>
          <div style="width: 100%" v-if="fileData.data && fileData.data.fileListOne.length > 0">
            <div v-for="(item, index) in fileData.data.fileListOne" :key="index">
              <div style="cursor: pointer; color: #409eff" @click="openFile(item)">
                {{ item.fileName }}
              </div>
            </div>
          </div>
          <div v-else>暂无关联</div>
        </template>
      </byForm>
      <template #footer>
        <el-button @click="openFileDialog = false" size="default">取 消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import byTable from "@/components/byTable/index";
import useUserStore from "@/store/modules/user";
import { ref } from "vue";
import byForm from "@/components/byForm/index";
import FundsPDF from "@/components/PDF/fundsPDF.vue";

const loading = ref(false);
const sourceList = ref({
  data: [],
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 10,
    type: "",
    keyword: "",
    writeOffStatus: "",
    corporationId: "",
    departmentId: "",
    createUser: "",
    currency: "",
    beginTime: "",
    endTime: "",
    minAdvanceAmounts: undefined,
    maxAdvanceAmounts: undefined,
    paymentRemarks: "",
    paymentMethod: "",
    status: "",
    paymentStatus: "",
  },
});
const { proxy } = getCurrentInstance();
const fundsType = ref([]);
const userList = ref([]);
const companyData = ref([]);
const accountCurrency = ref([]);
const fundsPaymentMethod = ref([]);
const deptTreeData = ref([]);
const status = ref([
  {
    label: "审批中",
    value: "10",
  },
  {
    label: "驳回",
    value: "20",
  },
  {
    label: "审批通过",
    value: "30",
  },
]);
const paymentStatus = ref([
  {
    label: "已打款",
    value: "10",
  },
  {
    label: "部分打款",
    value: "15",
  },
  {
    label: "未打款",
    value: "20",
  },
]);
const selectConfig = computed(() => {
  return [
    {
      label: "类型",
      prop: "type",
      data: fundsType.value,
    },
    {
      label: "审批状态",
      prop: "status",
      data: status.value,
    },
    {
      label: "放款状态",
      prop: "paymentStatus",
      data: paymentStatus.value,
    },
  ];
});
const config = computed(() => {
  return [
    {
      attrs: {
        label: "归属公司",
        prop: "corporationName",
        width: 180,
      },
    },
    {
      attrs: {
        label: "归属部门",
        prop: "deptName",
        width: 140,
      },
    },
    {
      attrs: {
        label: "请款类型",
        prop: "type",
        width: 130,
        slot: "type",
      },
    },
    {
      attrs: {
        label: "请款人",
        prop: "userName",
        width: 120,
      },
    },
    {
      attrs: {
        label: "请款时间",
        prop: "createTime",
        width: 160,
      },
    },
    {
      attrs: {
        label: "请款金额",
        slot: "total",
        width: 120,
      },
    },
    {
      attrs: {
        label: "用款说明",
        prop: "paymentRemarks",
        "min-width": 180,
      },
    },
    {
      attrs: {
        label: "关联附件",
        slot: "file",
        width: 80,
        align: "left",
      },
    },
    {
      attrs: {
        label: "付款方式",
        prop: "paymentMethod",
        width: 120,
      },
      render(paymentMethod) {
        return proxy.dictValueLabel(paymentMethod, fundsPaymentMethod.value);
      },
    },
    {
      attrs: {
        label: "放款状态",
        prop: "accountPaymentStatus",
        width: 120,
      },
      render(status) {
        return proxy.dictValueLabel(status, paymentStatus.value);
      },
    },
    {
      attrs: {
        label: "付款账户",
        prop: "accountManagementName",
        width: 160,
      },
    },
    {
      attrs: {
        label: "审批状态",
        prop: "status",
        width: 120,
      },
      render(status) {
        return status == 10
          ? "审批中"
          : status == 20
          ? "驳回"
          : status == 30
          ? "审批通过"
          : "";
      },
    },
    {
      attrs: {
        label: "操作",
        width: "120",
        align: "center",
        fixed: "right",
      },
      renderHTML(row) {
        return [
          row.type == 1 && row.writeOffStatus == 0 && row.status == "30"
            ? {
                attrs: {
                  label: "核销",
                  type: "primary",
                  text: true,
                },
                el: "button",
                click() {
                  openModal(row);
                },
              }
            : {},
          {
            attrs: {
              label: "打印",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              clickPrint(row);
            },
          },
        ];
      },
    },
  ];
});
const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy
    .post("/accountRequestFunds/page", sourceList.value.pagination)
    .then((message) => {
      sourceList.value.data = message.rows;
      sourceList.value.pagination.total = message.total;
      setTimeout(() => {
        loading.value = false;
      }, 200);
    });
};
const openModal = (row = {}) => {
  const flowName = `${userInfo.nickName}的请款申请（发起）`;
  let query = {
    flowKey: "account_request_funds_flow",
    random: proxy.random(),
    flowName,
  };
  if (row.id) {
    query.advanceId = row.id;
    query.corporationId = row.corporationId;
  }
  proxy.$router.replace({
    path: "/platform_manage/process/processApproval",
    query,
  });
};
const userInfo = useUserStore().user;
const recursive = (data) => {
  data.map((item) => {
    item.label = item.deptName;
    item.id = item.corporationId;
    if (item.children) {
      recursive(item.children);
    } else {
      item.children = [];
    }
  });
};
const getDictData = () => {
  proxy
    .getDictOne(["founds_type", "funds_payment_method", "account_currency"])
    .then((res) => {
      fundsType.value = res["founds_type"].map((x) => ({
        label: x.dictValue,
        value: x.dictKey,
      }));
      fundsPaymentMethod.value = res["funds_payment_method"].map((x) => ({
        label: x.dictValue,
        value: x.dictKey,
      }));
      accountCurrency.value = res["account_currency"].map((x) => ({
        label: x.dictValue,
        value: x.dictKey,
      }));
    });
  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,
          };
        });
      }
    });
  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: userInfo.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);
          }
        }
      }
    });
};
getDictData();
getList();
const openPrint = ref(false);
const rowData = ref({});
const clickPrint = (row) => {
  rowData.value = row;
  openPrint.value = true;
};
const clickDownload = () => {
  proxy.getPdf("请款PDF文件");
};
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
});
const defaultProps = {
  children: "children",
  label: "deptName",
};
const openSearch = ref(false);
const formSearchConfig = computed(() => {
  return [
    {
      type: "select",
      prop: "corporationId",
      label: "归属公司",
      data: companyData.value,
      clearable: true,
      filterable: true,
    },
    {
      type: "slot",
      slotName: "departmentId",
      label: "归属部门",
      itemWidth: 50,
    },
    {
      type: "select",
      prop: "createUser",
      label: "请款人",
      data: userList.value,
      itemWidth: 50,
      clearable: true,
      filterable: true,
    },
    {
      type: "select",
      prop: "type",
      label: "请款类型",
      data: fundsType.value,
      clearable: true,
      filterable: true,
    },
    {
      type: "select",
      prop: "currency",
      label: "币种",
      data: accountCurrency.value,
      clearable: true,
      filterable: true,
    },
    {
      type: "slot",
      slotName: "time",
      label: "请款时间",
    },
    {
      type: "slot",
      slotName: "money",
      label: "请款金额",
    },
    {
      type: "input",
      itemType: "textarea",
      prop: "paymentRemarks",
      label: "用款说明",
    },
    {
      type: "select",
      prop: "paymentMethod",
      label: "付款方式",
      data: fundsPaymentMethod.value,
      clearable: true,
      itemWidth: 50,
      filterable: true,
    },
    {
      type: "input",
      prop: "oppositeAccountName",
      label: "对方账户",
      itemWidth: 50,
    },
    {
      type: "select",
      prop: "status",
      label: "流程状态",
      data: status.value,
      itemWidth: 50,
      clearable: true,
      filterable: true,
    },
    {
      type: "select",
      prop: "paymentStatus",
      label: "打款状态",
      data: paymentStatus.value,
      itemWidth: 50,
      clearable: true,
      filterable: true,
    },
  ];
});
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.minAdvanceAmounts &&
    sourceList.value.pagination.maxAdvanceAmounts &&
    Number(sourceList.value.pagination.minAdvanceAmounts) >
      Number(sourceList.value.pagination.maxAdvanceAmounts)
  ) {
    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.keyword = "";
  sourceList.value.pagination.pageNum = 1;
  getList();
};
const pushProcessApproval = (row) => {
  proxy.$router.push({
    path: "/platform_manage/process/processApproval",
    query: {
      flowKey: "account_request_funds_flow",
      id: row.flowInfoId,
      processType: 20,
      random: proxy.random(),
      flowName: "请款详情",
      businessId: row.id,
    },
  });
  return;
};
const printObj = ref({
  id: "pdfDom",
  popTitle: "",
  extraCss:
    "https://cdn.bootcdn.net/ajax/libs/animate.css/4.1.1/animate.compat.css, https://cdn.bootcdn.net/ajax/libs/hover.css/2.3.1/css/hover-min.css",
  extraHead: '<meta http-equiv="Content-Language"content="zh-cn"/>',
});

const fileData = reactive({
  data: {},
});
const fileConfig = computed(() => [
  {
    type: "title",
    title: "业务附件",
  },
  {
    type: "slot",
    slotName: "businessFile",
  },
  {
    type: "title",
    title: "打款附件",
  },
  {
    type: "slot",
    slotName: "fundsFile",
  },
]);
const openFileDialog = ref(false);
const handleOpenFile = (row) => {
  fileData.data = {
    fileList: [],
    fileListOne: [],
  };
  proxy
    .post("/fileInfo/getList", { businessIdList: [row.id] })
    .then((fileObj) => {
      if (fileObj[row.id] && fileObj[row.id].length > 0) {
        fileData.data.fileList = fileObj[row.id];
      }
    });
  proxy
    .post("/accountPayment/detail", { id: row.accountPaymentId })
    .then((res) => {
      let ids = [];
      if (
        res.accountPaymentRecordsList &&
        res.accountPaymentRecordsList.length > 0
      ) {
        ids = res.accountPaymentRecordsList.map((x) => x.id);
      }
      proxy
        .post("/fileInfo/getList", {
          businessIdList: [row.accountPaymentId, ...ids],
        })
        .then((fileObj) => {
          if (fileObj) {
            let arr = [];
            for (const key in fileObj) {
              if (fileObj[key]) {
                arr = [...arr, ...fileObj[key]];
              }
            }
            fileData.data.fileListOne = arr;
          }
        });
    });
  openFileDialog.value = true;
};
const openFile = (item) => {
  window.open(item.fileUrl, "_blank");
};
</script>

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