<template>
  <ele-modal
    custom-class="ele-dialog-form long-dialog-form"
    :centered="true"
    :visible.sync="addOrEditDialogFlag"
    :title="title"
    :append-to-body="true"
    :close-on-click-modal="false"
    width="70%"
    :before-close="cancel"
    :maxable="true"
    :resizable="true"
  >
    <el-form
      ref="form"
      :rules="rules"
      class="el-form-box"
      :model="form"
      label-width="140px"
    >
      <headerTitle title="基本信息"></headerTitle>
      <el-row :gutter="12">
        <el-col :span="8">
          <el-form-item label="发票类型" prop="type">
            <el-select
              v-model="form.type"
              @change="handleSelType('isType')"
              clearable
              style="width: 100%"
            >
              <el-option label="开票" :value="1"></el-option>
              <el-option label="收票" :value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="form.type">
          <el-form-item label="来源类型" prop="sourceType">
            <el-select
              v-model="form.sourceType"
              @change="handleSelType()"
              :disabled="isOtherSourceFlag"
              clearable
              style="width: 100%"
            >
              <el-option label="对账单" :value="1"></el-option>
              <el-option label="合同" :value="2"></el-option>
              <el-option label="订单" :value="3"></el-option>
              <el-option label="其他无订单无合同" :value="4"></el-option>
              <!-- <el-option
                label="应收"
                :value="5"
                v-if="form.type == 1"
              ></el-option>
              <el-option
                label="应付"
                :value="4"
                v-if="form.type == 2"
              ></el-option> -->
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="form.sourceType == 1">
          <el-form-item label="对账单" prop="sourceCode">
            <el-input
              v-model="form.sourceCode"
              readonly
              @click.native="handleSelectAccount(1)"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="form.sourceType == 2">
          <el-form-item label="合同" prop="sourceCode">
            <el-input
              v-model="form.sourceCode"
              readonly
              @click.native="handleSelectAccount(2)"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="form.sourceType == 3">
          <el-form-item label="订单" prop="sourceCode">
            <el-input
              v-model="form.sourceCode"
              readonly
              @click.native="handleSelectAccount(3)"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="form.sourceType == 5">
          <el-form-item label="应收" prop="sourceCode">
            <el-input
              v-model="form.sourceCode"
              readonly
              @click.native="handleSelectAccount(5)"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="form.sourceType == 4">
          <el-form-item label="应付" prop="sourceCode">
            <el-input
              v-model="form.sourceCode"
              readonly
              @click.native="handleSelectAccount(4)"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="发票金额" prop="amount">
            <el-input-number
              v-model="form.amount"
              :precision="2"
              :controls="false"
              style="width: 100%"
              :min="0"
              disabled
            ></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="发票号" prop="invoiceNos">
            <el-input
              v-model="form.invoiceNos"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="开票日期">
            <el-date-picker
              style="width: 100%"
              v-model="form.expectInvoiceDate"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="申请部门" prop="applyDeptId">
            <ele-tree-select
              clearable
              :data="deptTreeList"
              v-model="form.applyDeptId"
              valueKey="id"
              labelKey="name"
              placeholder="请选择"
              @change="changeDeptInfo"
              default-expand-all
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="申请人" prop="applyUserId">
            <personSelect
              ref="directorRef"
              v-model="form.applyUserId"
              @selfChange="changeUserInfo"
            />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="发票类型" prop="category">
            <el-radio v-model="form.category" :label="2"
              >增值税普通发票</el-radio
            >
            <el-radio v-model="form.category" :label="1"
              >增值税专用发票</el-radio
            >
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="files" label="发票附件">
            <fileMain v-model="form.files"></fileMain>
          </el-form-item>
        </el-col>
      </el-row>
      <headerTitle title="发票信息"></headerTitle>
      <el-row :gutter="12">
        <el-col :span="12">
          <el-form-item label="甲方名称" prop="companyName">
            <el-input
              v-model="form.companyName"
              placeholder="请输入"
              v-if="enterprisePage.length <= 1 || form.type == 1"
            />
            <el-select
              v-if="enterprisePage.length > 1 && form.type == 2"
              style="width: 100%"
              v-model="form.companyName"
              placeholder="请选择"
              @change="enterpriseChange"
            >
              <el-option
                v-for="item in enterprisePage"
                :key="item.id"
                :label="item.name"
                :value="item.name"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="甲方统一社会信用代码"
            prop="companyUsc"
            class="form_item_label"
          >
            <el-input v-model="form.companyUsc"></el-input>
          </el-form-item>
          <el-form-item label="甲方联系人" prop="companyContactName">
            <el-input v-model="form.companyContactName"></el-input>
          </el-form-item>
          <el-form-item label="甲方电话" prop="companyTel">
            <el-input v-model="form.companyTel"></el-input>
          </el-form-item>
          <el-form-item label="甲方开户行" prop="companyBankBranchNo">
            <el-input v-model="form.companyBankBranchNo"></el-input>
          </el-form-item>
          <el-form-item label="甲方银行账号" prop="companyBankAccount">
            <el-input v-model="form.companyBankAccount"></el-input>
          </el-form-item>
          <el-form-item label="甲方地址" prop="companyAddress">
            <el-input v-model="form.companyAddress"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="乙方名称" prop="receiverName">
            <el-input
              v-model="form.receiverName"
              placeholder="请输入"
              v-if="enterprisePage.length <= 1 || form.type == 2"
            />
            <el-select
              v-if="enterprisePage.length > 1 && form.type == 1"
              style="width: 100%"
              v-model="form.receiverName"
              placeholder="请选择"
              @change="enterpriseChange"
            >
              <el-option
                v-for="item in enterprisePage"
                :key="item.id"
                :label="item.name"
                :value="item.name"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="乙方统一社会信用代码"
            prop="salesCompanyUsc"
            class="form_item_label"
          >
            <el-input v-model="form.salesCompanyUsc"></el-input>
          </el-form-item>
          <el-form-item label="乙方联系人" prop="receiverContactName">
            <el-input v-model="form.receiverContactName"></el-input>
          </el-form-item>
          <el-form-item label="乙方电话" prop="receiverTel">
            <el-input v-model="form.receiverTel"></el-input>
          </el-form-item>
          <el-form-item label="乙方开户行" prop="salesCompanyBankBranchNo">
            <el-input v-model="form.salesCompanyBankBranchNo"></el-input>
          </el-form-item>
          <el-form-item label="乙方银行账号" prop="salesCompanyBankAccount">
            <el-input v-model="form.salesCompanyBankAccount"></el-input>
          </el-form-item>
          <el-form-item label="地址" prop="receiverAddress">
            <el-input v-model="form.receiverAddress"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <headerTitle title="关联物品清单"></headerTitle>
    <table-info
      :isOtherSourceFlag="isOtherSourceFlag"
      :dialogType="dialogType"
      :form="form"
      :contactData="contactData"
      ref="table"
      @setPrice="setPrice"
      :invoiceAmount="form.invoiceAmount"
    ></table-info>
    <div slot="footer">
      <el-button type="primary" @click="handleSave(0)">保存</el-button>
      <el-button
        type="primary"
        v-if="isNeed_process_is_close"
        @click="handleSave(1)"
        >提交</el-button
      >
      <el-button @click="cancel">返回</el-button>
    </div>
    <process-submit-dialog
      api-fun-name="fininvoiceapplyStatusAPI"
      :processSubmitDialogFlag.sync="processSubmitDialogFlag"
      v-if="processSubmitDialogFlag"
      ref="processSubmitDialogRef"
      @reload="reload"
    ></process-submit-dialog>
    <!--对账单-->
    <account-statement-dialog
      ref="accountStatementDialogRef"
      :form="form"
      v-if="accountStatementDialogFlag"
      :accountstatement-dialog-flag.sync="accountStatementDialogFlag"
      @getAccountData="getAccountData"
      :contactData="contactData"
      :type="form.type"
    >
    </account-statement-dialog>
    <!--采购订单-->
    <purchasinOrderListDialog
      ref="orderListDialogRef"
      @changeParent="changeOrder"
    ></purchasinOrderListDialog>
    <!--销售订单-->
    <saleOrderListDialog
      ref="saleOrderListDialogref"
      @changeParent="changeOrder"
    ></saleOrderListDialog>

    <contractListDialog
      ref="selectContractRef"
      @changeParent="changeContract"
      :type="form.type"
    ></contractListDialog>
    <!-- 应收 -->
    <receivableDialog
      ref="receivableRef"
      @receivableDone="receivableDone"
      v-if="receivableDialogFlag"
      :receivableDialogFlag.sync="receivableDialogFlag"
    ></receivableDialog>
    <!-- 应付 -->
    <paymentListDialog
      ref="receivableRef1"
      @receivableDone="receivableDone"
      v-if="paymentListDialogFlag"
      :paymentListDialogFlag.sync="paymentListDialogFlag"
    ></paymentListDialog>
  </ele-modal>
