<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>
          <template v-if="
              checkPermission(['business:payment:edit', 'business:payment:add'])
            ">
            <el-button v-if="editStatus" type="primary" size="small" icon="Finished" @click="submitForm">保存</el-button>
            <el-button v-else-if="form.verifyStatus === 0" type="warning" size="small" icon="Edit"
              @click="editStatus = true">修改</el-button>
              <el-button v-show="form.verifyStatus == 3 " type="warning" size="small" icon="Finished"
              @click="returnZero"    v-hasPermi="['business:payment:return']">退回</el-button>
            <el-button v-if="form.id && editStatus" size="small" icon="Close"
              @click="editStatus = false">取消修改</el-button>
          </template>
          <el-button v-show="form.id && !editStatus && form.verifyStatus === 0"
            v-hasPermi="['business:payment:financialVerify']" type="primary" size="small" icon="Check"
            @click="verifyHandler">财务审核</el-button>
          <el-button v-show="form.id && !editStatus && form.verifyStatus === 1"
            v-hasPermi="['business:payment:cashierVerify']" type="primary" size="small" icon="Check"
            @click="cashierVerifyHandler">出纳审核</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" style="width: 100%" v-model.trim="form.flowNo" readonly 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="formDate" required>
                <el-date-picker v-if="editStatus" style="width: 100%" v-model="form.formDate" size="small"
                  :clearable="true" format="YYYY-MM-DD" value-format="YYYY-MM-DD" align="center" type="date"
                  placeholder="申请日期" />
                <span v-else>{{ form.formDate }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="支出类目：">
                <el-select v-if="editStatus" style="width: 100%" v-model.trim="form.paymentCauseId" placeholder="支出类目"
                  size="small" :clearable="true" @change="paymentCauseChange">
                  <el-option v-for="item in paymentTypes" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
                <span v-else>{{ form.paymentCause }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="支出科目：">
                <el-select v-if="editStatus" style="width: 100%" v-model.trim="form.paymentSubjectId" placeholder="支出科目"
                  size="small" :clearable="true" @change="paymentSubjectChange">
                  <el-option v-for="item in paymentSubjects" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
                <span v-else>{{ form.paymentSubject }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="收款账户名：">
                <el-input v-if="editStatus" style="width: 100%" v-model.trim="form.acceptAccount" size="small"
                  type="text" placeholder="收款账户名" :clearable="true" />
                <span v-else>{{ form.acceptAccount }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="收款账号：">
                <template v-if="editStatus">
                  <el-input v-model.trim="form.acceptAccountNo" size="small" type="text" style="width: 100%"
                    placeholder="收款账号" :clearable="true" />
                </template>
                <span v-else>{{ form.acceptAccountType }} -
                  {{ form.acceptAccountNo }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="收款账户开户银行:" label-width="120px">
                <template v-if="editStatus">
                  <el-input v-model.trim="form.bankNo" size="small" type="text" style="width: 100%"
                    placeholder="收款账户开户银行" :clearable="true" />
                </template>
                <span v-else>{{ form.bankNo }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="客户名称：" prop="companyName" required>
                <el-autocomplete v-if="editStatus" style="width: 100%" :fetch-suggestions="querySearchCompanyAsync"
                  :trigger-on-focus="true" v-model="form.companyName" placeholder="请输入客户名称"
                  popper-class="my-autocomplete" @select="handleSelectCompany">
                  <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> <el-link  :underline="false" type="primary" @click="handleInfo(form)">{{ form.companyName }}</el-link></span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="合同编号：" required>
                <el-input v-if="editStatus" style="width: 100%" v-model.trim="form.contractNo" size="small" type="text"
                  placeholder="请选择" :clearable="true">
                  <template #append>
                    <el-button icon="Search" @click="() => contractChoiceHandler()" />
                  </template>
                </el-input>
                <span v-else style="width: 100%">
                    <!-- <el-button class="text-overflow" type="primary" link @click="(showContractDialog(currentContract.contractId))">{{ currentContract.formNo }}</el-button> -->
                    <!-- {{ form.contractNo }} -->
                    <el-link :underline="false" type="primary" @click="handleContract(form)" >{{ form.contractNo }}</el-link>
                </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.payedAmount) }}</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.amount" size="small" readonly placeholder="支出金额"
                  :clearable="true" :precision="2" controls-position="right" :controls="false" @change="amountChange" />
                <span v-else>{{ rowNum(form.amount) }}</span>
              </el-form-item>
            </el-col>
            <el-col v-if="form.verifyStatus === 2 || form.verifyStatus === 4" :span="6">
              <el-form-item label="驳回原因：" required>
                <span>{{ form.verifyComment }}</span>
              </el-form-item>
            </el-col>


            <el-col :span="12">
              <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-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>

                  <el-table-column label="任务金额" prop="amount" width="100" align="center">
                    <template #default="scope">
                      <span>{{ rowNum(scope.row.amount) }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="已收款金额" prop="reallyAmount" width="100" align="center">
                    <template #default="scope">
                      <span>{{ rowNum(scope.row.reallyAmount) }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="本次支出金额" prop="paymentAmount" width="100" align="center">
                    <template #default="scope">
                      <template v-if="editStatus">
                        <el-input-number v-model="scope.row.paymentAmount" size="small" placeholder="本次支出金额"
                          :precision="2" :controls="false" style="width: 100%" @change="
                            (arg) =>
                              amountChangeHandler(
                                arg,
                                scope.row,
                                'paymentAmount'
                              )
                          " />
                      </template>
                      <template v-else>{{
                        rowNum(scope.row.paymentAmount)
                        }}</template>
                    </template>
                  </el-table-column>
                  <el-table-column label="已支付金额" prop="payment" width="100" align="center">
                    <template #default="scope">
                      <span>{{ rowNum(scope.row.payment) }}</span>
                    </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" /> 附件
                  <i style="color: red">*</i>
                </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" 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="操作" width="50" 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="rejectForm" label-width="100" size="small">
        <el-form-item label="审核状态">
          <el-select v-model.trim="rejectForm.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="rejectForm.verifyStatus == 2 ? '驳回原因' : '审核意见'" :prop="verifyRemark">
          <el-input v-model.trim="rejectForm.verifyComment" type="textarea" maxlength="200" show-word-limit :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="rejectForm.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">
              <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>
    <el-dialog title="出纳审核详情" v-model="cashierOpen" width="500px" append-to-body draggable>
      <el-form ref="dictRef" :model="form" label-width="100" size="small">
        <el-form-item label="审核状态">
          <el-select v-model.trim="cashierForm.verifyStatus" placeholder="请选择" size="small">
            <el-option v-for="i in cashierVerified" :key="i.value" :label="i.label" :value="i.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="实际支出时间" required>
          <el-date-picker v-model.trim="cashierForm.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="支出附件上传" required>
        </el-form-item> -->
        <el-form-item :label="cashierForm.verifyStatus == 4 ? '驳回原因' : '审核意见'" :prop="verifyComment">
          <el-input v-model.trim="cashierForm.verifyComment" type="textarea" maxlength="200" show-word-limit :rows="3"
            placeholder="请输入审核意见" />
        </el-form-item>
        <el-form-item label="附件">
          <el-upload action="#" :http-request="upload3" :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="cashierForm.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">
              <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="cashierVerifyUpload()">确 定</el-button>
          <el-button icon="close" size="small" @click="cashierVerifyCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <dialog-contract-choice ref="contractChoiceRef" @choice="contractChoiceHandle" />
    <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 {
  //   getOrder,
  //   initTaskTypes,
  //   addOrder,
  //   updateOrder,
  //   verifyOrder,
  //   alterOrder,
  //   dissolutionOrder,
  // } from "@/api/business/crm/contract";
  import {
    listCompany,
    getPayment,
    savePayment,
    listTypes,
    listContractDetail,
    verifyPayment,setPaymentZero
  } from "@/api/business/financial/payment";
  import { listSource } from "@/api/settings/source";
  import { listUser } from "@/api/system/user";
  import CustomerFormCom from "@/components/CustomerFormCom";
  import DialogContractChoice from "@/views/dialog/DialogContractChoice.vue";
  import { formatDate, rowNum } from "@/utils/index";
  import { ref } from "vue";
  import companyForm from "@/views/business/crm/company/formView.vue";
  import contractForm from "@/views/business/crm/order/form.vue";
  import useUserStore from "@/store/modules/user";
  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 rejectForm = ref({});

  const cashierForm = ref({});

  const detailEmpty = {
    id: null,
    taskTypeName: "",
    taskTypeId: null,
    serviceNum: undefined,
    freeNum: undefined,
    price: undefined,
    amount: undefined,
    addressStyle: undefined,
    address: undefined,
    fictionAddressId: undefined,
    tenantId: undefined,
    explain: 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 paymentTypes = ref([]);
  const paymentSubjects = ref([]);

  const paymentEmpty = {
    id: null,
    flowNo: "",
    paymentCauseId: null,
    paymentSubjectId: null,
    acceptAccountTypeId: null,
    subsidiaryId: null,
    subsidiary: null,
    subsidiaryName: "",
    subsidiaryBankAccount: "",
    subsidiaryBankName: "",
    explain: undefined,
    companyId: null,
    companyName: "",
    amount: 0,
    verifyStatus: 0,
    acceptAccount: "",
    accountBank: "",
    applierId: useUserStore().user.userId,
    applierName: "",
    creatorName: useUserStore().user.nickName,
    details: [],
    files: [],
  };
  const isFullscreen = ref(false);
  const webHost = import.meta.env.VITE_APP_BASE_API;
  const data = reactive({
    form: {},
    rules: {
      companyName: [
        { required: true, message: "客户名称不能为空", trigger: "blur" },
      ],
      formDate: [
        { required: true, message: "支出日期不能为空", trigger: "blur" },
      ],
    },
    timeOptions: { start: "08:30", step: "00:15", end: "18:30" },
    verified: [
      {
        value: 0,
        label: "未审核",
      },
      {
        value: 1,
        label: "通过",
      },
      {
        value: 2,
        label: "驳回",
      },
    ],
    cashierVerified: [
      {
        value: 1,
        label: "未审核",
      },
      {
        value: 3,
        label: "通过",
      },
      {
        value: 4,
        label: "驳回",
      },
    ],
    cashierOpen: false,
  });
  const { form, rules, timeOptions, verified, cashierVerified, cashierOpen } =
    toRefs(data);
  /***********************  方法区  ****************************/
  /** 打开抽屉 */
  function open(id) {
    reset();
    visible.value = true;
    editStatus.value = true;
    if (id != null) {
      getPayment(id).then((res) => {
        form.value = res.data;
        editStatus.value = false;
        paymentCauseChange(form.value.paymentCauseId);
        paymentSubjectChange(form.value.paymentSubjectId);
      });
    }
  }

  function init() {
    Promise.all([listTypes()]).then((res) => {
      paymentTypes.value = res[0].rows;
    });
  }
  /** 取消按钮 */
  function cancel() {
    visible.value = false;
    reset();
  }

  /** 表单重置 */
  function reset() {
    form.value = JSON.parse(JSON.stringify(paymentEmpty));
    paymentSubjects.value = [];
  }
  function returnZero() {
    proxy.$modal
      .confirm("是否确认退回")
      .then(function () {
        setPaymentZero(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";
  }

  /** 提交按钮 */
  function submitForm() {
    if (form.value.contractId === 0 || form.value.contractId == null) {
      proxy.$modal.msgError("请输入合同");
      return;
    }
    if (form.value.amount == null || form.value.amount === 0) {
      proxy.$modal.msgError("请输入支出金额");
      return;
    }
    if (form.value.amount > form.value.contractAmount - form.value.payedAmount) {
      proxy.$modal.msgError("支出金额大于合同金额");
      return;
    }
    proxy.$refs["orderRef"].validate((valid) => {
      if (valid && detailValid()) {
        const formValue = form.value;
        savePayment(formValue).then((res) => {
          open(res.data.id);
          getList.value();
        });
      }
    });
  }

  function detailValid() {
    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() {
    rejectHandler();
  }

  function cashierVerifyHandler() {
    cashierOpen.value = true;
    cashierForm.value = proxy.deepClone(form.value);
  }

  function rejectHandler() {
    rejectOpen.value = true;
    rejectForm.value = proxy.deepClone(form.value);
  }

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

  function cashierVerifyCancel() {
    cashierOpen.value = false;
    cashierForm.value = {};
  }
  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 (rejectForm.value.evidenceFiles == null) {
          rejectForm.value.evidenceFiles = [];
        }
        rejectForm.value.evidenceFiles.push(file);
      }
    });
  }
  function upload3(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 (cashierForm.value.evidenceFiles == null) {
          cashierForm.value.evidenceFiles = [];
        }
        cashierForm.value.evidenceFiles.push(file);
      }
    });
  }
  function handleDelFile2(index) {
    rejectForm.value.files.splice(index, 1);
  }
  function rejectSubmitHandler() {
    if (form.value.verifyRemark === "" || form.value.verifyRemark == null) {
      proxy.$modal.msgError("请填写驳回原因");
      return;
    }
  }

  function verifyUpload() {
    if (rejectForm.value.verifyStatus === 0) {
      proxy.$modal.msgError("请选择审核结果");
      return;
    }
    if (
      rejectForm.value.verifyStatus === 2 &&
      (rejectForm.value.verifyComment == null ||
        rejectForm.value.verifyComment === "")
    ) {
      proxy.$modal.msgError("请输入审核意见");
      return;
    }


    // if (
    //   rejectForm.value.evidenceFiles == null ||
    //   rejectForm.value.evidenceFiles.length === 0 || rejectForm.value.evidenceFiles.length>5
    // ) {
    //   proxy.$modal.msgError("请上传附件并至多上传5个");
    //   return;
    // }
    verifyPayment(rejectForm.value).then((res) => {
      open(form.value.id);
      getList.value();
      rejectCancel();
      proxy.$modal.msgSuccess("保存成功");
    });
  }

  function cashierVerifyUpload() {
    if (cashierForm.value.verifyStatus === 1) {
      proxy.$modal.msgError("请选择审核结果");
      return;
    }
    if (
      cashierForm.value.actuallyDate == null ||
      cashierForm.value.actuallyDate === ""
    ) {
      proxy.$modal.msgError("请选择支出时间");
      return;
    }
    // if (
    //   cashierForm.value.evidenceFiles == null ||
    //   cashierForm.value.evidenceFiles.length === 0 || cashierForm.value.evidenceFiles.length>5
    // ) {
    //   proxy.$modal.msgError("请上传附件并至多上传5个");
    //   return;
    // }
    if (
      cashierForm.value.verifyStatus === 4 &&
      (cashierForm.value.verifyComment == null ||
        cashierForm.value.verifyComment === "")
    ) {
      proxy.$modal.msgError("请输入审核意见");
      return;
    }
    cashierForm.value.paymentStatus =
      cashierForm.value.verifyStatus === 3 ? 1 : 0;
    verifyPayment(cashierForm.value).then((res) => {
      open(cashierForm.value.id);
      getList.value();
      cashierVerifyCancel();
      proxy.$modal.msgSuccess("保存成功");
    });
  }

  /** 文件上传 */
  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;
        form.value.files.push(file);
      }
    });
  }

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

  function amountChangeHandler(arg, row, field) {
    computeTotalAmount();
  }

  function computeTotalAmount() {
    let amount = 0;
    for (let index = 0; index < form.value.details.length; index++) {
      const element = form.value.details[index];
      amount += element.paymentAmount == null ? 0 : element.paymentAmount;
    }
    form.value.amount = amount;
  }
  function handlerEportFilesDel(row, index) {
    proxy.$modal
      .confirm("确定删除吗？")
      .then((_) => {
        rejectForm.value.evidenceFiles.splice(index, 1);
      })
      .catch((_) => {
        proxy.$modal.msg("已取消删除");
      });
  }
  function handlerEportFilesDel2(row, index) {
    proxy.$modal
      .confirm("确定删除吗？")
      .then((_) => {
        cashierForm.value.evidenceFiles.splice(index, 1);
      })
      .catch((_) => {
        proxy.$modal.msg("已取消删除");
      });
  }
  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].paymentAmount;
      }
      // 判断到款状态
      form.value.amount = amount;
      if (form.value.payedAmount > 0)
        form.value.arriveStatus =
          form.value.payedAmount === form.value.amount ? 1 : 2;
      else form.value.arriveStatus = 0;
    }
  }
  function handleInfo(row) {
    proxy.$refs.companyRef.open(row.companyId);
  }
  function handleContract() {
    proxy.$refs.contractRef.open(form.value.contractId);
  }

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

  function querySearchCompanyAsync(queryString, cb) {
    const query =
      queryString.length > 0
        ? {
          keyword: queryString,
          pageSize: 50,
          pageNum: 1,
          orderByColumn: "create_time",
        }
        : { pageSize: 50, pageNum: 1, orderByColumn: "create_time" };
    listCompany(query).then((res) => {
      cb(res.rows);
    });
  }

  function handleSelectCompany(item) {
    form.value.companyName = item.name;
    form.value.companyId = item.id;
  }

  function paymentCauseChange(arg) {
    const index = paymentTypes.value.findIndex((v) => v.id === arg);
    if (index >= 0) {
      paymentSubjects.value = [{ id: "0", name: "请选择" }].concat(
        paymentTypes.value[index].bizPaymentSubjectList
      );
      form.value.paymentCause = paymentTypes.value[index].name;
      if (
        paymentSubjects.value.findIndex(
          (v) => v.id === form.value.paymentSubjectId
        ) < 0
      ) {
        form.value.paymentSubjectId = null;
        form.value.paymentSubject = "";
      }
    }
  }
  function contractChoiceHandler() {
    if (form.value.companyId == null || form.value.companyId === "") {
      proxy.$modal.msgError("请选择客户");
      return;
    }
    proxy.$refs.contractChoiceRef.open({ companyId: form.value.companyId });
  }

  function contractChoiceHandle(info) {
    form.value.details = []
    form.value.contractId = info.id;
    form.value.contractNo = info.contractNo;
    form.value.contractAmount = info.trueAmount;
    form.value.payedAmount = info.paidAmount;
    listContractDetail({ contractId: info.id }).then((res) => {
      const rows = res.rows;
      rows.forEach((item) => {
        const detail = {
          contractId: item.contractId,
          contractDetailId: item.id,
          companyId: form.value.companyId,
          taskTypeId: item.taskTypeId,
          amount: item.amount,
          taskTypeName: item.taskTypeName,
          payment: item.payment,
          reallyAmount: item.reallyAmount,
          explain: item.explain
        };
        form.value.details.push(detail);
      });
    });
  }

  function handlerDelAttach(row, index) {
    proxy.$modal
      .confirm("确认删除该项么？")
      .then((_) => {
        form.value.files.splice(index, 1);
      })
      .catch((err) => {
        proxy.$modal.msgError("取消删除");
      });
  }

  function paymentSubjectChange(id) {
    const index = paymentSubjects.value.findIndex((v) => v.id === id);
    if (index >= 0) {
      form.value.paymentSubjectId = paymentSubjects.value[index].id;
    }
  }

  function checkPermission(templatePermission) {
    const all_permission = "*:*:*";
    const permissions = useUserStore().permissions;
    const hasPermissions = permissions.some((permission) => {
      return (
        all_permission === permission || templatePermission.includes(permission)
      );
    });
    return hasPermissions;
  }

  init();

  /** 暴露给父组件的方法 */
  defineExpose({
    open,
  });
</script>