<template>
  <div style="width: 100%; padding: 0px 15px">
    <el-form :model="formData.data" :rules="rules" ref="formDom" label-position="top" :disabled="judgeStatus()">
      <div class="_t">基础信息</div>
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="归属公司" prop="corporationId">
            <el-select v-model="formData.data.corporationId" placeholder="请选择" filterable style="width: 100%">
              <el-option v-for="item in companyData" :label="item.name" :value="item.id"> </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="归属部门" prop="departmentId">
            <el-tree-select
              v-model="formData.data.departmentId"
              :data="deptTreeData"
              check-strictly
              :render-after-expand="false"
              node-key="deptId"
              style="width: 100%"
              :props="defaultProps" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="币种" prop="currency">
            <el-select v-model="formData.data.currency" placeholder="请选择" filterable style="width: 100%">
              <el-option v-for="item in currencyType" :label="item.dictValue" :value="item.dictKey"> </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="请款类型" prop="type">
            <el-select v-model="formData.data.type" placeholder="请选择" filterable style="width: 100%" @change="changeType">
              <el-option v-for="item in fundsType" :label="item.dictValue" :value="item.dictKey"> </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="formData.data.type === '3'">
          <el-form-item label="关联预支" prop="advanceId">
            <el-select v-model="formData.data.advanceId" placeholder="请选择" filterable style="width: 100%" @change="changeAdvanceId">
              <el-option v-for="item in advanceList" :label="item.createTime.substr(0, 10) + '  ' + item.currency + item.total" :value="item.id"> </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="formData.data.type === '3'">
          <el-form-item label="  ">
            <el-button type="primary" @click="clickPrint" text>查看</el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="用款时间" prop="paymentTime">
            <el-date-picker v-model="formData.data.paymentTime" type="datetime" placeholder="请选择" value-format="YYYY-MM-DD HH:mm:ss" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="用款说明" prop="paymentRemarks">
        <el-input v-model="formData.data.paymentRemarks" placeholder="请输入" type="textarea"> </el-input>
      </el-form-item>
      <el-form-item label="上传附件">
        <div style="width: 100%">
          <el-upload
            v-model:fileList="fileList"
            action="https://winfaster.obs.cn-south-1.myhuaweicloud.com"
            :data="uploadData"
            multiple
            :before-upload="handleBeforeUpload"
            :on-success="handleSuccess"
            :on-preview="onPreviewFile">
            <el-button>选择</el-button>
          </el-upload>
        </div>
      </el-form-item>
      <div class="_t">请款明细</div>
      <el-form-item>
        <el-button type="primary" @click="handleAddRow" v-if="formData.data.type !== '3'" style="margin: 10px 0"> 添加行 </el-button>
        <el-table :data="formData.data.accountRequestFundsDetailList">
          <el-table-column prop="count" label="费用类型" min-width="150">
            <template #default="{ row, $index }">
              <el-form-item :prop="'accountRequestFundsDetailList.' + $index + '.costType'" :rules="rules.costType" :inline-message="true">
                <el-select v-model="row.costType" placeholder="请选择" filterable style="width: 100%">
                  <el-option v-for="item in fundsCostType" :label="item.dictValue" :value="item.dictKey"> </el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="count" label="关联合同" min-width="150">
            <template #default="{ row, $index }">
              <el-form-item :prop="'accountRequestFundsDetailList.' + $index + '.contractId'" :rules="rules.contractId" :inline-message="true">
                <el-select v-model="row.contractId" placeholder="请选择" filterable style="width: 100%">
                  <el-option v-for="item in contractList" :label="item.code" :value="item.id"> </el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="count" label="款项说明" min-width="150">
            <template #default="{ row, $index }">
              <el-form-item :prop="'accountRequestFundsDetailList.' + $index + '.remarks'" :rules="rules.remarks" :inline-message="true">
                <el-input v-model="row.remarks" placeholder="请输入" type="textarea" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="advanceAmount" label="预支金额" width="120" v-if="formData.data.type === '3'" />
          <el-table-column prop="amount" :label="formData.data.type !== '3' ? '请款金额' : '核销金额'" min-width="150">
            <template #default="{ row, $index }">
              <el-form-item :prop="'accountRequestFundsDetailList.' + $index + '.amount'" :rules="rules.amount" :inline-message="true">
                <el-input-number
                  onmousewheel="return false;"
                  v-model="row.amount"
                  :precision="2"
                  :controls="false"
                  :min="0"
                  style="width: 100%"
                  @change="handleChangeAmount" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="zip" label="操作" width="100" v-if="formData.data.type !== '3'">
            <template #default="{ $index }">
              <el-button type="primary" link @click="handleRemove($index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-row :gutter="10">
        <el-col :span="6" v-if="formData.data.type === '3'">
          <el-form-item label="预支总额" prop="advanceAmounts">
            <el-input v-model="formData.data.advanceAmounts" placeholder="请输入" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item :label="formData.data.type !== '3' ? '请款总额' : '核销总额'" prop="total">
            <el-input v-model="formData.data.total" placeholder="请输入" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="单据数量" prop="quantity">
            <el-input-number
              onmousewheel="return false;"
              v-model="formData.data.quantity"
              placeholder="请输入"
              style="width: 100%"
              :precision="0"
              :controls="false"
              :min="0" />
          </el-form-item>
        </el-col>
      </el-row>
      <div class="_t">收付款信息</div>
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="付款方式" prop="paymentMethod">
            <el-select v-model="formData.data.paymentMethod" placeholder="请选择" filterable style="width: 100%">
              <el-option v-for="item in fundsPaymentMethod" :label="item.dictValue" :value="item.dictKey"> </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="付款账户" prop="accountManagementId">
            <el-select v-model="formData.data.accountManagementId" placeholder="请选择" filterable style="width: 100%">
              <el-option v-for="item in accountData" :label="item.alias" :value="item.id"> </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="户名" prop="name">
            <el-input v-model="formData.data.name" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="银行账号" prop="accountOpening">
            <el-input v-model="formData.data.accountOpening" placeholder="请输入" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="开户银行" prop="openingBank">
            <el-input v-model="formData.data.openingBank" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="联行号 / SWIFT Code" prop="interbankNumber">
            <el-input v-model="formData.data.interbankNumber" placeholder="请输入" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-dialog title="查看" v-if="openPrint" v-model="openPrint" width="840px">
      <div id="pdfDom" style="width: 776px">
        <div style="padding: 60px 30px; font-size: 12px !important; color: black">
          <div style="font-size: 16px; text-align: center; padding: 8px">
            <span>{{ dictDataEcho(printDetails.type, fundsType) }}审批单</span>
          </div>
          <div style="padding: 8px 0">
            <span>{{ printDetails.corporationName }}</span>
            <span style="padding-left: 32px">创建时间: {{ printDetails.createTime }}</span>
          </div>
          <div style="border: 1px solid black">
            <div style="display: flex; border-bottom: 1px solid black">
              <div style="width: 126px; border-right: 1px solid black; padding: 8px">创建人</div>
              <div style="width: calc(100% - 126px); padding: 8px">
                {{ dictValueLabel(printDetails.createUser, userList) }}
              </div>
            </div>
            <div style="display: flex; border-bottom: 1px solid black">
              <div style="width: 126px; border-right: 1px solid black; padding: 8px">创建人部门</div>
              <div style="width: calc(100% - 126px); padding: 8px">
                {{ printDetails.deptName }}
              </div>
            </div>
            <div style="display: flex; border-bottom: 1px solid black" v-if="printDetails.type !== '3'">
              <div style="width: 126px; border-right: 1px solid black; padding: 4px 8px; display: flex; align-items: center">费用明细</div>
              <div style="width: calc(100% - 126px)">
                <div style="border-bottom: 1px solid black; display: flex">
                  <div style="width: 80px; padding: 4px 8px; border-right: 1px solid black; text-align: center">费用类型</div>
                  <div style="width: 120px; padding: 4px 8px; border-right: 1px solid black; text-align: center">关联合同</div>
                  <div style="width: calc(100% - 360px); padding: 4px 8px; border-right: 1px solid black; text-align: center">款项说明</div>
                  <div style="width: 60px; padding: 4px 8px; border-right: 1px solid black; text-align: center">货币</div>
                  <div style="width: 100px; padding: 4px 8px; text-align: center">付款金额</div>
                </div>
                <template v-if="printDetails.accountRequestFundsDetailList && printDetails.accountRequestFundsDetailList.length > 0">
                  <div v-for="(item, index) in printDetails.accountRequestFundsDetailList" :key="index">
                    <div
                      :style="
                        index + 1 !== printDetails.accountRequestFundsDetailList.length ? 'border-bottom: 1px solid black;  display: flex' : ' display: flex'
                      ">
                      <div style="width: 80px; padding: 4px 8px; border-right: 1px solid black; text-align: center">
                        {{ dictDataEcho(item.costType, fundsCostType) }}
                      </div>
                      <div style="width: 120px; padding: 4px 8px; border-right: 1px solid black; display: flex; align-items: center">
                        {{ item.contractCode }}
                      </div>
                      <div style="width: calc(100% - 360px); padding: 4px 8px; border-right: 1px solid black; display: flex; align-items: center">
                        {{ item.remarks }}
                      </div>
                      <div style="width: 60px; padding: 4px 8px; border-right: 1px solid black; display: flex; align-items: center">
                        {{ dictDataEcho(printDetails.currency, currencyType) }}
                      </div>
                      <div style="width: 100px; padding: 4px 8px; display: flex; align-items: center">
                        {{ item.amount }}
                      </div>
                    </div>
                  </div>
                </template>
              </div>
            </div>
            <div style="display: flex; border-bottom: 1px solid black" v-else>
              <div style="width: 126px; border-right: 1px solid black; padding: 4px 8px; display: flex; align-items: center">费用明细</div>
              <div style="width: calc(100% - 126px)">
                <div style="border-bottom: 1px solid black; display: flex">
                  <div style="width: 80px; padding: 4px 8px; border-right: 1px solid black; text-align: center">费用类型</div>
                  <div style="width: 120px; padding: 4px 8px; border-right: 1px solid black; text-align: center">关联合同</div>
                  <div style="width: calc(100% - 420px); padding: 4px 8px; border-right: 1px solid black; text-align: center">款项说明</div>
                  <div style="width: 60px; padding: 4px 8px; border-right: 1px solid black; text-align: center">货币</div>
                  <div style="width: 80px; padding: 4px 8px; border-right: 1px solid black; text-align: center">预支金额</div>
                  <div style="width: 80px; padding: 4px 8px; text-align: center">付款金额</div>
                </div>
                <template v-if="printDetails.accountRequestFundsDetailList && printDetails.accountRequestFundsDetailList.length > 0">
                  <div v-for="(item, index) in printDetails.accountRequestFundsDetailList" :key="index">
                    <div
                      :style="
                        index + 1 !== printDetails.accountRequestFundsDetailList.length ? 'border-bottom: 1px solid black;  display: flex' : ' display: flex'
                      ">
                      <div style="width: 80px; padding: 4px 8px; border-right: 1px solid black; text-align: center">
                        {{ dictDataEcho(item.costType, fundsCostType) }}
                      </div>
                      <div style="width: 120px; padding: 4px 8px; border-right: 1px solid black; display: flex; align-items: center">
                        {{ item.contractCode }}
                      </div>
                      <div style="width: calc(100% - 420px); padding: 4px 8px; border-right: 1px solid black; display: flex; align-items: center">
                        {{ item.remarks }}
                      </div>
                      <div style="width: 60px; padding: 4px 8px; border-right: 1px solid black; display: flex; align-items: center">
                        {{ dictDataEcho(printDetails.currency, currencyType) }}
                      </div>
                      <div style="width: 80px; padding: 4px 8px; border-right: 1px solid black; display: flex; align-items: center">
                        {{ item.advanceAmount }}
                      </div>
                      <div style="width: 80px; padding: 4px 8px; display: flex; align-items: center">
                        {{ item.amount }}
                      </div>
                    </div>
                  </div>
                </template>
              </div>
            </div>
            <div style="display: flex; border-bottom: 1px solid black" v-if="printDetails.type !== '3'">
              <div style="width: 126px; border-right: 1px solid black; padding: 8px">总报销金额</div>
              <div style="width: calc(100% - 126px); display: flex">
                <div style="width: calc(100% - 100px); padding: 8px; border-right: 1px solid black">{{ NumberToChinese(computeMoney("amount")) }}</div>
                <div style="width: 100px; padding: 8px">{{ computeMoney("amount") }}</div>
              </div>
            </div>
            <div v-else>
              <div style="display: flex; border-bottom: 1px solid black">
                <div style="display: flex; border-bottom: 1px solid black">
                  <div style="width: 126px; border-right: 1px solid black; padding: 8px">核销总金额</div>
                  <div style="width: calc(100% - 126px); display: flex">
                    <div style="width: calc(100% - 100px); padding: 8px; border-right: 1px solid black">{{ NumberToChinese(computeMoney("amount")) }}</div>
                    <div style="width: 100px; padding: 8px">{{ computeMoney("amount") }}</div>
                  </div>
                </div>
                <div style="width: 126px; border-right: 1px solid black; padding: 8px">预支总金额</div>
                <div style="width: calc(100% - 126px); display: flex">
                  <div style="width: calc(100% - 100px); padding: 8px; border-right: 1px solid black">{{ NumberToChinese(computeMoney("advanceAmount")) }}</div>
                  <div style="width: 100px; padding: 8px">{{ computeMoney("advanceAmount") }}</div>
                </div>
              </div>
              <div style="display: flex; border-bottom: 1px solid black">
                <div style="width: 126px; border-right: 1px solid black; padding: 8px">差额 (核销 - 预支)</div>
                <div style="width: calc(100% - 126px); display: flex">
                  <div style="width: calc(100% - 100px); padding: 8px; border-right: 1px solid black">{{ NumberToChinese(computeBalance()) }}</div>
                  <div style="width: 100px; padding: 8px">{{ computeBalance() }}</div>
                </div>
              </div>
            </div>
            <div style="display: flex; border-bottom: 1px solid black">
              <div style="width: 126px; border-right: 1px solid black; padding: 8px">单据数量</div>
              <div style="width: calc(100% - 126px); padding: 8px">
                {{ printDetails.quantity }}
              </div>
            </div>
            <div style="display: flex; border-bottom: 1px solid black">
              <div style="width: 126px; border-right: 1px solid black; padding: 0 8px; display: flex; align-items: center">收款信息</div>
              <div style="width: calc(100% - 126px)">
                <div style="border-bottom: 1px solid black; display: flex">
                  <div style="width: 19%; padding: 0 8px; border-right: 1px solid black; text-align: center">支付方式</div>
                  <div style="width: 27%; padding: 0 8px; border-right: 1px solid black; text-align: center">收款方户名</div>
                  <div style="width: 27%; padding: 0 8px; border-right: 1px solid black; text-align: center">开户行</div>
                  <div style="width: 27%; padding: 0 8px; text-align: center">收款方账号</div>
                </div>
                <div style="display: flex">
                  <div style="width: 19%; padding: 0 8px; border-right: 1px solid black; display: flex; align-items: center">
                    {{ dictDataEcho(printDetails.paymentMethod, fundsPaymentMethod) }}
                  </div>
                  <div style="width: 27%; padding: 0 8px; border-right: 1px solid black; display: flex; align-items: center">
                    {{ printDetails.name }}
                  </div>
                  <div style="width: 27%; padding: 0 8px; border-right: 1px solid black; display: flex; align-items: center">
                    {{ printDetails.openingBank }}
                  </div>
                  <div style="width: 27%; padding: 0 8px; display: flex; align-items: center">
                    {{ printDetails.accountOpening }}
                  </div>
                </div>
              </div>
            </div>
            <div style="display: flex; border-bottom: 1px solid black">
              <div style="width: 126px; border-right: 1px solid black; padding: 8px">电子发票(PDF/JPG)</div>
              <div style="width: calc(100% - 126px); padding: 8px">{{ printDetails.electronicInvoiceText }}</div>
            </div>
            <div style="display: flex">
              <div style="width: 126px; border-right: 1px solid black; padding: 4px 8px; display: flex; align-items: center">审批流程</div>
              <div style="width: calc(100% - 126px)">
                <template v-if="printDetails.recordList && printDetails.recordList.length > 0">
                  <div v-for="(item, index) in printDetails.recordList" :key="index">
                    <div
                      :style="
                        index + 1 !== printDetails.recordList.length
                          ? 'border-bottom: 1px solid black; padding: 4px 8px; display: flex'
                          : 'padding: 4px 8px; display: flex'
                      ">
                      <div style="width: calc(100% - 120px); word-wrap: break-word">
                        <span>{{ item.nodeName }}: </span>
                        <span style="padding-left: 4px">{{ item.processedUser }}</span>
                        <span style="padding-left: 4px">{{ item.remark }}</span>
                      </div>
                      <div style="width: 120px">{{ item.processedDate }}</div>
                    </div>
                  </div>
                </template>
              </div>
            </div>
          </div>
          <div style="padding-top: 16px">
            <span>打印时间: {{ presentTime }}</span>
            <span style="padding-left: 32px">打印人: {{ useUserStore().user.nickName }}</span>
          </div>
        </div>
      </div>
      <template #footer>
        <el-button @click="openPrint = false" size="large">取消</el-button>
        <el-button type="primary" @click="clickDownload()" size="large">下载PDF</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ElMessage } from "element-plus";