</template>
<script>
  import personSelect from '@/components/CommomSelect/person-select.vue';
  import { listOrganizations } from '@/api/system/organization';
  import { mapGetters } from 'vuex';
  import fileUpload from '@/components/upload/fileUpload.vue';
  import tableInfo from './tableInfoNew.vue';
  import { getTreeByPid } from '@/api/classifyManage';
  import {
    invoiceApplyInfoAPI,
    invoiceApplySaveAPI,
    invoiceApplyUpdateAPI
  } from '@/api/financialManage/invoiceManage';
  import { getpurchaseorderDetail } from '@/api/purchasingManage/purchaseOrder';
  import { getSaleOrderDetail } from '@/api/saleManage/saleorder';
  import { getDetail } from '@/api/contractManage/contractBook';
  import processSubmitDialog from '@/BIZComponents/processSubmitDialog/processSubmitDialog.vue';
  import accountStatementDialog from './accountstatementDialog.vue';
  import contractListDialog from '@/views/saleManage/saleOrder/components/contractListDialog.vue';
  import purchasinOrderListDialog from '@/views/purchasingManage/purchaseOrder/invoice/components/orderListDialog.vue'; //采购订单
  import saleOrderListDialog from '@/views/saleManage/saleOrder/invoice/components/orderListDialog.vue'; //销售订单
  import { enterprisePage } from '@/api/contractManage/contractBook';
  import { contactDetail } from '@/api/saleManage/contact';
  // import fileMain from '@/components/addDoc/index.vue';
  import receivableDialog from '@/views/financialManage/receivableManage/components/receivableDialog.vue'; //应收
  import paymentListDialog from '@/views/financialManage/payableManage/components/paymentListDialog.vue'; //应付

  import { updateContractStatus } from '@/api/contractManage/contractBook';

  const defForm = {
    accountingSubjectCode: '',
    accountingSubjectId: '',
    accountingSubjectName: '',
    amount: undefined,
    contactId: '',
    companyAddress: '',
    companyBankAccount: '',
    companyUsc: '',
    expectInvoiceDate: '',
    companyBankBranchNo: '',
    companyName: '',
    receiverAddress: '',
    receiverName: '',
    receiverTel: '',
    companyTel: '',
    detailList: [],
    drawerId: '',
    drawerName: '',
    files: [],
    invoiceStatus: '',
    link: [],
    remark: '',
    settlementAccountId: '',
    settlementAccountName: '',
    invoiceAmount: 0,
    getAccountData: '',
    sourceId: '',
    sourceCode: '',
    salesCompanyUsc: '',
    salesCompanyBankBranchNo: '',
    salesCompanyBankAccount: '',
    category: 1
  };
  export default {
    name: 'add-or-edit-dialog',
    components: {
      processSubmitDialog,
      fileUpload,
      personSelect,
      tableInfo,
      accountStatementDialog,
      contractListDialog,
      purchasinOrderListDialog,
      saleOrderListDialog,
      // fileMain,
      receivableDialog,
      paymentListDialog
    },
    props: {
      addOrEditDialogFlag: {
        type: Boolean,
        default: false
      },
      contactData: {
        type: Object,
        default: () => {
          return {};
        }
      }
    },
    provide() {
      return {
        invoiceType: () => this.form.type
      };
    },
    computed: {
      ...mapGetters(['user'])
    },
    data() {
      return {
        fullscreen: false,
        receivableDialogFlag: false,
        dialogType: '',
        title: '',
        isOtherSourceFlag: false,
        processSubmitDialogFlag: false,
        accountStatementDialogFlag: false,
        paymentListDialogFlag: false,
        enterprisePage: [],

        form: {
          applyDeptId: '',
          applyDeptName: '',
          applyUserId: '',
          applyUserName: '',
          type: 1,
          id: '',
          ...defForm
        },
        feeTypeList: [],
        accountingSubjectList: [],
        deptList: [],
        deptTreeList: [],
        rules: {
          applyDeptId: { required: true, message: '请选择', trigger: 'change' },
          applyUserId: { required: true, message: '请选择', trigger: 'change' },
          accountingSubjectId: {
            required: true,
            message: '请选择',
            trigger: 'change'
          },
          feeTypeId: { required: true, message: '请选择', trigger: 'change' },
          amount: { required: true, message: '请输入', trigger: 'blur' },
          companyName: { required: true, message: '请输入', trigger: 'blur' },
          type: { required: true, message: '请选择', trigger: 'change' },
          sourceType: { required: true, message: '请选择', trigger: 'change' }
        }
      };
    },
    created() {
      this.getClassifyList(24, 'accountingSubjectList');
      this.getDeptList();
    },
    methods: {
      //从发票管理新增发票初始化
      async init(row = {}, type) {
        this.title = type == 'add' ? '新增' : '修改';
        this.dialogType = type;
        if (type == 'add') {
          this.form.applyDeptId = this.user.info.groupId;
          this.form.applyDeptName = this.user.info.groupName;
          this.form.applyUserId = this.user.info.userId;
          this.form.applyUserName = this.user.info.name;
          enterprisePage({
            pageNum: 1,
            size: 200
          }).then((res) => {
            this.enterprisePage = [];
            this.enterprisePage.push(...res.list);
            this.enterpriseChange(this.enterprisePage[0]?.name);
          });
        } else {
          await this.getInfo(row.id);
        }
        this.$nextTick(async () => {
          await this.getUserList(this.form.applyDeptId);
        });
      },

      //来源类型
      async handleSelectAccount(val) {
        if (val == 1) {
          this.accountStatementDialogFlag = true;
        }
        if (val == 2) {
          this.$refs.selectContractRef.open({}, 1, 1);
        }
        if (val == 3 && this.form.type == 2) {
          this.$refs.orderListDialogRef.open({}, 1, true);
        }
        if (val == 3 && this.form.type == 1) {
          this.$refs.saleOrderListDialogref.open({}, 1, true);
        }
        if (val == 5) {
          this.receivableDialogFlag = true;
        }
        if (val == 4) {
          this.paymentListDialogFlag = true;
        }
      },
      //合同回调
      async changeContract(data) {
        const res = await getDetail(data.id);
        this.$set(this.form, 'sourceId', data.id);
        this.$set(this.form, 'sourceCode', data.contractNo);
        this.$set(
          this.form,
          'amount',
          res.contractVO?.discountTotalPrice - res.contractVO?.invoiceAmount
        );
        this.$set(this.form, 'invoiceAmount', res.contractVO?.invoiceAmount);
        this.getContactDetail(
          this.form.type == 2
            ? res.contractVO?.partbId
            : res.contractVO?.partaId,
          res.contractVO
        );

        res.productList.forEach((item) => {
          item.singlePrice =
            (item.discountSinglePrice &&
              Number(item.discountSinglePrice).toFixed(2)) ||
            item.singlePrice;
          item.totalPrice =
            (item.discountTotalPrice &&
              Number(item.discountTotalPrice).toFixed(2)) ||
            item.totalPrice;
          item.typeName = this.form.type == 1 ? '销售合同' : '采购合同';
          item.type = this.form.type == 1 ? '101' : '102';
        });
        this.$nextTick(() => {
          this.$refs.table.setValue(res.productList);
        });
        this.$forceUpdate();
      },
      async getContactDetail(id, data) {
        let contactValue = {};
        if (id) {
          this.form.contactId = id;
          contactValue = await contactDetail(id);
        }
        const { base, other, bankList, linkList } = contactValue;
        if (this.form.type == 1) {
          this.form.companyName = base.name;
          this.form.companyUsc = base.unifiedSocialCreditCode;
          this.form.companyAddress = other?.addressName + other?.address;
          this.form.companyTel =
            data.partbTel ||
            linkList.find((item) => item.ifChief == 1)?.mobilePhone;

          this.form.companyBankAccount = bankList[0]?.accountNo;
          this.form.companyBankBranchNo = bankList[0]?.bankName;
          this.enterpriseChange(data.partbName);
        } else {
          this.form.receiverName = base.name;
          this.form.receiverAddress = other?.addressName + other?.address;
          this.form.receiverTel =
            data.partaTel ||
            linkList.find((item) => item.ifChief == 1)?.mobilePhone;
          this.form.salesCompanyUsc = base.unifiedSocialCreditCode;
          this.form.salesCompanyBankAccount = bankList[0]?.accountNo;
          this.form.salesCompanyBankBranchNo = bankList[0]?.bankName;
          this.enterpriseChange(data.partaName);

        }
      },
      //订单回调
      async changeOrder(data) {
        this.$set(this.form, 'sourceId', data.id);
        this.$set(this.form, 'sourceCode', data.orderNo);
        let res = {};
        if (this.form.type == 2) {
          res = await getpurchaseorderDetail(data.id);
        } else {
          res = await getSaleOrderDetail(data.id);
        }
        this.$set(this.form, 'amount', res.payAmount - res.invoiceAmount);
        this.$set(this.form, 'invoiceAmount', res.invoiceAmount);
        this.getContactDetail(
          this.form.type == 2 ? res.partbId : res.partaId,
          res
        );
        res.productList.forEach((item) => {
          item.singlePrice =
            (item.discountSinglePrice &&
              Number(item.discountSinglePrice).toFixed(2)) ||
            item.singlePrice;
          item.totalPrice =
            (item.discountTotalPrice &&
              Number(item.discountTotalPrice).toFixed(2)) ||
            item.totalPrice;
          item.typeName = this.form.type == 1 ? '销售订单' : '采购订单';
          item.type = this.form.type == 1 ? '201' : '202';
        });
        this.$nextTick(() => {
          this.$refs.table.setValue(res.productList);
        });
        this.$forceUpdate();

        console.log(res);
      },

      //应收应付回调
      async payableManage(data) {
        const { row, form } = data;
        console.log(data);
        this.$set(this.form, 'sourceId', row.id);
        this.$set(this.form, 'sourceCode', row.code);
        this.$set(
          this.form,
          'amount',
          row.receivedTotalPrice || row.paidTotalPrice
        );
        this.$set(this.form, 'invoiceAmount', row.invoiceAmount);
        this.getContactDetail(form.contactId, {});
      },
      receivableDone(data) {
        this.$set(this.form, 'type', Number(data.type));
        this.$set(this.form, 'sourceType', data.sourceType);
        this.payableManage(data.data);
      },
      //对账单回调
      async getAccountData(tableInfo) {
        let res = {};
        if (this.form.type == 2) {
          res = await getpurchaseorderDetail(tableInfo?.children?.orderId);
        } else {
          res = await getSaleOrderDetail(tableInfo?.children?.orderId);
        }
        this.getContactDetail(tableInfo.contactId, res);
        this.$nextTick(() => {
          this.$set(this.form, 'sourceId', tableInfo?.children?.id);
          this.$set(this.form, 'sourceCode', tableInfo?.statementNo);
          this.$set(
            this.form,
            'invoiceAmount',
            tableInfo?.children?.invoiceAmount
          );

          this.$refs.table.getAccountData(tableInfo);
        });
      },
      //订单、合同列表
      async createInvoice1(data, type, sourceType) {
        this.$set(this.form, 'type', Number(type));
        this.$set(this.form, 'sourceType', sourceType);

        await this.init({}, 'add');

        if (sourceType == 2) {
          this.changeContract(data);
        }
        if (sourceType == 3) {
          this.changeOrder(data);
        }
        if (sourceType == 4 || sourceType == 5) {
          this.payableManage(data);
        }
      },

      //对账单列表
      createInvoice(
        row = {},
        invoiceType,
        tableInfo = {},
        isOtherSourceFlag = true,
        dialogType = 'add'
      ) {
        this.dialogType = dialogType;
        this.init(row, dialogType);
        this.form.type = tableInfo.type;
        this.$set(this.form, 'sourceType', invoiceType);
        // this.form.sourceType=invoiceType
        setTimeout(() => {
          this.getAccountData(tableInfo);
        }, 400);
      },
      //获取详情
      async getInfo(id) {
        this.form = await invoiceApplyInfoAPI(id);
      },

      //获取分类管理中的数据
      async getClassifyList(id, listName) {
        let res = await getTreeByPid(id);
        this[listName] = res.data;
      },
      //获取费用类别选中数据
      changeFeeTypeInfo(val) {
        if (!val) {
          this.form.feeTypeName = '';
          this.form.feeTypeCode = '';
        }
        let data = this.$refs.feeTypeTree?.$refs?.tree?.getCurrentNode() || {};
        this.form.feeTypeName = data.name;
        this.form.feeTypeCode = data.code;
      },
      //获取会计科目选中数据
      changeSubjectInfo(val) {
        if (!val) return (this.form.accountingSubjectName = '');
        let data = this.$refs.treeSelect?.$refs?.tree?.getCurrentNode() || {};
        this.form.accountingSubjectName = data.name;
      },
      // 获取部门数据
      getDeptList() {
        listOrganizations().then((list) => {
          this.deptList = list;
          this.deptTreeList = this.$util.toTreeData({
            data: list,
            idField: 'id',
            parentIdField: 'parentId'
          });
        });
      },
      // 选择负责人部门
      changeDeptInfo(id) {
        const info = this.deptList.find((e) => e.id == id) || {};
        this.form.applyDeptName = info.name;
        this.form.applyUserId = '';
        this.form.applyUserName = '';
        this.getUserList(id);
      },
      // 获取人员数据
      getUserList(deptId) {
        if (deptId) {
          this.$refs.directorRef.getList({ deptId });
        }
      },
      //选择人员数据
      changeUserInfo(val, info) {
        this.form.applyUserName = info.name;
      },

      //
      handleSelType(val) {
        this.form = Object.assign({}, this.form, defForm);
        if (val == 'isType') {
          this.$set(this.form, 'sourceType', '');
        }
        this.$refs.table.clearTable();
        this.enterpriseChange(this.enterprisePage[0]?.name);
      },
      setPrice(val) {
        this.form.amount = val;
      },
      //系统公司信息
      enterpriseChange(name) {
        let data = this.enterprisePage.find((item) => item.name == name);

        if (this.form.type == 2) {
          this.form.companyName = data?.name;
          this.form.companyUsc = data?.unifiedSocialCreditCode;
          this.form.companyAddress = data?.address;
          this.form.companyTel = data?.tel;
        } else {
          this.form.receiverName = data?.name;
          this.form.receiverAddress = data?.address;
          this.form.salesCompanyUsc = data?.unifiedSocialCreditCode;
          this.form.receiverTel = data?.tel;
        }
        this.$forceUpdate();
      },
      //
      handleSave(flag) {
        this.$refs.form.validate(async (valid) => {
          if (!valid) return this.$message.warning('有必填项未填，请检查');
          let tableData = {};
          if (this.form.sourceType != 4 || this.form.sourceType != 5) {
            tableData = await this.$refs.table.getTableValidate();
          }
          // 校验表格数据
          const tableValid = await new Promise((resolve) => {
            this.$refs.table.validateForm((valid) => {
              resolve(valid);
            });
          });
          if (!tableValid) {
            return;
          }
          this.form.link = tableData.link;
          this.form.detailList = tableData.detailList;
          const API =
            this.dialogType == 'add'
              ? invoiceApplySaveAPI
              : invoiceApplyUpdateAPI;
          const id = await API(this.form);
          if (this.form.sourceType == 2) {
            updateContractStatus([this.form.sourceId]);
          }
          if (flag) {
            await this.handleSub(id);
            return;
          }
          this.$message.success('操作成功');
          this.done();
          this.cancel();
        });
      },
      //提交-开启流程
      async handleSub(id = '') {
        let data = await invoiceApplyInfoAPI(id);
        this.processSubmitDialogFlag = true;
        let key =
          data.type == 1 ? 'fin_invoice_apply' : 'fin_invoice_receive_apply';
        this.$nextTick(() => {
          let params = {
            businessId: data.id,
            businessKey: key,
            formCreateUserId: data.createUserId,
            variables: {
              type: data.type,
              businessCode: data.code,

              businessName: data.companyName,
              businessType: data.type == 1 ? '开票' : '收票'
            }
            // callBackMethodType : '1',
            // callBackMethod : 'proTargetPlanApproveApiImpl.updatePlanApprovalStatus',
            // pcHandle : '/bpm/handleTask/components/project-manage/plan-manage/submit.vue',
            // pcView : '/bpm/handleTask/components/project-manage/plan-manage/detailDialog.vue',
            // miniHandle : '',
            // miniView : '',
          };
          this.$refs.processSubmitDialogRef.init(params);
        });
        // try {
        //   await invoiceApplySubmit({
        //     businessId: id || this.form.id,
        //     type: this.form.type
        //   });
        // } catch (e) {
        //   this.$message.error(e.message);
        // }
      },
      reload() {
        this.done();
        this.cancel();
      },
      //刷新主列表数据
      done() {
        this.$emit('reload');
      },
      //关闭弹窗
      cancel() {
        this.$emit('update:addOrEditDialogFlag', false);
      }
    }
  };
</script>
<style scoped lang="scss"></style>
