<template xmlns:v-slot="http://www.w3.org/1999/XSL/Transform">
  <div>
    <el-form size="large" :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view'?'readonly':''"  :disabled="true"
             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="true" size="default" @click="insertEvent('base')"  plain>
          新增
        </el-button>
      </el-divider>
      <el-row  :gutter="15">
		  <el-col :span="24">
			  <vxe-table
				  border
				  show-overflow
				  show-footer
				  ref="baseTable"
				  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}"
			  >
				  <vxe-table-column field="programName" 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" 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" 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="操作" width="100">
					  <template v-slot="scope">
						  <el-button size="default" type="danger" @click="removeEvent(scope.row,scope.$rowIndex,'base')">删除</el-button>
					  </template>
				  </vxe-table-column>
			  </vxe-table>
		  </el-col>

      </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="large" 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="large" 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="large"
              :props="{
                value: 'id',             // ID字段名
                label: 'name',         // 显示名称
                children: 'children'    // 子级字段名
              }"
              :url="`/system-server/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>
        <template 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" placeholder="请填写电话" clearable></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%;">
                <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>
        </template>
        <template 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" placeholder="请填写电话" clearable></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%;">
                <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>
        </template>

        <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%;">
              <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%;">
              <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-number
              v-model="inputForm.account"
              controls-position="right"
              :controls="false"
              style="width:100%;"
              :max="999999999999999"
              :precision="2"
              placeholder="请填写发票金额"
              :step="0.01"
              :min="0"
              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="large" 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-col :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-col :span="12">
          <el-form-item label="实际开票人" prop="billingPeopleReal"
                        :rules="[
               ]">
            <SelectUserTree
              ref="companyTree"
              size="large"
              :props="{
                value: 'id',             // ID字段名
                label: 'name',         // 显示名称
                children: 'children'    // 子级字段名
              }"
              :url="`/system-server/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="[
               ]">
            <SelectUserTree
              ref="companyTree"
              size="large"
              :props="{
                value: 'id',             // ID字段名
                label: 'name',         // 显示名称
                children: 'children'    // 子级字段名
              }"
              :url="`/system-server/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="[
               ]">
            <SelectTree
              ref="areaTree"
              :props="{
                    value: 'id',             // ID字段名
                    label: 'name',         // 显示名称
                    children: 'children'    // 子级字段名
                  }"
              url="/system-server/sys/area/treeData"
              :value="inputForm.reconciliationArea"
              :clearable="true"
			  size="large"
              :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-divider content-position="left"><i class="el-icon-document"></i>
        发票明细
        <el-button style="margin-left: 20px" type="primary" :disabled="true" size="default" @click="insertEvent('detail')" plain>
          新增
        </el-button>
      </el-divider>
      <el-form size="large" :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view'?'readonly':''"  :disabled="true"
               label-width="160px" @submit.native.prevent>
      <el-row  :gutter="15">
		  <el-col :span="24">
			  <vxe-table
				  border
				  show-overflow
				  show-footer
				  ref="detailTable"
				  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"
							  clearable>
						  </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="default" type="danger" @click="removeEvent(scope.row,scope.$rowIndex,'detail')">删除</el-button>
					  </template>
				  </vxe-table-column>
			  </vxe-table>
		  </el-col>

      </el-row>
      </el-form>
      <el-divider content-position="left"><i class="el-icon-document"></i>
        收款明细
        <el-button style="margin-left: 20px" :disabled="true" type="primary" size="default" @click="insertEvent('receivables')" plain>
          新增
        </el-button>
      </el-divider>
      <el-row  :gutter="15">
		  <el-col :span="24">
			  <vxe-table
				  border
				  show-overflow
				  show-footer
				  ref="receivablesTable"
				  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="default" type="danger" @click="removeEvent(scope.row,scope.$rowIndex,'receivables')">删除</el-button>
					  </template>
				  </vxe-table-column>
			  </vxe-table>
		  </el-col>

      </el-row>
      <el-divider content-position="left"><i class="el-icon-document"></i>发票作废</el-divider>
      <el-form size="large" :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view'?'readonly':''"  :disabled="status === 'audit' || status === 'taskFormDetail'"
               label-width="160px" @submit.native.prevent>
      <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>
      </el-form>
    </el-form>
    <!--        附件-->
    <UpLoadComponent ref="uploadComponent"></UpLoadComponent>
    <ProgramPageForm ref="programPageForm" @getProgram="getProgram"></ProgramPageForm>
    <ContractForm  ref="contractForm" @getContract="getContract"></ContractForm>
    <WorkClientForm  ref="workClientForm" @getWorkClient="getWorkClient"></WorkClientForm>
  </div>