import useUserStore from "@/store/modules/user";
import { useRoute } from "vue-router";
import moment from "moment";

const route = useRoute();
const { proxy } = getCurrentInstance();
const defaultProps = {
  children: "children",
  label: "deptName",
};
const userList = ref([]);
const formData = reactive({
  data: {
    paymentTime: "",
    accountRequestFundsDetailList: [],
    fileList: [],
  },
});
let rules = ref({
  corporationId: [{ required: true, message: "请选择归属公司", trigger: "change" }],
  departmentId: [{ required: true, message: "请选择归属部门", trigger: "change" }],
  type: [{ required: true, message: "请选择请款类型", trigger: "change" }],
  // paymentTime: [{ required: true, message: "请选择用款时间", trigger: "change" }],
  currency: [{ required: true, message: "请选择币种", trigger: "change" }],
  paymentMethod: [{ required: true, message: "请选择付款方式", trigger: "change" }],
  advanceId: [{ required: true, message: "请选择关联预支", trigger: "change" }],
  // accountManagementId: [
  //   { required: true, message: "请选择付款账号", trigger: "change" },
  // ],
  costType: [{ required: true, message: "请选择费用类型", trigger: "change" }],
  remarks: [{ required: true, message: "请输入款项说明", trigger: "blur" }],
  amount: [{ required: true, message: "请输入请款金额", trigger: "blur" }],
});

