<template>
  <!-- 添加或修改项目信息对话框 -->
  <div class="el-drawer__wrapper">
    <el-drawer :title="title" v-model="visible" direction="rtl" size="100%">
      <div class="page-container form-container">
        <div class="form-btns-container">
          <span class="title-label"><el-icon>
              <Document />
            </el-icon>
            收款信息</span>

          <el-button v-if="editStatus" type="primary" size="small" icon="Finished" @click="submitForm">保存</el-button>
          <el-button v-show="form.status == 1 && auth.hasPermi('business:collection:return')" type="warning" size="small" icon="Finished" @click="returnZero"
           >退回</el-button>
          <el-button v-show="(!editStatus && form.verifyDate == null)&& auth.hasPermi('business:collection:edit') " type="warning" size="small" icon="Edit"
            @click="editStatus = true">修改</el-button>
          <el-button v-if="form.id && editStatus" type="info" size="small" icon="Close"
            @click="reForm()">取消修改</el-button>
          <el-button v-show="(form.id && !editStatus && form.verifyDate == null)
          && auth.hasPermi('business:collection:verify')"
           type="primary" size="small" icon="Check"
            @click="verifyHandler">收款审核</el-button>

          <div class="screen-btn" @click="handleScreen">
            <template v-if="!isFullscreen">
              <i class="fa fa-window-maximize" aria-hidden="true" />
              <!-- <span>全屏</span> -->
            </template>
            <template v-else>
              <i class="fa fa-window-restore" aria-hidden="true" />
              <!-- <span>还原</span> -->
            </template>
          </div>
          <div class="close-btn" @click="cancel">
            <i class="fa fa-times" aria-hidden="true" />
            <!-- <span>关闭</span> -->
          </div>
        </div>
        <div class="Y-scrollbar" style="
            position: absolute;
            top: 32px;
            bottom: 0;
            width: 100%;
            overflow: auto;
          "></div>
        <el-form ref="orderRef" class="master-container" size="small" :model="form" :rules="rules" label-width="100px">
          <el-row :gutter="30">
            <el-col :span="6">
              <el-form-item label="收款流水号：">
                <el-input v-if="editStatus" v-model.trim="form.flowNo" disabled size="small" type="text"
                  placeholder="收款流水号 点击保存时自动生成" :clearable="true" />
                <span v-else>{{ form.flowNo }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="收款账户：" prop="subsidiaryName">
                <el-autocomplete v-if="editStatus" :fetch-suggestions="querySearchAccountAsync" :trigger-on-focus="true"
                  v-model="form.subsidiaryName" placeholder="请输入收款账户" style="width: 100%" popper-class="my-autocomplete"
                  @select="handleSelectAccount">
                  <template #default="{ item }">
                    <div style="
                        display: flex;
                        flex-direction: row;
                        justify-content: space-between;
                      ">
                      <div class="name" style="font-size: 12px">
                        {{ item.name }}
                      </div>
                      <span class="code" style="font-size: 10px; color: darkgrey">{{ item.code }}</span>
                    </div>
                  </template>
                </el-autocomplete>
                <span v-else>{{ form.subsidiaryName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="收款开户行：" prop="subsidiaryBankName">
                <el-input v-if="editStatus" v-model.trim="form.subsidiaryBankName" size="small" type="text"
                  placeholder="开户行" :clearable="true" :readonly="true" />
                <span v-else>{{ form.subsidiaryBankName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="收款账号：" prop="subsidiaryBankAccount">
                <el-input v-if="editStatus" v-model.trim="form.subsidiaryBankAccount" size="small" type="text"
                  placeholder="账号" :clearable="true" :readonly="true" />
                <span v-else>{{ form.subsidiaryBankAccount }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="付款名称：" prop="applyName">
                <el-input v-if="editStatus" v-model.trim="form.applyName" size="small" type="text" placeholder="付款名称"
                  :clearable="true" />
                <span v-else>{{ form.applyName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="付款账号：" prop="appyAccount">
                <el-input v-if="editStatus" v-model.trim="form.appyAccount" size="small" type="text" placeholder="付款账号"
                  :clearable="true" />
                <span v-else>{{ form.appyAccount }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="到账日期：" prop="arriveDate">
                <el-date-picker v-if="editStatus" v-model.trim="form.arriveDate" size="small" :clearable="true"
                  style="width: 100%" format="YYYY-MM-DD" value-format="YYYY-MM-DD" align="center" type="date"
                  placeholder="到账日期" />
                <span v-else>{{ form.arriveDate }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="到账时间：" prop="arriveTime">
                <el-time-select v-if="editStatus" style="width: 100%" v-model.trim="form.arriveTime"
                  :picker-options="timeOptions" placeholder="选择时间" />
                <span v-else>{{ form.arriveTime }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="客户名称：" prop="companyName">
                <el-link :underline="false" type="primary" @click="handleInfo(form)">{{ form.companyName }}</el-link>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="合同编号：" prop="remark">
                <el-link v-if="auth.hasPermi('business:archive:order:cwview')" :underline="false" type="primary" @click="handleContract(form)">{{ form.contractNo }}</el-link>
                <span v-else>{{form.contractNo}}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="应收款金额：" prop="remark">
                <span>{{ rowNum(form.contractAmount) }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="未收款金额：" prop="remark">
                <span>{{ rowNum(form.nonpaymentAmount) }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="收款金额：" required>
                <el-input-number v-if="editStatus" v-model.trim="form.arriveAmount" size="small" placeholder="收款金额"
                  :clearable="true" disabled :precision="2" controls-position="right" :controls="false" @change="amountChange" />
                <span v-else>{{ rowNum(form.arriveAmount) }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="订单备注：">
                <span style="word-break: break-all">{{
                  form.orderRemark
                  }}</span>
              </el-form-item>
            </el-col>
            <el-col v-if="form.status === 1" :span="6">
              <el-form-item label="审核意见：" required>
                <span>{{ form.verifyComment }}</span>
              </el-form-item>
            </el-col>
            <el-col v-if="form.status === 2" :span="6">
              <el-form-item label="驳回原因：" required>
                <span>{{ form.verifyComment }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="收款备注：">
                <el-input v-if="editStatus" v-model.trim="form.remark" size="small" type="text" placeholder="收款备注"
                  :clearable="true" />
                <span v-else style="word-break: break-all">{{
                  form.remark
                  }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="签单类型:" prop="isNew">
                <el-radio-group v-model="form.isNew" disabled v-if="editStatus">
                  <el-radio :label="0">新签</el-radio>
                  <el-radio :label="1">续签</el-radio>
                </el-radio-group>
                <span v-else>{{ form.isNew === 0 ? '新签' : '续签' }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="是否为项目:" prop="isProject">
                <el-radio-group v-model="form.isProject" v-if="editStatus">
                  <el-radio :label="0">项目</el-radio>
                  <el-radio :label="1">非项目</el-radio>
                </el-radio-group>
                <span v-else>{{ form.isProject !== undefined && form.isProject !== null ? (form.isProject === 0 ? '项目' :
                  '非项目') : '' }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="项目编号:" prop="projectNo">
                <el-input v-if="editStatus" v-model.trim="form.projectNo" size="small" type="text" placeholder="项目编号"
                  :clearable="true" />
                <span v-else>{{ form.projectNo }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="项目名称:" prop="projectName">
                <el-input v-if="editStatus" v-model.trim="form.projectName" size="small" type="text" placeholder="项目名称"
                  :clearable="true" />
                <span v-else>{{ form.projectName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="项目主体名称:" prop="projectMainName">
                <el-input v-if="editStatus" v-model.trim="form.projectMainName" size="small" type="text"
                  placeholder="项目主体名称" :clearable="true" />
                <span v-else>{{ form.projectMainName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="审核时间" prop="verifyDate">
                <span>{{ form.verifyDate }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="制表时间" prop="createTime">
                <span>{{ form.createTime }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="申请人：">
                <span>{{ form.applierName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="甲方：">
                <span>{{ form.boss }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="乙方：">
                <span>{{ form.party }}</span>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div class="details-container">
          <el-row :gutter="2" style="height: 100%">
            <el-col :span="18">
              <div class="details-head">
                <div class="title">
                  <i class="fa fa-th-list" aria-hidden="true" /> 收款明细
                </div>
              </div>
              <div class="details-body">
                <el-table ref="filesTable" :data="form.details" size="small" height="100%" border
                  header-row-class-name="list-header-row" highlight-current-row>
                  <el-table-column type="index" label="序号" width="47" align="center" />
                  <el-table-column label="任务名称" prop="taskTypeName" align="center" show-overflow-tooltip>

                  </el-table-column>
                  <el-table-column label="说明" prop="explain" align="center" show-overflow-tooltip />


                  <el-table-column label="任务金额" prop="amount" width="150" header-align="center" align="right">
                    <template #default="scope">
                      <span>{{ rowNum(scope.row.amount) }}</span>
                    </template>
                  </el-table-column>
           
                  <el-table-column label="已收款金额" prop="arrived" width="150" align="right" header-align="center">
                    <template #default="scope">
                      <span>{{ rowNum(scope.row.arrived) }}</span>
                    </template>
                  </el-table-column>

                  <el-table-column label="待收款金额" width="150" align="center">
                    <template #default="scope">
                      {{
                      rowNum((Number(scope.row.amount) || 0) - (Number(scope.row.arrived) || 0))
                      }}

                    </template>
                  </el-table-column>
                  <el-table-column label="本次收款金额" prop="arriveAmount" width="150" header-align="center" align="right">
                    <template #default="scope">
                      <template v-if="editStatus">
                        <el-input-number v-model="scope.row.arriveAmount" size="small" :min="0.0" placeholder="本次收款金额"
                          :precision="2" :controls="false" style="width: 100%" @change="
                            (arg) =>
                              amountChangeHandler(
                                arg,
                                scope.row,
                                'arriveAmount'
                              )
                          " />
                      </template>
                      <template v-else>{{
                        rowNum(scope.row.arriveAmount)
                        }}</template>
                    </template>
                  </el-table-column>


                  <el-table-column label="备注" prop="remark" width="250" align="center">
                    <template #default="scope">
                      <template v-if="editStatus">
                        <el-input v-model="scope.row.remark" placeholder="备注" size="small" />
                      </template>
                      <template v-else>{{ scope.row.remark }}</template>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="details-head">
                <div class="title">
                  <i class="fa fa-th-list" aria-hidden="true" />
                  <span style="color: red"><i style="color: red" /> *</span>
                </div>
                <el-upload v-if="editStatus" action="#" :http-request="upload" :with-credentials="true"
                  :show-file-list="false" multiple>
                  <el-button size="small" type="primary" icon="Upload">点击上传</el-button>
                </el-upload>
              </div>
              <div class="details-body">
                <el-table ref="filesTable" :data="form.files" size="small" height="100%" border
                  header-row-class-name="list-header-row" highlight-current-row>
                  <el-table-column type="index" label="序号" width="47" align="center" />
                  <el-table-column label="文件名" prop="originalFileName" align="center" min-width="200"
                    show-overflow-tooltip>
                    <template #default="scope">
                      <el-button size="small" type="primary" link @click="openFile(scope.row)">{{
                        scope.row.originalFileName }}</el-button>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" min-width="60" align="center">
                    <template #default="scope">
                      <div v-if="editStatus">
                        <el-button size="small" link type="danger"
                          @click="handlerDelAttach(scope.row, scope.$index)">删除</el-button>
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
    </el-drawer>
    <el-dialog title="审核详情" v-model="rejectOpen" width="500px" append-to-body draggable :close-on-click-modal="false">
      <el-form ref="dictRef" :model="form" label-width="100" size="small">
        <el-form-item label="审核状态">
          <el-select style="width: 100%" v-model.trim="form.verifyStatus" placeholder="请选择" size="small">
            <el-option v-for="i in verified" :key="i.value" :label="i.label" :value="i.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="确认所属时间" required>
          <el-date-picker style="width: 100%" v-model.trim="form.actuallyDate" size="small" :clearable="true"
            format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" align="center" type="datetime"
            placeholder="确认所属时间" />
        </el-form-item>
        <el-form-item :label="form.verifyStatus === 2 ? '驳回原因' : '审核意见'" :prop="verifyComment">
          <el-input type="textarea" maxlength="200" show-word-limit v-model.trim="form.verifyComment" :rows="3"
            placeholder="请输入审核意见" />
        </el-form-item>
        <el-form-item label="附件">
          <el-upload action="#" :http-request="upload2" :with-credentials="true" :show-file-list="false" multiple
            :limit="5">
            <el-button size="small" type="primary" icon="Upload">点击上传</el-button>
          </el-upload>
          <el-table ref="dbTable" :data="form.evidenceFiles" size="small" border header-row-class-name="list-header-row"
            row-class-name="list-row">
            <el-table-column label="文件名" prop="originalFileName" align="center" show-overflow-tooltip>
              <template #default="scope">
                <el-button size="small" type="text" @click="openFile(scope.row)">{{
                  scope.row.originalFileName == ""
                  ? "打开文件"
                  : scope.row.originalFileName
                  }}</el-button>
              </template>
            </el-table-column>
            <!-- <el-table-column
              label="文件类型"
              width="80"
              prop="fileType"
              align="center"
            /> -->
            <el-table-column label="操作" width="80" prop="fileType" align="center">
              <template #default="scope">
                <el-button size="small" link type="danger"
                  @click="handlerEportFilesDel(scope.row, scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" icon="Finished" size="small" @click="verifyUpload()">确 定</el-button>
          <el-button icon="Close" size="small" @click="rejectCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <company-form ref="companyRef" :get-list="getList"></company-form>
    <contract-form ref="contractRef" :get-list="getList" />
  </div>
</template>
<script setup>
  import { uploadFile } from "@/api/tool/file";
  import auth from "@/plugins/auth";
  // import {
  //   getOrder,
  //   initTaskTypes,
  //   addOrder,
  //   updateOrder,
  //   verifyOrder,
  //   alterOrder,
  //   dissolutionOrder,
  // } from "@/api/business/crm/contract";
  import {
    listContract,
    listAccount,
    getCollection,
    getCollectionByContract,
    saveCollection,
    verifyCollection, setCollectionZero, getCollectionDetail,
  } from "@/api/business/financial/collection";
  import { listSource } from "@/api/settings/source";
  import { listCompany } from "@/api/business/crm/company";
  import { listUser } from "@/api/system/user";
  import CustomerFormCom from "@/components/CustomerFormCom";
  import { formatDate } from "@/utils/index";
  import companyForm from "@/views/business/crm/company/formView.vue";
  import contractForm from "@/views/business/crm/order/formView.vue";
  import { ref } from "vue";

  import useUserStore from "@/store/modules/user";
  import match from "@/utils/match";
  const { proxy } = getCurrentInstance();
  const baseUrl = import.meta.env.VITE_APP_BASE_API;

  /** 父组件传参 */
  const props = defineProps({
    getList: {
      type: Function,
      default: () => { },
    },
  });
  const { getList } = toRefs(props);
  /** 字典数组区 */
  const { virtual_address } = proxy.useDict("virtual_address");
  /** 表单抽屉 页变量 */
  const title = ref("");
  const loading = ref(false);
  const multiple = ref(true);
  const visible = ref(false);
  const editStatus = ref(false);
  const sourceCategories = ref([]);
  const type = ref("");

  const rejectOpen = ref(false);

  const detailEmpty = {
    id: null,
    taskTypeName: "",
    taskTypeId: null,
    serviceNum: undefined,
    freeNum: undefined,
    price: undefined,
    amount: undefined,
    addressStyle: undefined,
    address: undefined,
    fictionAddressId: undefined,
    tenantId: undefined,
    province: "",
    city: "",
    district: "",
    addressStyle: 1,
    provinceId: undefined,
    processes: [],
    defaultProcesses: [],
  };
  const provinces = ref(proxy.region.getProvinces());
  provinces.value.unshift({ code: "", name: "全部" });
  const cities = ref([]);
  const districts = ref([]);

  const contractEmpty = {
    serviceType: 1,
    contractType: 0,
    formDate: formatDate(new Date(), "YYYY-MM-DD"),
    signerId: useUserStore().user.userId,
    signerName: useUserStore().user.nickName,
    files: [],
  };
  const isFullscreen = ref(false);
  const webHost = import.meta.env.VITE_APP_BASE_API;
  const data = reactive({
    form: {},
    rules: {},
    timeOptions: { start: "08:30", step: "00:15", end: "18:30" },
    verified: [
      {
        value: 0,
        label: "未审核",
      },
      {
        value: 1,
        label: "通过",
      },
      {
        value: 2,
        label: "不通过",
      },
    ],
  });
  const { form, rules, timeOptions, verified } = toRefs(data);
  /***********************  方法区  ****************************/
  /** 打开抽屉 */
  function open(id) {
    reset();
    visible.value = true;
    editStatus.value = true;
    getCollection(id).then((res) => {
      form.value = res.data;
      form.value.actuallyDate = null;
      console.log("form23", form.value);
      editStatus.value = false;
    });
  }

  /** 取消按钮 */
  function cancel() {
    visible.value = false;
    reset();
  }
  function handleInfo(row) {
    proxy.$refs.companyRef.open(row.companyId);
  }
  function handleContract() {
    proxy.$refs.contractRef.open(form.value.contractId);
  }
  // 数字格式化
  function rowNum(num) {
    if (!num) {
      return;
    }
    num = num.toLocaleString(); // 3,000
    if (num.indexOf(".") == -1) {
      num = num + ".00"; //3,000.00
    } else if (num.charAt(num.indexOf(".") == num.length - 2)) {
      num = num;
    }
    return num;
  }

  /** 表单重置 */
  function reset() {
    form.value = JSON.parse(JSON.stringify(contractEmpty));
    console.log("重置表单", form.value);
    type.value = "";
    // console.log(form)
    // proxy.resetForm("orderRef");
  }

  function returnZero() {
    proxy.$modal
      .confirm("是否确认退回")
      .then(function () {
        form.value.status = 0;
        return setCollectionZero(form.value.id)
      })
      .then(() => {
        visible.value = false;
        getList.value();
        proxy.$modal.msgSuccess("退回成功");
      })
      .catch(() => { });
  }

  /** 全屏缩放 */
  function handleScreen() {
    const dom = document.querySelector(
      ".list-container > .el-drawer__wrapper > .el-overlay"
    );
    isFullscreen.value = !isFullscreen.value;
    dom.style.position = isFullscreen.value ? "fixed" : "absolute";
  }

  /** 提交按钮 */
  async function submitForm() {
    // 应收款金额  和明细比较 如果大于应收内容 提示 当前的合同提过的收款申请总金额超过当前合同金额，不可提交，如有需要请跟财务人员联系
    const res = await getCollectionDetail(form.value.contractId);
    if (res.data == null || res.data.length == 0) {
      const amount = form.value.arriveAmount;
      if (amount > form.value.contractAmount) {
        proxy.$modal.msgError("当前的合同提过的收款申请总金额超过当前合同金额，不可提交，请联系财务人员。");
        return false;
      }
      for (let i = 0; i < form.value.details.length; i++) {
        let item = form.value.details[i];
        const Amount = (Number(item.countAmount) || 0)*1000 - (Number(item.reviewAmount) || 0)*1000;
        if ( item.arriveAmount + (Amount/1000) > (Number(item.amount) || 0)) {
          proxy.$modal.msgError("当前的" + item.taskTypeName + "本次收款金额超过系统内存在的收款金额，不可提交，请联系财务人员。");
          return false;
        }
      }
    } else {
      const countAmount = res.data.map((item) => item.status === 1&&item.arriveAmount).reduce((total, number) => {
        return total + number;
      });
      const amount = countAmount + form.value.arriveAmount;
      if (amount > form.value.contractAmount) {
        proxy.$modal.msgError("当前的合同提过的收款申请总金额超过当前合同金额，不可提交，请联系财务人员。");
        return false;
      }
      for (let i = 0; i < form.value.details.length; i++) {
        let item = form.value.details[i];
        let countAmount = 0;
        for (let j = 0; j < res.data.length; j++) {
          let match = res.data[j];
          if (item.taskTypeId == match.taskTypeId) {
            countAmount += match.arriveAmount;
          }
        }
        if (item.amount < match.add(item.arriveAmount)) {
          proxy.$modal.msgError("当前的" + item.taskTypeName + "收款申请总金额超过当前服务金额，不可提交，请联系财务人员。");
          return false;
        }
       // const amount = (rowNum((Number(item.amount) || 0) - (Number(item.arrived) || 0))) < (Number(item.arriveAmount) || 0)
        const diff = (Number(item.amount) || 0)*1000 - (Number(item.arrived) || 0)*1000;
        const Amount = (Number(item.countAmount) || 0)*1000 - (Number(item.reviewAmount) || 0)*1000;
        if ( item.arriveAmount + (Amount/1000) > (Number(item.amount) || 0)) {
          proxy.$modal.msgError("当前的" + item.taskTypeName + "本次收款金额超过系统内存在的收款金额，不可提交，请联系财务人员。");
          return false;
        }
      }
    }

    if (form.value.arriveAmount > form.value.contractAmount) {
      proxy.$modal.msgError("实际收款金额不能大于合同收款金额");
      return;
    }
    proxy.$refs["orderRef"].validate((valid) => {
      if (valid && detailValid()) {
        const formValue = form.value;
        saveCollection(formValue).then((res) => {
          open(form.value.id);
          getList.value();
          proxy.$modal.msgSuccess("保存成功");
        });
      }
    });
  }

  function detailValid() {
    // 20240109 暂时附件非必填。
    // if (form.value.files.length === 0) {
    //   proxy.$modal.msgError("收款附件为空");
    //   return false;
    // }
    return true;
  }

  /** 查询表单信息  */
  function getForm() {
    loading.value = true;
    getOrder(form.value.id).then((response) => {
      loading.value = false;
      form.value = response.data;
    });
  }
  function handleServiceTypeClick(tab) {
    computedService();
  }

  function verifyHandler() {
    // proxy.$modal
    //   .confirm("是否确认审核?")
    //   .then((_) => {
    //     verifyUpload(1);
    //   })
    //   .catch((_) => {
    //     proxy.$modal.msg("取消审核");
    //   });
    rejectOpen.value = true;
  }

  function rejectHandler() {
    rejectOpen.value = true;
  }

  function rejectCancel() {
    rejectOpen.value = false;
    rejectReset();
  }

  function rejectReset() { }

  function rejectSubmitHandler() {
    if (form.value.verifyRemark === "" || form.value.verifyRemark == null) {
      proxy.$modal.msgError("请填写驳回原因");
      return;
    }
  }

  async function verifyUpload() {
    // const formValue = proxy.deepClone(form.value);
    // formValue.verifyStatus = status;
    // formValue.status = status;

    if (form.value.verifyStatus === 0) {
      proxy.$modal.msgError("请选择审核结果");
      return;
    }

    if (form.value.actuallyDate == null || form.value.actuallyDate === "") {
      proxy.$modal.msgError("请选择确认所属时间");
      return;
    }
    if (
      form.value.verifyStatus === 2 &&
      (form.value.verifyComment == null || form.value.verifyComment === "")
    ) {
      proxy.$modal.msgError("请输入驳回原因");
      return;
    }
    // if (
    //   form.value.evidenceFiles == null ||
    //   form.value.evidenceFiles.length === 0 || form.value.evidenceFiles.length>5
    // ) {
    //   proxy.$modal.msgError("请上传凭证并至多上传5个");
    //   return;
    // }
    // 应收款金额  和明细比较 如果大于应收内容 提示 当前的合同提过的收款申请总金额超过当前合同金额，不可提交，如有需要请跟财务人员联系
    if(form.value.verifyStatus === 1){
      const res = await getCollectionDetail(form.value.contractId);
      if (res.data == null || res.data.length == 0) {
        const amount = form.value.arriveAmount;
        if (amount > form.value.contractAmount) {
          proxy.$modal.msgError("当前的合同提过的收款申请总金额超过当前合同金额，不可提交，请联系财务人员。");
          return false;
        }
        for (let i = 0; i < form.value.details.length; i++) {
          let item = form.value.details[i];
          const Amount = (Number(item.countAmount) || 0)*1000 - (Number(item.reviewAmount) || 0)*1000;
          if ( item.arriveAmount + (Amount/1000) > (Number(item.amount) || 0)) {
            proxy.$modal.msgError("当前的" + item.taskTypeName + "本次收款金额超过系统内存在的收款金额，不可提交，请联系财务人员。");
            return false;
          }
        }
      } else {
        const countAmount = res.data.map((item) => item.status === 1&&item.arriveAmount).reduce((total, number) => {
          return total + number;
        });
        const amount = countAmount + form.value.arriveAmount;
        if (amount > form.value.contractAmount) {
          proxy.$modal.msgError("当前的合同提过的收款申请总金额超过当前合同金额，不可提交，请联系财务人员。");
          return false;
        }
        for (let i = 0; i < form.value.details.length; i++) {
          let item = form.value.details[i];
          let countAmount = 0;
          for (let j = 0; j < res.data.length; j++) {
            let match = res.data[j];
            if (item.taskTypeId == match.taskTypeId) {
              countAmount += match.arriveAmount;
            }
          }
          if (item.amount < match.add(item.arriveAmount)) {
            proxy.$modal.msgError("当前的" + item.taskTypeName + "收款申请总金额超过当前服务金额，不可提交，请联系财务人员。");
            return false;
          }
          const diff = (Number(item.amount) || 0)*1000 - (Number(item.arrived) || 0)*1000;
          const Amount = (Number(item.countAmount) || 0)*1000 - (Number(item.reviewAmount) || 0)*1000;
          if ( item.arriveAmount + (Amount/1000) > (Number(item.amount) || 0)) {
            proxy.$modal.msgError("当前的" + item.taskTypeName + "本次收款金额超过系统内存在的收款金额，不可提交，请联系财务人员。");
            return false;
          }
        }
      }
    }

    if (form.value.arriveAmount > form.value.contractAmount) {
      proxy.$modal.msgError("实际收款金额不能大于合同收款金额");
      return;
    }
    form.value.status = form.value.verifyStatus;
    form.value.arriveStatus = form.value.status === 1 ? 1 : 0;
    verifyCollection(form.value).then((res) => {
      open(form.value.id);
      getList.value();
      rejectCancel();
      proxy.$modal.mseSuccess("保存成功");
    });
  }

  /** 文件上传 */
  function upload(param) {
    const fileForm = new FormData();
    fileForm.append("file", param.file);
    uploadFile(fileForm).then((res) => {
      if (res.code === 200) {
        const file = {};
        file.fileName = res.newFileName;
        file.url = res.url;
        file.originalFileName = res.originalFilename;
        file.fileUrl = res.fileName;
        console.log(11212, form.value.files);
        form.value.files.push(file);
      }
    });
  }
  function upload2(param) {
    const formData = new FormData();
    formData.append("file", param.file);
    uploadFile(formData).then((res) => {
      if (res.code === 200) {
        const file = {};
        file.fileName = res.newFileName;
        file.url = res.url;
        file.fileType =
          res.newFileName.split(".")[res.newFileName.split(".").length - 1];
        file.originalFileName = res.originalFilename;
        file.fileUrl = res.fileName;
        console.log(11212, file);
        if (form.value.evidenceFiles == null) {
          form.value.evidenceFiles = [];
        }
        form.value.evidenceFiles.push(file);
      }
    });
  }

  function handleDelFile(index) {
    form.value.files.splice(index, 1);
  }

  function amountChangeHandler(arg, row, field) {
    computeTotalAmount();
  }
  function handlerEportFilesDel(row, index) {
    proxy.$modal
      .confirm("确定删除吗？")
      .then((_) => {
        form.value.evidenceFiles.splice(index, 1);
      })
      .catch((_) => {
        proxy.$modal.msg("已取消删除");
      });
  }

  function computeTotalAmount() {
    let amount = 0;
    for (let index = 0; index < form.value.details.length; index++) {
      const element = form.value.details[index];
      amount += element.arriveAmount == null ? 0 : element.arriveAmount;
    }
    form.value.arriveAmount = amount;
  }

  function amountChange() {
    let amount = 0;
    if (form.value.details.length > 0) {
      for (let i = 0; i < form.value.details.length; i++) {
        amount = amount + form.value.details[i].arriveAmount;
      }
      // 判断到款状态
      form.value.arriveAmount = amount;
      if (form.value.arriveAmount > 0)
        form.value.arriveStatus =
          form.value.arriveAmount === form.value.amount ? 1 : 2;
      else form.value.arriveStatus = 0;
    }
  }
  function querySearchAccountAsync(queryString, cb) {
    const query =
      queryString.length > 0
        ? { keyword: queryString, pageSize: 20, pageNum: 1 }
        : { pageSize: 20, pageNum: 1 };
    listAccount(query).then((res) => {
      cb(res.rows);
    });
  }

  function handleSelectAccount(item) {
    form.value.subsidiaryName = item.name;
    form.value.subsidiaryBankName = item.accountOpen;
    form.value.subsidiaryBankAccount = item.accountNum;
  }

  function openFile(row) {
    window.open(`${baseUrl}${row.fileUrl}`);
  }

  function handlerDelAttach(row, index) {
    proxy.$modal
      .confirm("确认删除该项么？")
      .then((_) => {
        form.value.files.splice(index, 1);
      })
      .catch((err) => {
        proxy.$modal.msgError("取消删除");
      });
  }
  const reForm = () =>{
    open(form.value.id);
  }
  /** 暴露给父组件的方法 */
  defineExpose({
    open,
  });
</script>