</template>

<script>
  import FinanceInvoiceService from '@/api/finance/invoice/FinanceInvoiceService'
  import WorkClientService from '@/api/sys/WorkClientService'
  import ProgramPageForm from '@/views/finance/invoice/ProgramPageForm'
  import UpLoadComponent from '@/views/common/UpLoadComponent'
  import ContractForm from '@/views/program/registered/ContractForm'
  import WorkClientForm from '@/views/program/registered/WorkClientForm'
  import SelectUserTree from '@/views/utils/treeUserSelect'
  import SelectTree from '@/components/treeSelect/treeSelect.vue'
  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: this.$store.state.user.name,
          billingPeopleId: this.$store.state.user.id,
          billingDate: '',
          collectDate: '',
          billingPeopleReal: this.$store.state.user.id,
          reconciliationPeople: '',
          reconciliationArea: '',
          remarks: '',
          name: '',
          status: '',
          procInsId: '',
          processDefinitionId: '',
          workAttachmentDtoList: [],
          financeInvoiceDetailDTOList: [],
          financeInvoiceReceivablesDTOList: [],
          financeInvoiceInvalidDTO: {},
          invalidStatus: '',
          isMultiple: ''
        },
        programRow: '',
        bankList: [],
        err: '',
        keyWatch: '',
        yesNoFlag: [{label: '否', value: '0'}, {label: '是', value: '1'}]
      }
    },
    financeInvoiceService: null,
    workClientService: null,
    created () {
      this.financeInvoiceService = new FinanceInvoiceService()
      this.workClientService = new WorkClientService()
    },
    mounted () {
    },
    components: {
      ProgramPageForm,
      ContractForm,
      WorkClientForm,
      SelectUserTree,
      SelectTree,
      UpLoadComponent
    },
    computed: {
      bus: {
        get () {
          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.method = method
        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: this.$store.state.user.name,
          billingPeopleId: this.$store.state.user.id,
          billingDate: '',
          collectDate: '',
          billingPeopleReal: this.$store.state.user.id,
          reconciliationPeople: '',
          reconciliationArea: '',
          remarks: '',
          name: '',
          status: '',
          procInsId: '',
          processDefinitionId: '',
          workAttachmentDtoList: [],
          financeInvoiceDetailDTOList: [],
          financeInvoiceReceivablesDTOList: [],
          financeInvoiceInvalidDTO: {
            id: '',
            invalidStatus: '',
            invoiceId: '',
            remarks: ''
          },
          invalidStatus: '',
          isMultiple: ''
        }
        // 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(async () => {
          this.$refs.inputForm.resetFields()
          this.loading = true
          await this.financeInvoiceService.queryIdByInvalidId(id).then((data) => {
            this.inputForm.id = data.businessId
          })
          this.financeInvoiceService.queryById(this.inputForm.id).then(async (data) => {
            await 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.workClientService.findById(this.inputForm.billingWorkplaceRealId).then((data) => {
                this.bankList = data.workClientBank
              })
            }
            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.formReadOnly === true) {
            method = 'view'
            // }
            if (!this.commonJS.isEmpty(this.status) && this.status === 'audit' && this.inputForm.financeInvoiceDetailDTOList.length === 0) {
              this.inputForm.financeInvoiceDetailDTOList.push({
                code: '',
                number: '',
                account: this.inputForm.account,
                rate: '',
                amount: '',
                tax: '',
                allAmount: ''
              })
            }
            this.$refs.uploadComponent.newUpload('view', 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 (this.commonJS.isNotEmpty(data.status) && data.status !== '5' && data.status !== '7') { // 审核状态不是“发票申请审核完成”或“作废撤回”，就弹出提示
              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 !== '6') { // 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 !== '8') { // 审核状态不是“驳回”，就弹出提示
            this.loading = false
            this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
            throw new Error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
          } else {
            this.doSubmit('reapply', callback)
          }
        })
      },
      // 表单提交
      async doSubmit (status, callback) {
        this.loading = true
        if (await this.$refs.uploadComponent.checkProgress()) {
          this.loading = false
          throw new Error()
        }
        if (status === 'save') {
          // 暂存
          // this.inputForm.status = '1'
          this.loading = true
          this.inputForm.workAttachmentDtoList = this.$refs.uploadComponent.getDataList()
          this.financeInvoiceService.saveFormInvalid(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 = '6'
        } else if (status === 'agree') {
          // 审核同意 已作废
          this.inputForm.status = '9'
          this.inputForm.financeInvoiceInvalidDTO.invalidStatus = '1'
          this.inputForm.invalidStatus = '1'
        } else if (status === 'reapply') {
          this.inputForm.status = '6'
        }
        // if (this.commonJS.isEmpty(this.inputForm.financeInvoiceBaseDTOList)) {
        //   this.loading = false
        //   this.$message.error('至少新增一条基本信息')
        //   return
        // } else {
        //   if (this.inputForm.financeInvoiceBaseDTOList.length === 0) {
        //     this.loading = false
        //     this.$message.error('至少新增一条基本信息')
        //     return
        //   }
        // }
        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 (acc !== this.inputForm.account) {
            this.loading = false
            this.$message.warning('发票明细中 “开票金额”总和 与发票详情中 “发票金额” 不等')
            return
          }
          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 = ''
            return
          }
        }
        if (status === 'start') {
          if (this.commonJS.isEmpty(this.inputForm.financeInvoiceInvalidDTO.remarks)) {
            this.loading = false
            this.$message.warning('作废原因未填写')
            throw new Error('作废原因未填写')
          }
        }
        this.$refs['inputForm'].validate((valid) => {
          if (valid) {
            this.loading = true
            this.inputForm.workAttachmentDtoList = this.$refs.uploadComponent.getDataList()
            this.financeInvoiceService.saveFormInvalid(this.inputForm).then((data) => {
              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: {},
          invalidStatus: '',
          isMultiple: ''
        }
        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.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.name
            r.contractName = item.contractName
            r.programNo = item.no
            r.clientName = item.clientName
            r.client = item.client
            r.programId = item.id
            r.location = item.location // 项目所在地
            this.inputForm.financeInvoiceBaseDTOList[this.programRow] = r
          } else {
            let r = {
              programName: item.name,
              contractName: item.contractName,
              programNo: item.no,
              clientName: item.clientName,
              client: item.client,
              programId: item.id,
              location: item.location // 项目所在地
            }
            this.inputForm.financeInvoiceBaseDTOList.push(r)
          }
        })
        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.name // 合同名称
        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.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.inputForm.billingWorkplaceReal = row.name // 实际开票单位姓名
        this.inputForm.billingWorkplaceRealId = row.id // 实际开票单位id ‘客户id’
        this.inputForm.taxpayerIdentificationNo = row.uscCode // 纳税人识别号 ‘统一社会信用代码’
        this.inputForm.address = row.registerAddress // 地址 ‘注册地址’
        this.inputForm.telPhone = row.telephone // 电话
        this.bankList = row.backs
        this.inputForm.bankAccount = ''
        this.inputForm.openBank = ''
        this.$forceUpdate()
      },
      changeBank (value) {
        this.bankList.forEach(item => {
          if (item.id === value) {
            this.inputForm.bankAccount = item.bankNumber
          }
        })
      },
      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) < 0 || parseFloat(row.rate) > 100) {
            this.$message.warning('“税率” 请填写 0 到 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 !== '6') { // status的值不等于“审核中”，就弹出提示
                this.loading = false
                this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
                throw new Error()
              } else {
                if (type === 'agree') {
                  // 同意
                  this.inputForm.status = '9'
                }
                if (type === 'reject') {
                  // 驳回
                  this.inputForm.status = '8'
                  // this.inputForm.status = '5'
                }
                if (type === 'reback') {
                  // 撤回
                  // this.inputForm.status = '7'
                  this.inputForm.status = '5'
                }
                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 !== '8') { // status的值不等于“驳回”就弹出提示
                this.loading = false
                this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
                throw new Error()
              } else {
                // 终止
                let param = {status: '5', id: this.inputForm.id}
                this.financeInvoiceService.updateStatusById(param).then(() => {
                  this.loading = false
                  callback()
                })
              }
            })
          }
        }
      }
    }
  }
</script>
<style scoped>
  /deep/ .el-input-number .el-input__inner {
    text-align: left;
  }
</style>