const handleAddRow = () => {
  formData.data.accountRequestFundsDetailList.push({
    costType: "",
    remarks: "",
    amount: undefined,
  });
};

const handleRemove = (index) => {
  formData.data.accountRequestFundsDetailList.splice(index, 1);
  handleChangeAmount();
};

// 提交方法
const formDom = ref(null);
const handleSubmit = async () => {
  let status = await formDom.value.validate();
  if (status) {
    if (fileList.value && fileList.value.length > 0) {
      for (let i = 0; i < fileList.value.length; i++) {
        if (fileList.value[i].raw.uploadState) {
          ElMessage("文件上传中,请稍后提交");
          return false;
        }
      }
      formData.data.fileList = fileList.value.map((item) => {
        return {
          id: item.raw.id,
          fileName: item.raw.fileName,
          fileUrl: item.raw.fileUrl,
          uploadState: item.raw.uploadState,
        };
      });
    } else {
      formData.data.fileList = [];
    }
    if (!(formData.data.accountRequestFundsDetailList.length > 0)) {
      ElMessage("请添加请款明细！");
      return false;
    }
    for (let i = 0; i < formData.data.accountRequestFundsDetailList.length; i++) {
      if (!formData.data.accountRequestFundsDetailList[i].amount || Number(formData.data.accountRequestFundsDetailList[i].amount) === 0) {
        ElMessage("请款金额不能为0");
        return false;
      }
    }
    return true;
  } else {
    setTimeout(() => {
      const errorDiv = document.getElementsByClassName("is-error");
      errorDiv[0].scrollIntoView();
    }, 0);
  }
  return status;
};
// 获取用户信息并赋默认值
const userInfo = useUserStore().user;
// const tenantId = "@福建宏星！#￥%……&*（）";
const tenantId = userInfo.tenantId;

