<template xmlns:v-slot="http://www.w3.org/1999/XSL/Transform">
  <div>
    <el-dialog
      :title="title"
      :close-on-click-modal="false"
      v-dialogDrag
      width="1200px"
      @close="close"
      append-to-body
      @keyup.enter.native="submit"
      :visible.sync="visible">
    <el-form size="middle" :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view'?'readonly':''"  :disabled="method === 'view'"
             label-width="160px" @submit.native.prevent>
      <el-divider content-position="left"><i class="el-icon-document"></i>
        基本信息
        <el-button style="margin-left: 20px" type="primary" :disabled="method === 'view'" size="mini" @click="insertEvent('base')"  plain>
          新增
        </el-button>
      </el-divider>
      <el-row  :gutter="15">
        <vxe-table
          border
          show-overflow
          show-footer
          ref="baseTable"
          :key="baseKey"
          class="vxe-table-element"
          :data="inputForm.financeInvoiceBaseDTOList"
          style="margin-left: 5em"
          @cell-click=""
          @edit-closed=""
          highlight-current-row
          :edit-config="{trigger: 'click', mode: 'cell', showStatus: true, autoClear: true, icon: '-'}"
        >
          <vxe-table-column field="programName" align="center" title="项目名称" :edit-render="{}">
            <template v-slot:edit="scope">
              <el-input @focus="openProgramPageForm(scope.$rowIndex)" placeholder="请填写项目名称" :readonly="true" v-model="scope.row.programName"/>
            </template>
          </vxe-table-column>
          <vxe-table-column field="contractName" align="center" title="合同名称" :edit-render="{}">
            <template v-slot:edit="scope">
              <el-input @focus="openContractForm()" placeholder="请填写合同名称" :readonly="true" v-model="scope.row.contractName"/>
            </template>
          </vxe-table-column>
          <vxe-table-column field="programNo" align="center" title="项目编号" :edit-render="{}">
            <template v-slot:edit="scope">
              <el-input :readonly="true" placeholder="请填写项目编号" v-model="scope.row.programNo"/>
            </template>
          </vxe-table-column>
          <!--          <vxe-table-column field="clientName" title="委托方" :edit-render="{}">-->
          <!--            <template v-slot:edit="scope">-->
          <!--              <el-input :readonly="true" placeholder="请填写委托方" v-model="scope.row.clientName"/>-->
          <!--            </template>-->
          <!--          </vxe-table-column>-->
          <!--            <vxe-table-column field="reportNo" title="报告号" :edit-render="{}">-->
          <!--              <template v-slot:edit="scope">-->
          <!--                <el-input v-model="scope.row.reportNo" placeholder="请填写报告号"/>-->
          <!--              </template>-->
          <!--            </vxe-table-column>-->
          <vxe-table-column title="操作" align="center" width="100">
            <template v-slot="scope">
              <el-button size="mini" type="danger" @click="removeEvent(scope.row,scope.$rowIndex,'base')">删除</el-button>
            </template>
          </vxe-table-column>
        </vxe-table>
      </el-row>
      <el-divider content-position="left"><i class="el-icon-document"></i> 发票详情</el-divider>
      <el-row  :gutter="15">
        <el-col :span="12">
          <el-form-item label="发票类型" prop="type"
                        :rules="[
                        {required: true, message:'发票类型不能为空', trigger:'blur'}
               ]">
            <el-radio v-model="inputForm.type" v-for="item in $dictUtils.getDictList('invoice_type')" :label="item.value" size="small" style="margin-right: 20px">
              {{item.label}}</el-radio>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="发票申请编号" prop="no"
                        :rules="[
               ]">
            <el-input :disabled="true" placeholder="请填写发票申请编号" v-model="inputForm.no"clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="开票类型" prop="billingType"
                        :rules="[
                        {required: true, message:'开票类型不能为空', trigger:'blur'}
               ]">
            <el-radio v-model="inputForm.billingType" @change="changeRadio" v-for="item in $dictUtils.getDictList('invoice_billing_type')" :label="item.value" size="small" style="margin-right: 20px">
              {{item.label}}</el-radio>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="15">
        <el-col v-if="inputForm.billingType === '2'" :span="12">
          <el-form-item label="姓名" prop="name"
                        :rules="[
                        {required: true, message:'姓名不能为空', trigger:'blur'}
               ]">
            <SelectUserTree
              ref="companyTree"
              size="medium"
              :props="{
                value: 'id',             // ID字段名
                label: 'name',         // 显示名称
                children: 'children'    // 子级字段名
              }"
              :url="`/sys/user/treeUserDataAllOffice?type=2`"
              :value="inputForm.name"
              :clearable="true"
              :accordion="true"
              @getValue="(value) => {inputForm.name=value}"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="15">
        <el-col v-if="inputForm.billingType === '1'" :span="12">
          <el-form-item label="实际开票单位" prop="billingWorkplaceReal"
                        :rules="[
                        {required: true, message:'实际开票单位不能为空', trigger:'blur'},{required: true, message:'实际开票单位不能为空', trigger:'change'}
               ]">
            <el-input :readonly="true" placeholder="请填写实际开票单位" v-model="inputForm.billingWorkplaceReal" @focus="openWorkClientForm()" clearable></el-input>
          </el-form-item>
        </el-col>
        <div v-if="inputForm.type === '1'">
          <el-col v-if="inputForm.billingType === '1'" :span="12">
            <el-form-item label="纳税人识别号" prop="taxpayerIdentificationNo"
                          :rules="[
                      {required: true, message:'纳税人识别号不能为空', trigger:'blur'},{required: true, message:'纳税人识别号不能为空', trigger:'change'}
             ]">
              <el-input v-model="inputForm.taxpayerIdentificationNo" placeholder="请填写纳税人识别号" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col v-if="inputForm.billingType === '1'" :span="12">
            <el-form-item label="地址" prop="address"
                          :rules="[
                      {required: true, message:'地址不能为空', trigger:'blur'},{required: true, message:'地址不能为空', trigger:'change'}
             ]">
              <el-input v-model="inputForm.address" placeholder="请填写地址"clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col v-if="inputForm.billingType === '1'" :span="12">
            <el-form-item label="电话" prop="telPhone"
                          :rules="[
                      {required: true, message:'电话不能为空', trigger:'blur'},{required: true, message:'电话不能为空', trigger:'change'}
             ]">
              <el-input v-model="inputForm.telPhone" :readonly="commonJS.isNotEmpty(inputForm.billingId)" placeholder="请填写电话">
                <el-button slot="append" icon="el-icon-search" @click="openBillingChoose()"></el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col v-if="inputForm.billingType === '1'" :span="12">
            <el-form-item label="开户银行" prop="openBank"
                          :rules="[
                      {required: true, message:'开户银行不能为空', trigger:'blur'},{required: true, message:'开户银行不能为空', trigger:'change'}
             ]">
              <el-select v-model="inputForm.openBank" @change="changeBank" placeholder="请选择开户银行" clearable style="width: 100%;"clearable>
                <el-option
                  v-for="item in bankList"
                  :key="item.id"
                  :label="item.ourBank"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-if="inputForm.billingType === '1'" :span="12">
            <el-form-item label="银行账号" prop="bankAccount"
                          :rules="[
                      {required: true, message:'银行账号不能为空', trigger:'blur'},{required: true, message:'银行账号不能为空', trigger:'change'}
             ]">
              <el-input :disabled="true" placeholder="请填写银行账号" v-model="inputForm.bankAccount"clearable></el-input>
            </el-form-item>
          </el-col>
        </div>
        <div v-if="inputForm.type !== '1'">
          <el-col v-if="inputForm.billingType === '1'" :span="12">
            <el-form-item label="纳税人识别号" prop="taxpayerIdentificationNo"
                          :rules="[
             ]">
              <el-input v-model="inputForm.taxpayerIdentificationNo" placeholder="请填写纳税人识别号"clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col v-if="inputForm.billingType === '1'" :span="12">
            <el-form-item label="地址" prop="address"
                          :rules="[
             ]">
              <el-input v-model="inputForm.address" placeholder="请填写地址" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col v-if="inputForm.billingType === '1'" :span="12">
            <el-form-item label="电话" prop="telPhone"
                          :rules="[
             ]">
              <el-input v-model="inputForm.telPhone" :readonly="commonJS.isNotEmpty(inputForm.billingId)" placeholder="请填写电话">
                <el-button slot="append" icon="el-icon-search" @click="openBillingChoose()"></el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col v-if="inputForm.billingType === '1'" :span="12">
            <el-form-item label="开户银行" prop="openBank"
                          :rules="[
             ]">
              <el-select v-model="inputForm.openBank" @change="changeBank" placeholder="请选择开户银行" clearable style="width: 100%;"clearable>
                <el-option
                  v-for="item in bankList"
                  :key="item.id"
                  :label="item.ourBank"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-if="inputForm.billingType === '1'" :span="12">
            <el-form-item label="银行账号" prop="bankAccount"
                          :rules="[
             ]">
              <el-input :disabled="true" placeholder="请填写银行账号" v-model="inputForm.bankAccount"clearable></el-input>
            </el-form-item>
          </el-col>
        </div>

        <el-col :span="12">
          <el-form-item label="收款类型" prop="receivablesType"
                        :rules="[
                        {required: true, message:'收款类型不能为空', trigger:'blur'}
               ]">
            <el-select v-model="inputForm.receivablesType" placeholder="请选择收款类型" clearable style="width: 100%;"clearable>
              <el-option
                v-for="item in $dictUtils.getDictList('invoice_receivables_type')"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="开票内容" prop="billingContent"
                        :rules="[
                        {required: true, message:'开票内容不能为空', trigger:'blur'}
               ]">
            <el-select v-model="inputForm.billingContent" placeholder="请选择开票内容" clearable style="width: 100%;"clearable>
              <el-option
                v-for="item in $dictUtils.getDictList('invoice_billing_content')"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="发票金额(元)" prop="account"
                        :rules="[
                        {required: true, message:'发票金额不能为空', trigger:'blur'}
               ]">
            <el-input
              @input="fixedAccount"
              placeholder="请填写发票金额"
              maxlength="15"
              v-model="inputForm.account"
            >
            </el-input>
            <!--            <el-input-number-->
            <!--              v-model="inputForm.account"-->
            <!--              controls-position="right"-->
            <!--              :controls="false"-->
            <!--              style="width:100%;"-->
            <!--              :max="999999999999999"-->
            <!--              :precision="2"-->
            <!--              placeholder="请填写发票金额"-->
            <!--              :step="0.01"-->
            <!--              clearable>-->
            <!--            </el-input-number>-->
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否多张开票" prop="isMultiple"
                        :rules="[
                        {required: true, message:'是否多张开票不能为空', trigger:'blur'}
               ]">
            <el-radio v-model="inputForm.isMultiple" v-for="item in yesNoFlag" :label="item.value" size="small" style="margin-right: 20px">
              {{item.label}}
            </el-radio>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="开票内容要求" prop="billingContentTerms"
                        :rules="[
               ]">
            <el-input type="textarea" maxlength="500" v-model="inputForm.billingContentTerms" placeholder="开票内容要求" show-word-limit></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="开票人" prop="billingPeople"
                        :rules="[
               ]">
            <el-input :disabled="true" v-model="inputForm.billingPeople" placeholder="请选择开票人" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-form size="middle" :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view'?'readonly':''"  :disabled="true"
                 label-width="160px" @submit.native.prevent>
          <el-col v-if="status === 'audit'" :span="12" >
            <el-form-item label="开票时间" prop="billingDate"
                          :rules="[
                         {required: true, message:'开票时间不能为空', trigger:'blur'}
                 ]">
              <el-date-picker
                v-model="inputForm.billingDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择开票时间"
                style="width:100%"
                placement="bottom-start"
                clearable>
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col v-if="status !== 'audit'" :span="12" >
            <el-form-item label="开票时间" prop="billingDate"
                          :rules="[
                 ]">
              <el-date-picker
                v-model="inputForm.billingDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择开票时间"
                style="width:100%"
                placement="bottom-start"
                clearable>
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="领票时间" prop="collectDate"
                          :rules="[
                 ]">
              <el-date-picker
                v-model="inputForm.collectDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择领票时间"
                style="width:100%"
                placement="bottom-start"
                clearable>
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-form>
        <el-col :span="12">
          <el-form-item label="实际开票人" prop="billingPeopleReal"
                        :rules="[
                        {required: true, message:'实际开票人不能为空', trigger:'blur'},
                        {required: true, message:'实际开票人不能为空', trigger:'change'}
               ]">
            <SelectUserTree
              ref="companyTree"
              size="medium"
              :props="{
                value: 'id',             // ID字段名
                label: 'name',         // 显示名称
                children: 'children'    // 子级字段名
              }"
              :url="`/sys/user/treeUserDataAllOffice?type=2`"
              :value="inputForm.billingPeopleReal"
              :clearable="true"
              :accordion="true"
              @getValue="(value) => {inputForm.billingPeopleReal=value}"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="对账人" prop="reconciliationPeople"
                        :rules="[
                        {required: true, message:'对账人不能为空', trigger:'blur'},
                        {required: true, message:'对账人不能为空', trigger:'change'}
               ]">
            <SelectUserTree
              ref="companyTree"
              size="medium"
              :props="{
                value: 'id',             // ID字段名
                label: 'name',         // 显示名称
                children: 'children'    // 子级字段名
              }"
              :url="`/sys/user/treeUserDataAllOffice?type=2`"
              :value="inputForm.reconciliationPeople"
              :clearable="true"
              :accordion="true"
              @getValue="(value) => {inputForm.reconciliationPeople=value}"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="对账地区" prop="reconciliationArea"
                        :rules="[
                        {required: true, message:'对账地区不能为空', trigger:'blur'},
                        {required: true, message:'对账地区不能为空', trigger:'change'}
               ]">
            <SelectTree
              ref="areaTree"
              :props="{
                    value: 'id',             // ID字段名
                    label: 'name',         // 显示名称
                    children: 'children'    // 子级字段名
                  }"
              url="/sys/area/treeData"
              :value="inputForm.reconciliationArea"
              :clearable="true"
              size="medium"
              :accordion="true"
              @getValue="(value) => {inputForm.reconciliationArea=value}"/>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="remarks"
                        :rules="[
               ]">
            <el-input maxlength="500" type="textarea" placeholder="请填写备注" v-model="inputForm.remarks"show-word-limit></el-input>
          </el-form-item>
        </el-col>
      </el-row>


      <el-form :disabled="true">
        <el-divider content-position="left"><i class="el-icon-document"></i>
          发票明细
          <el-button style="margin-left: 20px" type="primary" :disabled="true" size="mini" @click="insertEvent('detail')" plain>
            新增
          </el-button>
          <el-popover
            placement="top"
            width="400"
            v-model="importVisible">
            <p>请先下载模板，然后再进行导入操作</p>
            <el-row :gutter="1">
              <el-col :span="6">
                <el-button :disabled="true" type="success" size="small" @click="downloadTpl">下载模板</el-button>
              </el-col>
              <el-col :span="6">
                <el-upload
                  action=""
                  :auto-upload="false"
                  :on-change="beforeUploadDetail"
                  :show-file-list="false">
                  <el-button :disabled="true" size="small" type="primary">导入全部</el-button>
                </el-upload>
              </el-col>
              <el-col :span="6">
                <el-upload
                  action=""
                  :auto-upload="false"
                  :on-change="beforeUploadDetailCode"
                  :show-file-list="false">
                  <el-button :disabled="true" size="small" type="primary" >仅导入当前纳税人识别号</el-button>
                </el-upload>
              </el-col>
            </el-row>
            <div style="text-align: right; margin-top: 10px;margin-right: 10px;">
              <el-button size="mini" :disabled="true" type="default" @click="importVisible = false" plain>取消</el-button>
              <!--            <el-button type="primary" size="mini" @click="importVisible = false">确定</el-button>-->
            </div>
            <el-button style="margin-left: 20px" slot="reference" :disabled="true" type="warning" size="mini" plain>导入</el-button>
          </el-popover>
        </el-divider>
      </el-form>

      <el-form size="middle" :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view'?'readonly':''"  :disabled="true"
               label-width="160px" @submit.native.prevent>
        <el-row  :gutter="15">
          <vxe-table
            border
            show-overflow
            show-footer
            ref="detailTable"
            :key="detailKey"
            class="vxe-table-element"
            :data="inputForm.financeInvoiceDetailDTOList"
            style="margin-left: 5em"
            @cell-click=""
            @edit-closed=""
            highlight-current-row
            :edit-config="{trigger: 'click', mode: 'cell', showStatus: true, autoClear: true}"
          >
            <vxe-table-column field="code" title="发票代码" :edit-render="{}">
              <template v-slot:edit="scope">
                <el-input v-model="scope.row.code" placeholder="请填写发票代码"/>
              </template>
            </vxe-table-column>
            <vxe-table-column field="number" title="发票号" :edit-render="{}">
              <template v-slot:edit="scope">
                <el-input
                  oninput ="value=value.replace(/\D|^/g,'')"
                  placeholder="请填写发票号"
                  maxlength="8"
                  @blur="checkNumber(scope.row,scope.$rowIndex)"
                  v-model="scope.row.number"
                  clearable>
                </el-input>
              </template>
            </vxe-table-column>
            <vxe-table-column field="account" title="开票金额(元)" :edit-render="{}">
              <template v-slot:edit="scope">
                <el-input-number
                  @blur="checkAccount(scope.row,scope.$rowIndex)"
                  v-model="scope.row.account"
                  controls-position="right"
                  :controls="false"
                  style="width:100%;"
                  :max="999999999999999"
                  :precision="2"
                  placeholder="请填写开票金额"
                  :step="0.01"
                  :min="0">
                </el-input-number>
              </template>
            </vxe-table-column>
            <vxe-table-column field="rate" title="税率(%)" :edit-render="{}">
              <template v-slot:edit="scope">
                <el-input-number
                  @blur="checkRate(scope.row, scope.$rowIndex)"
                  v-model="scope.row.rate"
                  controls-position="right"
                  :controls="false"
                  style="width:100%;"
                  :precision="2"
                  placeholder="请填写税率"
                  :step="0.01"
                  :min="0"
                  clearable>
                </el-input-number>
              </template>
            </vxe-table-column>
            <vxe-table-column field="amount" title="金额" :edit-render="{}">
              <template v-slot:edit="scope">
                <el-input :readonly="true" v-model="scope.row.amount" placeholder="请填写金额"/>
              </template>
            </vxe-table-column>
            <vxe-table-column field="tax" title="税额" :edit-render="{}">
              <template v-slot:edit="scope">
                <el-input :readonly="true" v-model="scope.row.tax" placeholder="请填写税额"/>
              </template>
            </vxe-table-column>
            <vxe-table-column field="allAmount" title="累计登记金额" :edit-render="{}">
              <template v-slot:edit="scope">
                <el-input-number
                  v-model="scope.row.allAmount"
                  controls-position="right"
                  :controls="false"
                  style="width:100%;"
                  :precision="2"
                  placeholder="请填写累计登记金额"
                  :step="0.01"
                  :min="0"
                  clearable>
                </el-input-number>
              </template>
            </vxe-table-column>
            <vxe-table-column title="操作" width="100">
              <template v-slot="scope">
                <el-button size="mini" type="danger" @click="removeEvent(scope.row,scope.$rowIndex,'detail')">删除</el-button>
              </template>
            </vxe-table-column>
          </vxe-table>
        </el-row>
      </el-form>
      <div v-if="false">
        <el-divider content-position="left"><i class="el-icon-document"></i>
          收款明细
          <el-button style="margin-left: 20px" :disabled="method === 'view'" type="primary" size="mini" @click="insertEvent('receivables')" plain>
            新增
          </el-button>
        </el-divider>
        <el-row  :gutter="15">
          <vxe-table
            border
            show-overflow
            show-footer
            ref="receivablesTable"
            :key="receivablesKey"
            class="vxe-table-element"
            :data="inputForm.financeInvoiceReceivablesDTOList"
            style="margin-left: 5em"
            @cell-click=""
            @edit-closed=""
            highlight-current-row
            :edit-config="{trigger: 'click', mode: 'cell', showStatus: true, autoClear: true}"
          >
            <vxe-table-column field="remittanceUnit" title="汇款单位" :edit-render="{}">
              <template v-slot:edit="scope">
                <el-input v-model="scope.row.remittanceUnit" placeholder="请填写汇款单位"/>
              </template>
            </vxe-table-column>
            <vxe-table-column field="remittanceAmount" title="汇款金额(元)" :edit-render="{}">
              <template v-slot:edit="scope">
                <el-input-number
                  v-model="scope.row.remittanceAmount"
                  controls-position="right"
                  :controls="false"
                  style="width:100%;"
                  :precision="2"
                  placeholder="请填写汇款金额"
                  :step="0.01"
                  :min="0"
                  clearable>
                </el-input-number>
              </template>
            </vxe-table-column>
            <vxe-table-column field="remittanceDate" title="汇款时间" :edit-render="{}">
              <template v-slot:edit="scope">
                <el-input v-model="scope.row.remittanceDate" type="date" transfer placeholder="请填写汇款时间"/>
              </template>
            </vxe-table-column>
            <vxe-table-column title="操作" width="100">
              <template v-slot="scope">
                <el-button size="mini" type="danger" @click="removeEvent(scope.row,scope.$rowIndex,'receivables')">删除</el-button>
              </template>
            </vxe-table-column>
          </vxe-table>
        </el-row>
        <el-divider content-position="left"><i class="el-icon-document"></i>发票作废</el-divider>
        <el-row :gutter="15">
          <el-col :span="24">
            <el-form-item label="作废原因" prop="financeInvoiceInvalidDTO.remarks"
                          :rules="[
                        {required: true, message:'作废原因不能为空', trigger:'blur'}
               ]">
              <el-input maxlength="500" type="textarea" placeholder="请填写作废原因" v-model="inputForm.financeInvoiceInvalidDTO.remarks" show-word-limit></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>
    <!--        附件-->
    <UpLoadComponent ref="uploadComponent"></UpLoadComponent>
    <ProgramPageForm ref="programPageForm" @getProgram="getProgram"></ProgramPageForm>
    <ContractForm  ref="contractForm" @getContract="getContract"></ContractForm>
    <WorkClientForm  ref="workClientForm" @getWorkClientRadioChoose="getWorkClient"></WorkClientForm>
    <WorkClientBillingChooseRadio ref="billingChoose" @getBilling="getBilling"></WorkClientBillingChooseRadio>


      <span slot="footer" class="dialog-footer">
      <el-button size="small" :loading="loading" @click="close()" icon="el-icon-circle-close">关闭</el-button>
      <el-button size="small" :loading="loading" type="primary" v-if="method != 'view'" @click="submit()" icon="el-icon-circle-check" v-noMoreClick>确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import FinanceInvoiceService from '@/api/cw/invoice/CwFinanceInvoiceService'
  import WorkClientService from '@/api/cw/workClientInfo/WorkClientService'
  import ProgramPageForm from './ProgramPageForm'
  import UpLoadComponent from '@/views/common/UpLoadComponent'
  import ContractForm from '../projectRecords/WorkContractChooseCom'
  import WorkClientForm from '../workClientInfo/WorkClientChooseRadio'
  import SelectUserTree from '@/views/modules/utils/treeUserSelect'
  import SelectTree from '@/components/treeSelect/treeSelect.vue'
  import WorkClientBillingChooseRadio from '@/views/modules/cw/workClientInfo/WorkClientBillingChooseRadio'

  export default {
    props: {
      businessId: {
        type: String,
        default: ''
      },
      formReadOnly: {
        type: Boolean,
        default: false
      },
      status: {
        type: String,
        default: ''
      }
    },
    data () {
      return {
        title: '',
        method: '',
        visible: false,
        loading: false,
        inputForm: {
          id: '',
          financeInvoiceBaseDTOList: [],
          programName: '',
          contractName: '',
          programNo: '',
          clientName: '',
          reportNo: '',
          type: '1',
          no: '',
          billingType: '1',
          billingWorkplaceReal: '',
          billingWorkplaceRealId: '',
          taxpayerIdentificationNo: '',
          address: '',
          telPhone: '',
          openBank: '',
          bankAccount: '',
          receivablesType: '2',
          billingContent: '',
          account: '',
          billingContentTerms: '',
          billingPeople: JSON.parse(localStorage.getItem('user')).name,
          billingPeopleId: JSON.parse(localStorage.getItem('user')).id,
          billingDate: '',
          collectDate: '',
          billingPeopleReal: JSON.parse(localStorage.getItem('user')).id,
          reconciliationPeople: '',
          reconciliationArea: '',
          remarks: '',
          name: '',
          status: '',
          procInsId: '',
          processDefinitionId: '',
          workAttachmentDtoList: [],
          financeInvoiceDetailDTOList: [],
          financeInvoiceReceivablesDTOList: [],
          financeInvoiceInvalidDTO: {},
          isMultiple: '',
          billingId: ''
        },
        programRow: '',
        bankList: [],
        err: '',
        keyWatch: '',
        importVisible: false,
        yesNoFlag: [{label: '否', value: '0'}, {label: '是', value: '1'}],
        baseKey: '',
        detailKey: '',
        receivablesKey: ''
      }
    },
    financeInvoiceService: null,
    workClientService: null,
    created () {
      this.financeInvoiceService = new FinanceInvoiceService()
      this.workClientService = new WorkClientService()
    },
    mounted () {
    },
    components: {
      ProgramPageForm,
      ContractForm,
      WorkClientForm,
      SelectUserTree,
      SelectTree,
      UpLoadComponent,
      WorkClientBillingChooseRadio
    },
    computed: {
      bus: {
        get () {
          this.$refs.uploadComponent.setDividerName('附件')
          return this.businessId
        },
        set (val) {
          this.businessId = val
        }
      }
    },
    watch: {
      'keyWatch': {
        handler (newVal) {
          if (this.commonJS.isNotEmpty(this.bus)) {
            this.init('', this.bus)
          } else {
            this.$nextTick(() => {
              this.$refs.inputForm.resetFields()
            })
          }
        }
      },
      'loading': {
        handler (newVal) {
          // this.$emit('changeLoading', newVal)
          this.$refs.uploadComponent.changeLoading(newVal)
        }
      }
    },
    methods: {
      getKeyWatch (keyWatch) {
        this.keyWatch = keyWatch
      },
      init (method, id) {
        this.importVisible = false
        this.method = method
        if (this.commonJS.isEmpty(id)) {
          id = 'false'
        }
        this.inputForm = {
          id: '',
          financeInvoiceBaseDTOList: [],
          programName: '',
          contractName: '',
          programNo: '',
          clientName: '',
          reportNo: '',
          type: '1',
          no: '',
          billingType: '1',
          billingWorkplaceReal: '',
          billingWorkplaceRealId: '',
          taxpayerIdentificationNo: '',
          address: '',
          telPhone: '',
          openBank: '',
          bankAccount: '',
          receivablesType: '2',
          billingContent: '',
          account: '',
          billingContentTerms: '',
          billingPeople: JSON.parse(localStorage.getItem('user')).name,
          billingPeopleId: JSON.parse(localStorage.getItem('user')).id,
          billingDate: '',
          collectDate: '',
          billingPeopleReal: JSON.parse(localStorage.getItem('user')).id,
          reconciliationPeople: '',
          reconciliationArea: '',
          remarks: '',
          name: '',
          status: '',
          procInsId: '',
          processDefinitionId: '',
          workAttachmentDtoList: [],
          financeInvoiceDetailDTOList: [],
          financeInvoiceReceivablesDTOList: [],
          financeInvoiceInvalidDTO: {
            id: '',
            invalidStatus: '',
            invoiceId: '',
            remarks: ''
          },
          isMultiple: '',
          billingId: ''
        }
        if (method === 'add') {
          this.title = `新建发票`
        } else if (method === 'edit') {
          this.title = '修改发票信息'
        } else if (method === 'view') {
          this.title = '查看发票信息'
        }
        this.inputForm.id = id
        this.visible = true
        this.loading = false
        this.$nextTick(() => {
          this.$refs.inputForm.resetFields()
          this.loading = true
          this.financeInvoiceService.queryById(this.inputForm.id).then(({data}) => {
            this.$refs.uploadComponent.clearUpload()
            this.inputForm = this.recover(this.inputForm, data)
            this.inputForm = JSON.parse(JSON.stringify(this.inputForm))
            if (!this.commonJS.isEmpty(this.inputForm.billingWorkplaceRealId)) {
              this.bankList = []
              this.workClientService.queryById(this.inputForm.billingWorkplaceRealId).then((data) => {
                if (this.commonJS.isNotEmpty(data.data.cwWorkClientBillingDTOList)) {
                  data.data.cwWorkClientBillingDTOList.forEach(i => {
                    i.ourBank = i.accountHolder
                    this.bankList.push(i)
                  })
                } else {
                  this.bankList = []
                }
              })
            }

            if (this.commonJS.isEmpty(this.inputForm.type)) {
              this.inputForm.type = '1'
            }
            if (this.commonJS.isEmpty(this.inputForm.billingType)) {
              this.inputForm.billingType = '1'
            }
            if (this.commonJS.isEmpty(this.inputForm.receivablesType)) {
              this.inputForm.receivablesType = '2'
            }
            if (this.commonJS.isEmpty(this.inputForm.billingPeople)) {
              this.inputForm.billingPeople = JSON.parse(localStorage.getItem('user')).name
            }
            if (this.commonJS.isEmpty(this.inputForm.billingPeopleId)) {
              this.inputForm.billingPeopleId = JSON.parse(localStorage.getItem('user')).id
            }
            if (this.commonJS.isEmpty(this.inputForm.billingPeopleReal)) {
              this.inputForm.billingPeopleReal = JSON.parse(localStorage.getItem('user')).id
            }
            if (this.commonJS.isEmpty(this.inputForm.financeInvoiceBaseDTOList)) {
              this.inputForm.financeInvoiceBaseDTOList = []
            }
            if (this.commonJS.isEmpty(this.inputForm.workAttachmentDtoList) || this.inputForm.workAttachmentDtoList.length === 0) {
              this.inputForm.workAttachmentDtoList = []
            }
            if (this.commonJS.isEmpty(this.inputForm.financeInvoiceReceivablesDTOList) || this.inputForm.financeInvoiceReceivablesDTOList.length === 0) {
              this.inputForm.financeInvoiceReceivablesDTOList = []
            }
            if (this.commonJS.isEmpty(this.inputForm.isMultiple) && this.status !== 'taskFormDetail') {
              // 是否多张开票  默认为 0 否
              this.inputForm.isMultiple = '0'
            }
            if (this.status === 'audit' || this.status === 'taskFormDetail') {
              method = 'view'
            }
            if (this.status === 'audit') {
              if (this.commonJS.isEmpty(this.inputForm.billingDate)) {
                this.inputForm.billingDate = this.moment(new Date()).format('YYYY-MM-DD')
              }
            }
            if (!this.commonJS.isEmpty(this.status) && this.status === 'audit' && (this.commonJS.isEmpty(this.inputForm.financeInvoiceDetailDTOList) || this.inputForm.financeInvoiceDetailDTOList.length === 0)) {
              this.inputForm.financeInvoiceDetailDTOList = []
              this.inputForm.financeInvoiceDetailDTOList.push({
                code: '',
                number: '',
                account: this.inputForm.account,
                rate: '',
                amount: '',
                tax: '',
                allAmount: ''
              })
            }
            this.$refs.uploadComponent.newUpload(method, this.inputForm.workAttachmentDtoList, 'invoice')
            this.loading = false
          })
        })
      },
      saveForm (callback) {
        this.doSubmit('save', callback)
      },
      startForm (callback) {
        this.loading = true
        if (this.commonJS.isNotEmpty(this.inputForm.id)) {
          this.financeInvoiceService.queryById(this.inputForm.id).then(({data}) => {
            if (data.status !== '0' && data.status !== '1' && data.status !== '3') { // 审核状态不是“未发起”或“暂存”或“撤回”，就弹出提示
              this.loading = false
              this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
              throw new Error()
            } else {
              this.doSubmit('start', callback)
            }
          })
        } else {
          this.doSubmit('start', callback)
        }
      },
      async agreeForm (callback) {
        this.loading = true
        await this.financeInvoiceService.queryById(this.inputForm.id).then(({data}) => {
          if (data.status !== '2') { // status的值不等于“审核中”，就弹出提示
            this.loading = false
            this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
            throw new Error()
          } else {
            this.doSubmit('agree', callback)
          }
        })
      },
      reapplyForm (callback) {
        this.loading = true
        this.financeInvoiceService.queryById(this.inputForm.id).then(({data}) => {
          if (data.status !== '4') { // 审核状态不是“驳回”，就弹出提示
            this.loading = false
            this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
            throw new Error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
          } else {
            this.doSubmit('reapply', callback)
          }
        })
      },
      submit () {
        this.loading = true
        if (this.$refs.uploadComponent.checkProgress()) {
          this.loading = false
          throw new Error()
        } else {
          if (this.commonJS.isEmpty(this.inputForm.financeInvoiceBaseDTOList)) {
            this.loading = false
            this.$message.error('至少新增一条基本信息')
            throw new Error()
          } else {
            if (this.inputForm.financeInvoiceBaseDTOList.length === 0) {
              this.loading = false
              this.$message.error('至少新增一条基本信息')
              throw new Error()
            }
          }
          if (this.commonJS.isNotEmpty(this.inputForm.financeInvoiceBaseDTOList)) {
            let i = this.inputForm.financeInvoiceBaseDTOList.length
            for (let j = 0; j < i; j++) {
              if (this.commonJS.isEmpty(this.inputForm.financeInvoiceBaseDTOList[j].programName)) {
                this.loading = false
                this.$message.error('第' + (j + 1) + '行的基本信息不能为空')
                throw new Error()
              }
            }
          }
          this.$refs['inputForm'].validate((valid) => {
            if (valid) {
              this.loading = true
              this.inputForm.workAttachmentDtoList = this.$refs.uploadComponent.getDataList()
              if (this.inputForm.isMultiple === '1') {
                // 是否多张开票,若选择是,则附件必须上传文件
                if (this.commonJS.isEmpty(this.inputForm.workAttachmentDtoList)) {
                  this.loading = false
                  this.$message.error('需上传开票明细相关文件')
                  throw new Error('需上传开票明细相关文件')
                }
              }
              this.financeInvoiceService.saveForm(this.inputForm).then(({data}) => {
                this.$refs.inputForm.resetFields()
                this.close()
                this.$emit('refreshDataList')
                this.loading = false
              }).catch(() => {
                this.loading = false
              })
            } else {
              this.loading = false
            }
          })
        }
      },
      // 表单提交
      async doSubmit (status, callback) {
        this.loading = true
        if (await this.$refs.uploadComponent.checkProgress()) {
          this.loading = false
          throw new Error()
        }
        if (status === 'save') {
          // 暂存
          this.loading = true
          this.inputForm.status = '1'
          this.inputForm.workAttachmentDtoList = this.$refs.uploadComponent.getDataList()
          this.financeInvoiceService.saveForm(this.inputForm).then(({data}) => {
            callback(data.businessTable, data.businessId, this.inputForm)
            this.loading = false
          }).catch(() => {
            this.loading = false
          })
          return
        } else if (status === 'start') {
          // 送审  待审核
          this.inputForm.status = '2'
        } else if (status === 'agree') {
          // 审核同意
          this.inputForm.status = '5'
        } else if (status === 'reapply') {
          this.inputForm.status = '2'
        }
        if (this.commonJS.isEmpty(this.inputForm.financeInvoiceBaseDTOList)) {
          this.loading = false
          this.$message.error('至少新增一条基本信息')
          throw new Error()
        } else {
          if (this.inputForm.financeInvoiceBaseDTOList.length === 0) {
            this.loading = false
            this.$message.error('至少新增一条基本信息')
            throw new Error()
          }
        }
        if (this.commonJS.isNotEmpty(this.inputForm.financeInvoiceBaseDTOList)) {
          let i = this.inputForm.financeInvoiceBaseDTOList.length
          for (let j = 0; j < i; j++) {
            if (this.commonJS.isEmpty(this.inputForm.financeInvoiceBaseDTOList[j].programName)) {
              this.loading = false
              this.$message.error('第' + (j + 1) + '行的基本信息不能为空')
              throw new Error()
            }
          }
        }
        if (this.inputForm.status === '5') {
          let acc = 0
          this.inputForm.financeInvoiceDetailDTOList.forEach((item, index) => {
            if (this.commonJS.isEmpty(item.number)) {
              this.loading = false
              this.$message.warning('发票明细中第 ' + (index + 1) + ' 条数据的 “发票号” 为空')
              throw new Error()
            }
            if (this.commonJS.isEmpty(item.account)) {
              this.loading = false
              this.$message.warning('发票明细中第 ' + (index + 1) + ' 条数据的 “开票金额” 为空')
              throw new Error()
            }
            acc = (acc + parseFloat(parseFloat(item.account).toFixed(2)))
          })
          if (parseFloat(acc).toFixed(2) !== parseFloat(this.inputForm.account).toFixed(2)) {
            this.loading = false
            this.$message.warning('发票明细中 “开票金额”总和 与发票详情中 “发票金额” 不等')
            throw new Error()
          }
          this.inputForm.financeInvoiceDetailDTOList.forEach((item, index) => {
            this.inputForm.financeInvoiceDetailDTOList.forEach((item2, index2) => {
              if (index !== index2) {
                if (item.number === item2.number) {
                  this.loading = false
                  this.$message.warning('发票明细中第 ' + (index + 1) + ' 条数据的 “发票号” 存在重复')
                  throw new Error()
                }
              }
            })
          })
          for await (let [index, item] of this.inputForm.financeInvoiceDetailDTOList.entries()) {
            if (this.commonJS.isEmpty(item.number)) {
              this.loading = false
              this.$message.warning('发票明细中第 ' + (index + 1) + ' 条数据的 “发票号” 为空')
              this.err = true
            }
            await this.financeInvoiceService.queryByNumber(item.number, item.id).then(({data}) => {
              if (data === true) {
                this.loading = false
                this.$message.warning('发票明细中第 ' + (index + 1) + ' 条数据的 “发票号” 存在重复')
                this.err = data
              }
            })
          }
          if (this.err === true) {
            this.loading = false
            this.err = ''
            throw new Error()
          }
        }
        if (this.status === 'audit') {
          if (this.commonJS.isEmpty(this.inputForm.billingDate)) {
            this.$message.error('开票时间不可以为空')
            this.loading = false
            throw new Error('开票时间不可以为空')
          }
        }
        this.$refs['inputForm'].validate((valid) => {
          if (valid) {
            this.loading = true
            this.inputForm.workAttachmentDtoList = this.$refs.uploadComponent.getDataList()
            if (this.inputForm.isMultiple === '1') {
              // 是否多张开票,若选择是,则附件必须上传文件
              if (this.commonJS.isEmpty(this.inputForm.workAttachmentDtoList)) {
                this.loading = false
                this.$message.error('需上传开票明细相关文件')
                throw new Error('需上传开票明细相关文件')
              }
            }
            this.financeInvoiceService.saveForm(this.inputForm).then(({data}) => {
              if (status === 'start' || status === 'reapply') {
                this.inputForm.title = `${this.$store.state.user.name} 发起了 ${data.no} [财务-发票申请]`
              }
              this.inputForm.id = data.businessId
              callback(data.businessTable, data.businessId, this.inputForm)
              this.loading = false
            }).catch(() => {
              this.loading = false
            })
          } else {
            this.loading = false
          }
        })
      },
      close () {
        this.$refs.uploadComponent.clearUpload()
        this.$refs.inputForm.resetFields()
        this.inputForm = {
          id: '',
          financeInvoiceBaseDTOList: [],
          programName: '',
          contractName: '',
          programNo: '',
          clientName: '',
          reportNo: '',
          type: '1',
          no: '',
          billingType: '1',
          billingWorkplaceReal: '',
          billingWorkplaceRealId: '',
          taxpayerIdentificationNo: '',
          address: '',
          telPhone: '',
          openBank: '',
          bankAccount: '',
          receivablesType: '2',
          billingContent: '',
          account: '',
          billingContentTerms: '',
          billingPeople: '',
          billingPeopleId: '',
          billingDate: '',
          collectDate: '',
          billingPeopleReal: '',
          reconciliationPeople: '',
          reconciliationArea: '',
          remarks: '',
          name: '',
          workAttachmentDtoList: [],
          financeInvoiceDetailDTOList: [],
          financeInvoiceReceivablesDTOList: [],
          financeInvoiceInvalidDTO: {},
          isMultiple: '',
          billingId: ''
        }
        this.bankList = []
        this.visible = false
      },
      insertEvent (type) {
        if (type === 'base') {
          if (this.inputForm.financeInvoiceBaseDTOList.length >= 1) {
            if (this.commonJS.isEmpty(this.inputForm.financeInvoiceBaseDTOList[0].programId)) {
              this.$message.warning('非项目,只能有一条非项目数据')
              return
            }
          }
          this.$refs.baseTable.insertAt({})
          this.inputForm.financeInvoiceBaseDTOList.push({})
          this.baseKey = Math.random()
          // this.$refs.baseTable.insert().then((data) => {
          //   this.inputForm.financeInvoiceBaseDTOList.push(data)
          // })
        }
        if (type === 'detail') {
          this.$refs.detailTable.insert().then((data) => {
            this.inputForm.financeInvoiceDetailDTOList.push(data)
          })
        }
        if (type === 'receivables') {
          this.$refs.receivablesTable.insert().then((data) => {
            this.inputForm.financeInvoiceReceivablesDTOList.push(data)
          })
        }
      },
      // 删除
      removeEvent (row, rowIndex, type) {
        if (type === 'base') {
          this.$refs.baseTable.remove(row)
          this.inputForm.financeInvoiceBaseDTOList.splice(rowIndex, 1)
        }
        if (type === 'detail') {
          this.$refs.detailTable.remove(row)
          this.inputForm.financeInvoiceDetailDTOList.splice(rowIndex, 1)
        }
        if (type === 'receivables') {
          this.$refs.receivablesTable.remove(row)
          this.inputForm.financeInvoiceReceivablesDTOList.splice(rowIndex, 1)
        }
      },
      openProgramPageForm (rowIndex) {
        if (this.commonJS.isEmpty(this.inputForm.financeInvoiceBaseDTOList[0].programName) || this.inputForm.financeInvoiceBaseDTOList.length === 1) {
          this.$refs.programPageForm.init()
        } else {
          if (this.commonJS.isEmpty(this.inputForm.financeInvoiceBaseDTOList[0].programId)) {
            this.$refs.programPageForm.init('s')
          } else {
            this.$refs.programPageForm.init(false)
          }
        }
        this.programRow = rowIndex
      },
      getProgram (rows) {
        rows.forEach((item, index) => {
          if (index === 0) {
            let r = this.inputForm.financeInvoiceBaseDTOList[this.programRow]
            r.programName = item.projectName
            r.contractName = item.contractName
            r.programNo = item.projectNumber
            r.contractId = item.contractId
            r.programId = item.id
            this.inputForm.financeInvoiceBaseDTOList[this.programRow] = r
          } else {
            let r = {
              programName: item.projectName,
              contractName: item.contractName,
              programNo: item.projectNumber,
              contractId: item.contractId,
              programId: item.id
            }
            this.$refs.baseTable.insertAt(r)
            this.inputForm.financeInvoiceBaseDTOList.push(r)
            this.baseKey = Math.random()
          }
        })
        this.$forceUpdate()
        this.programRow = ''
        // this.inputForm.reconciliationArea = this.inputForm.financeInvoiceBaseDTOList[0].location
      },
      openContractForm () {
        if (!this.commonJS.isEmpty(this.inputForm.financeInvoiceBaseDTOList[0])) {
          if (this.commonJS.isEmpty(this.inputForm.financeInvoiceBaseDTOList[0].programId) && this.commonJS.isEmpty(this.inputForm.financeInvoiceBaseDTOList[0].programName)) {
            this.$message.warning('请先选择项目')
          } else if (this.commonJS.isEmpty(this.inputForm.financeInvoiceBaseDTOList[0].programId) && !this.commonJS.isEmpty(this.inputForm.financeInvoiceBaseDTOList[0].programName)) {
            this.$refs.contractForm.init()
          } else {
            this.$message.warning('只有非项目开票可选择合同信息')
          }
        } else {
          this.$message.warning('请选择项目信息')
        }
      },
      getContract (row) {
        this.inputForm.financeInvoiceBaseDTOList[0].contractName = row.contractName // 合同名称
        // this.inputForm.financeInvoiceBaseDTOList[0].client = row.clientId // 委托方
        // this.inputForm.financeInvoiceBaseDTOList[0].clientName = row.clientName // 委托方名称
        this.$forceUpdate()
      },
      changeRadio () {
        this.inputForm.address = ''
        this.inputForm.telPhone = ''
        this.inputForm.billingId = ''
        this.inputForm.billingWorkplaceReal = ''
        this.inputForm.billingWorkplaceRealId = ''
        this.inputForm.taxpayerIdentificationNo = ''
        this.bankList = []
        this.inputForm.bankAccount = ''
        this.inputForm.openBank = ''
        this.inputForm.name = ''
        this.$forceUpdate()
      },
      openWorkClientForm () {
        this.$refs.workClientForm.init(null, '')
      },
      getWorkClient (row) {
        this.bankList = []
        this.inputForm.billingWorkplaceReal = row.name // 实际开票单位姓名
        this.inputForm.billingWorkplaceRealId = row.id // 实际开票单位id ‘客户id’
        this.inputForm.taxpayerIdentificationNo = this.commonJS.isEmpty(row.uscCode) ? '' : row.uscCode // 纳税人识别号 ‘统一社会信用代码’
        this.inputForm.address = this.commonJS.isEmpty(row.address) ? '' : row.address // 地址
        this.inputForm.telPhone = this.commonJS.isEmpty(row.mobile) ? '' : row.mobile // 电话
        this.inputForm.billingId = '' // 实际开票单位的开票信息id
        // this.inputForm.telPhone = '' // 电话
        row.cwWorkClientBillingDTOList.forEach(item => {
          item.ourBank = item.accountHolder
          this.bankList.push(item)
        })
        this.inputForm.bankAccount = ''
        this.inputForm.openBank = ''
        this.$forceUpdate()
      },
      changeBank (value) {
        this.bankList.forEach(item => {
          if (item.id === value) {
            this.inputForm.bankAccount = item.account
          }
        })
      },
      checkNumber (row, rowIndex) {
        if (!this.commonJS.isEmpty(row.number)) {
          if (parseInt(row.number) > 99999999) {
            this.$message.warning('“发票号” 不可以大于 8 位，请重新输入')
            row.number = undefined
            return
          }
          this.inputForm.financeInvoiceDetailDTOList.forEach((item, index) => {
            if (rowIndex !== index) {
              if (row.number === item.number) {
                row.number = ''
                this.$message.warning('“发票号” 已存在，请重新输入')
                throw new Error()
              }
            }
          })
          this.financeInvoiceService.queryByNumber(row.number, row.id).then(({data}) => {
            if (data === true) {
              row.number = ''
              this.$message.warning('“发票号” 已存在，请重新输入')
            }
          })
        }
      },
      checkAccount (row, rowIndex) {
        if (this.commonJS.isEmpty(row.account)) {
          row.account = undefined
        }
        this.getAmount(row)
        this.getTax(row)
      },
      checkRate (row, rowIndex) {
        if (!this.commonJS.isEmpty(row.rate)) {
          if (parseFloat(row.rate) < 1 || parseFloat(row.rate) > 100) {
            this.$message.warning('“税率” 请填写 1 到 100 之间的数字，请重新输入')
            row.rate = undefined
          }
        }
        this.getAmount(row)
        this.getTax(row)
      },
      // 根据开票金额和税率计算出金额: 开票金额-税率*开票金额
      getAmount (row) {
        if (!this.commonJS.isEmpty(row.account) && !this.commonJS.isEmpty(row.rate)) {
          row.amount = parseFloat((parseFloat(row.account) - parseFloat((parseFloat(row.account) * parseFloat((parseFloat(row.rate) / 100).toFixed(4))).toFixed(4))).toFixed(2))
        } else {
          row.amount = undefined
        }
      },
      // 根据开票金额和税率计算出税额: 税率*开票金额
      getTax (row) {
        if (!this.commonJS.isEmpty(row.account) && !this.commonJS.isEmpty(row.rate)) {
          row.tax = parseFloat((parseFloat(row.account) * parseFloat((parseFloat(row.rate) / 100).toFixed(4))).toFixed(2))
        } else {
          row.tax = undefined
        }
      },
      // 获取发票金额，放到开票明细中第一条数据
      getTotalAccount () {
        if (!this.commonJS.isEmpty(this.inputForm.account)) {
          this.financeInvoiceDetailDTOList.push({account: this.inputForm.account})
        }
      },
      async updateStatusById (type, callback) {
        this.loading = true
        if (await this.$refs.uploadComponent.checkProgress()) {
          this.loading = false
          throw new Error()
        } else {
          if (type === 'reject' || type === 'reback') {
            this.financeInvoiceService.queryById(this.inputForm.id).then(({data}) => {
              if (data.status !== '2') { // status的值不等于“审核中”，就弹出提示
                this.loading = false
                this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
                throw new Error()
              } else {
                // if (type === 'agree') {
                //   // 同意
                //   this.inputForm.status = '5'
                // }
                if (type === 'reject') {
                  // 驳回
                  this.inputForm.status = '4'
                }
                if (type === 'reback') {
                  // 撤回
                  this.inputForm.status = '3'
                }
                if (type === 'reject' || type === 'reback') {
                  let param = {status: this.inputForm.status, id: this.inputForm.id}
                  this.financeInvoiceService.updateStatusById(param).then(() => {
                    this.loading = false
                    callback()
                  })
                }
              }
            })
          } else if (type === 'hold') {
            this.financeInvoiceService.queryById(this.inputForm.id).then(({data}) => {
              if (data.status !== '4') { // status的值不等于“驳回”就弹出提示
                this.loading = false
                this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
                throw new Error()
              } else {
                // 终止
                let param = {status: '1', id: this.inputForm.id}
                this.financeInvoiceService.updateStatusById(param).then(() => {
                  this.loading = false
                  callback()
                })
              }
            })
          }
        }
      },
      // 下载模板
      downloadTpl () {
        this.loading = true
        this.financeInvoiceService.exportTemplate().then((res) => {
          // 将二进制流文件写入excel表，以下为重要步骤
          this.$utils.downloadExcel(res.data, '发票明细导入模板')
          this.loading = false
        }).catch(function (err) {
          this.loading = false
          if (err.response) {
            console.log(err.response)
          }
        })
      },
      async detailPush (data) {
        if (this.commonJS.isNotEmpty(data)) {
          await data.forEach(item => {
            this.getAmount(item)
            this.getTax(item)
            this.inputForm.financeInvoiceDetailDTOList.push(item)
          })
        }
        this.$message.success('导入完成')
      },
      beforeUploadDetail (file) {
        const formBody = new FormData()
        formBody.append('file', file.raw)
        this.loading = true
        this.financeInvoiceService.importDetail(formBody).then(async (result) => {
          if (this.commonJS.isEmpty(result.data)) {
            this.importVisible = false
            this.loading = false
            throw new Error()
          }
          for await (let item of result.data) {
            this.inputForm.financeInvoiceDetailDTOList.forEach(detail => {
              if (item.number === detail.number) {
                this.$message.error('上传的文件中存在与页面重复的发票号，请重新填写后上传')
                this.importVisible = false
                this.loading = false
                throw new Error()
              }
            })
          }
          await this.detailPush(result.data)
          this.importVisible = false
          this.loading = false
        }).catch(() => {
          this.importVisible = false
          this.loading = false
        })
      },
      checkIdentificationNo () {
        if (this.commonJS.isEmpty(this.inputForm.taxpayerIdentificationNo)) {
          this.$message.error('当前纳税人识别号为空，导入失败')
          throw new Error()
        }
      },
      async beforeUploadDetailCode (file) {
        await this.checkIdentificationNo()
        const formBody = new FormData()
        formBody.append('file', file.raw)
        this.loading = true
        this.financeInvoiceService.importDetail(formBody).then(async result => {
          if (this.commonJS.isEmpty(result.data)) {
            this.importVisible = false
            this.loading = false
            throw new Error()
          }
          for await (let item of result.data) {
            await this.inputForm.financeInvoiceDetailDTOList.forEach(detail => {
              if (item.number === detail.number) {
                this.$message.error('上传的文件中存在与页面重复的发票号，请重新填写后上传')
                this.importVisible = false
                this.loading = false
                throw new Error()
              }
            })
          }
          this.detailPushCode(result.data)
          this.importVisible = false
          this.loading = false
        }).catch(() => {
          this.importVisible = false
          this.loading = false
        })
      },
      detailPushCode (data) {
        if (this.commonJS.isNotEmpty(data)) {
          data.forEach(item => {
            if (this.commonJS.isNotEmpty(item.taxpayerIdentificationNo)) {
              if (item.taxpayerIdentificationNo === this.inputForm.taxpayerIdentificationNo) {
                this.getAmount(item)
                this.getTax(item)
                this.inputForm.financeInvoiceDetailDTOList.push(item)
              }
            }
          })
        }
        this.$message.success('导入完成')
      },
      // 打开开票信息选择组件   选择电话号
      openBillingChoose () {
        if (this.commonJS.isEmpty(this.inputForm.billingWorkplaceRealId)) {
          this.$message.error('获取不到“实际开票单位”，请重新填写')
          return
        }
        this.$refs.billingChoose.init(this.inputForm.billingWorkplaceRealId)
      },
      // 开票信息选择组件  选择后回调
      getBilling (row) {
        if (this.commonJS.isNotEmpty(row.phone)) {
          this.inputForm.telPhone = row.phone
          this.inputForm.billingId = row.id
        } else {
          this.inputForm.telPhone = ''
          this.inputForm.billingId = ''
        }
      },
      // 格式化 发票金额  保留两位小数
      fixedAccount () {
        if (isNaN(this.inputForm.account) && !/^-$/.test(this.inputForm.account)) {
          this.inputForm.account = ''
        }
        if (!/^[+-]?\d*\.{0,1}\d{0,1}$/.test(this.inputForm.account)) {
          this.inputForm.account = this.inputForm.account.replace(/\.\d{2,}$/, this.inputForm.account.substr(this.inputForm.account.indexOf('.'), 3))
        }
        // 禁止录入整数部分两位以上，但首位为0
        var regStrs = [
          ['^(\\-)?0(\\d+)$', '$1']
        ]
        for (var i = 0; i < regStrs.length; i++) {
          var reg = new RegExp(regStrs[i][0])
          var result = this.inputForm.account.replace(reg, regStrs[i][1])
          this.inputForm.account = result
        }
      }
    }
  }
</script>
<style scoped>
  /deep/ .el-input-number .el-input__inner {
    text-align: left;
  }
</style>