watch(
  props.queryData,
  () => {
    if (props.queryData && (route.query.processType == 10 || route.query.processType == 20)) {
      for (var text in props.queryData) {
        formData.data[text] = props.queryData[text];
      }
      oldType.value = proxy.deepClone(formData.data.type);
      if (formData.data.fileList && formData.data.fileList.length > 0) {
        fileList.value = formData.data.fileList.map((item) => {
          return {
            raw: item,
            name: item.fileName,
            url: item.fileUrl,
          };
        });
      }
    }
  },
  {
    deep: true,
  }
);
onMounted(() => {
  formData.data.paymentTime = proxy.parseTime(new Date());
});
const companyData = ref([]);
const accountData = ref([]);
const deptTreeData = ref([]);
const fundsType = ref([]);
const fundsCostType = ref([]);
const fundsPaymentMethod = ref([]);
const currencyType = ref([]);
const advanceList = ref([]);
const contractList = ref([]);
const getDictData = () => {
  // 获取归属公司数据
  proxy.post("/corporation/page", { pageNum: 1, pageSize: 9999 }).then((res) => {
    companyData.value = res.rows;
  });
  // 账户数据
  proxy.post("/accountManagement/page", { pageNum: 1, pageSize: 9999 }).then((res) => {
    accountData.value = res.rows;
  });
  // 关联合同
  proxy.post("/contract/page", { pageNum: 1, pageSize: 9999 }).then((res) => {
    contractList.value = res.rows;
  });
  // 部门树
  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);
          }
        }
      }
    });
  // 请款类型数据
  proxy
    .post("/dictTenantData/page", {
      pageNum: 1,
      pageSize: 999,
      tenantId: tenantId,
      dictCode: "founds_type",
    })
    .then((res) => {
      fundsType.value = res.rows;
    });
  // 请款费用类型数据
  proxy
    .post("/dictTenantData/page", {
      pageNum: 1,
      pageSize: 999,
      tenantId: tenantId,
      dictCode: "funds_cost_type",
    })
    .then((res) => {
      fundsCostType.value = res.rows;
    });
  // 请款付款方式数据
  proxy
    .post("/dictTenantData/page", {
      pageNum: 1,
      pageSize: 999,
      tenantId: tenantId,
      dictCode: "funds_payment_method",
    })
    .then((res) => {
      fundsPaymentMethod.value = res.rows;
    });
  // 币种数据
  proxy
    .post("/dictTenantData/page", {
      pageNum: 1,
      pageSize: 999,
      tenantId: tenantId,
      dictCode: "account_currency",
    })
    .then((res) => {
      currencyType.value = res.rows;
    });
  proxy
    .post("/accountRequestFunds/page", {
      pageNum: 1,
      pageSize: 999,
      type: "1",
      writeOffStatus: "0",
    })
    .then((res) => {
      advanceList.value = res.rows;
    });
  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,
          };
        });
      }
    });
};
getDictData();
const recursive = (data) => {
  data.map((item) => {
    item.label = item.deptName;
    item.id = item.corporationId;
    if (item.children) {
      recursive(item.children);
    } else {
      item.children = [];
    }
  });
};
// 接收父组件的传值
const props = defineProps({
  queryData: String,
});
// 计算请款总金额
const handleChangeAmount = () => {
  let sum = 0;
  for (let i = 0; i < formData.data.accountRequestFundsDetailList.length; i++) {
    const e = formData.data.accountRequestFundsDetailList[i];
    if (e.amount) {
      sum = Number(parseFloat(Number(sum) + Number(e.amount)).toFixed(2))
    }
  }
  formData.data.total = sum;
};
// 上传附件
const uploadData = ref({});
const fileList = ref([]);
const handleBeforeUpload = async (file) => {
  const res = await proxy.post("/fileInfo/getSing", { fileName: file.name });
  uploadData.value = res.uploadBody;
  file.id = res.id;
  file.fileName = res.fileName;
  file.fileUrl = res.fileUrl;
  file.uploadState = true;
  return true;
};
const handleSuccess = (any, UploadFile) => {
  UploadFile.raw.uploadState = false;
};
const onPreviewFile = (file) => {
  window.open(file.raw.fileUrl, "_blank");
};
const getFormData = () => {
  return formData.data;
};
// 向父组件暴露
defineExpose({
  getFormData,
  handleSubmit,
});
const judgeStatus = () => {
  if (props.queryData.recordList && props.queryData.recordList.length > 0) {
    let data = props.queryData.recordList.filter((item) => item.status === 2 && item.nodeType !== 1);
    if (data && data.length > 0) {
      return true;
    }
  }
  return false;
};
const oldType = ref("");
const changeType = () => {
  if (formData.data.type === "3" || oldType.value === "3") {
    for (var text in formData.data) {
      if (text === "advanceId") {
        formData.data.advanceId = "";
      } else if (text === "corporationId") {
        formData.data.corporationId = proxy.deepClone(formData.data.corporationId);
      } else if (text === "type") {
        formData.data.type = proxy.deepClone(formData.data.type);
      } else if (text === "paymentTime") {
        formData.data.paymentTime = proxy.deepClone(formData.data.paymentTime);
      } else if (text === "accountRequestFundsDetailList") {
        formData.data.accountRequestFundsDetailList = [];
      } else if (text === "fileList") {
        formData.data.fileList = [];
      } else {
        delete formData.data[text];
      }
    }
  }
  oldType.value = proxy.deepClone(formData.data.type);
};
const openPrint = ref(false);
const printDetails = ref({});
const presentTime = ref("");
const changeAdvanceId = (val) => {
  if (val) {
    proxy.post("/accountRequestFunds/detail", { id: val }).then((res) => {
      printDetails.value = res;
      if (res.flowInfoId) {
        proxy.post("/flowExample/getApprovalRecord", { id: res.flowInfoId }).then((record) => {
          printDetails.value.recordList = record.recordList;
        });
      }
      formData.data.departmentId = res.departmentId;
      formData.data.currency = res.currency;
      formData.data.paymentRemarks = res.paymentRemarks;
      proxy.post("/fileInfo/getList", { businessIdList: [val] }).then((resFile) => {
        formData.data.fileList = resFile[val] || [];
        if (formData.data.fileList && formData.data.fileList.length > 0) {
          fileList.value = formData.data.fileList.map((item) => {
            return {
              raw: item,
              name: item.fileName,
              url: item.fileUrl,
            };
          });
          let electronicInvoiceText = "";
          for (let i = 0; i < resFile[val].length; i++) {
            if (i === 0) {
              electronicInvoiceText = resFile[val][0].fileName;
            } else {
              electronicInvoiceText = electronicInvoiceText + ", " + resFile[val][i].fileName;
            }
          }
          printDetails.value.electronicInvoiceText = electronicInvoiceText;
        }
      });
      formData.data.accountRequestFundsDetailList = res.accountRequestFundsDetailList.map((item) => {
        return {
          costType: item.costType,
          amount: item.amount,
          contractId: item.contractId,
          advanceAmount: item.amount,
          remarks: item.remarks,
        };
      });
      handleChangeAmount();
      formData.data.advanceAmounts = res.total;
      formData.data.quantity = res.quantity;
      formData.data.paymentMethod = res.paymentMethod;
      formData.data.accountManagementId = res.accountManagementId;
      formData.data.name = res.name;
      formData.data.accountOpening = res.accountOpening;
      formData.data.openingBank = res.openingBank;
      formData.data.interbankNumber = res.interbankNumber;
    });
  }
};
const clickDownload = () => {
  proxy.getPdf("请款PDF文件");
};
const clickPrint = () => {
  if (formData.data.advanceId) {
    presentTime.value = moment().format("yyyy-MM-DD HH:mm:ss");
    openPrint.value = true;
  } else {
    ElMessage("请选择关联预支");
  }
};
const computeMoney = (label) => {
  let amount = 0;
  if (printDetails.value.accountRequestFundsDetailList && printDetails.value.accountRequestFundsDetailList.length > 0) {
    for (let i = 0; i < printDetails.value.accountRequestFundsDetailList.length; i++) {
      if (printDetails.value.accountRequestFundsDetailList[i][label]) {
        amount = Number(parseFloat(Number(amount) + Number(printDetails.value.accountRequestFundsDetailList[i][label])).toFixed(2));
      }
    }
  }
  return amount;
};
const toDx = (n) => {
  //阿拉伯数字转换函数
  switch (n) {
    case "0":
      return "零";
    case "1":
      return "壹";
    case "2":
      return "贰";
    case "3":
      return "叁";
    case "4":
      return "肆";
    case "5":
      return "伍";
    case "6":
      return "陆";
    case "7":
      return "柒";
    case "8":
      return "捌";
    case "9":
      return "玖";
  }
};
const NumberToChinese = (m) => {
  let unit = ["仟", "佰", "拾", "", "仟", "佰", "拾", "", "角", "分", "厘"];
  m *= 1000;
  m = Number(parseFloat(m).toFixed(0));
  m += "";
  var x = m.length;
  var result = "";
  for (var i = 0; i < x; i++) {
    if (i == 3) {
      result = "元" + result;
    } else if (i == 7) {
      result = "万" + result;
    }
    if (m.charAt(x - i - 1) == 0) {
      if (i != 0 && i != 1 && i != 2) {
        if (result.charAt(0) != "零" && result.charAt(0) != "元" && result.charAt(0) != "万") {
          result = "零" + result;
        }
      }
      continue;
    }
    result = toDx(m.charAt(x - i - 1)) + unit[unit.length - i - 1] + result;
  }
  result += result.charAt(result.length - 1) == "元" ? "整" : "";
  return result;
};
const computeBalance = () => {
  let balance = 0;
  let advanceAmount = computeMoney("advanceAmount");
  let amount = computeMoney("amount");
  if (amount) {
    balance = Number(amount);
  }
  if (advanceAmount) {
    balance = Number(parseFloat(Number(balance) - Number(advanceAmount)).toFixed(2));
  }
  return balance;
};
</script>

<style lang="scss" scoped>
._t {
  margin-bottom: 5px;
  font-size: 14px;
}
::v-deep(.el-input-number .el-input__inner) {
  text-align: left;
}
</style>
