<template xmlns:v-slot="http://www.w3.org/1999/XSL/Transform">
  <div>
    <el-dialog
      :title="title"
      :close-on-click-modal="false"
	  draggable
      width="1300px"
      @close="close"
      append-to-body
      @keyup.enter.native="doSubmit"
      v-model="visible">
      <el-form :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view'?'readonly':''"
               label-width="160px" @submit.native.prevent>
        <el-row  :gutter="15" v-if="baseFlag !== true">
          <el-col :span="24">
			  <vxe-table
				  border
				  show-overflow
				  show-footer
				  ref="baseTable"
				  class="vxe-table-element"
				  :data="inputForm.financeInvoiceBaseDTOList"
				  style="margin-left: 5em"
				  highlight-current-row
				  :edit-config="{trigger: 'click', mode: 'cell', showStatus: true, autoClear: true}"
			  >
				  <vxe-table-column field="programName" align="center" title="项目名称">
					  <template #default="scope">
						  <el-link type="primary" :underline="false" @click="openProjectForm(scope.row.programId)" >{{scope.row.programName}}</el-link>
					  </template>
				  </vxe-table-column>
				  <vxe-table-column field="contractName" align="center" title="合同名称"></vxe-table-column>
				  <vxe-table-column field="account" align="center" title="开票金额"></vxe-table-column>
				  <vxe-table-column field="reportType" align="center" title="报备类型"></vxe-table-column>
				  <vxe-table-column field="programNo" align="center" title="项目编号"></vxe-table-column>
				  <!--            <vxe-table-column field="clientName" align="center" title="委托方"></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="mini" type="danger" @click="removeEvent(scope.row,scope.$rowIndex,'base')">删除</el-button>-->
				  <!--              </template>-->
				  <!--            </vxe-table-column>-->
			  </vxe-table>
		  </el-col>
        </el-row>
        <el-row :gutter="15" v-if="baseFlag === true">
          <el-form-item label="开票详情" prop="">
          <el-input :readonly="true" type="textarea" maxlength="500" v-model="programName"></el-input>
          </el-form-item>
        </el-row>
      </el-form>
		<template #footer>
			<span slot="footer" class="dialog-footer">
			  <el-button @click="close()" icon="el-icon-circle-close">关闭</el-button>
						<!--      <el-button size="small" type="primary" v-if="method != 'view'||receivablesFlag!==true" @click="doSubmit()" icon="el-icon-circle-check" v-noMoreClick>确定</el-button>-->
						<!--      <el-button size="small" type="primary" v-if="receivablesFlag===true" @click="doSubmit()" icon="el-icon-circle-check" v-noMoreClick>保留</el-button>-->
			</span>
		</template>

    </el-dialog>
    <ProgramPageForm ref="programPageForm" @getProgram="getProgram"></ProgramPageForm>
    <ContractForm  ref="contractForm" @getContract="getContract"></ContractForm>
    <WorkClientForm  ref="workClientForm" @getWorkClient="getWorkClient"></WorkClientForm>
    <ProjectForm ref="projectForm"></ProjectForm>
  </div>
</template>

<script>
  import financeInvoiceService from '@/api/cw/invoice/CwFinanceInvoiceService'
  import workClientService from '@/api/cw/workClientInfo/WorkClientService'
  import ProjectForm from '@/views/cw/projectRecords/ProjectRecordsForm'
  import ProgramPageForm from '@/views/cw/invoice/ProgramPageForm'
  import UpLoadComponent from '@/views/common/UpLoadComponent'
  import ContractForm from '@/views/cw/invoice/ContractForm'
  import WorkClientForm from '@/views/cw/invoice/WorkClientForm'
  export 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: {},
		  reportType:''
        },
        programRow: '',
        bankList: [],
        err: '',
        receivablesFlag: '', // true为收款，false为非收款
        detailFlag: '', // true为修改发票明细
        importVisible: false,
        baseFlag: false,
        programName: ''
      }
    },
    created () {
    },
    components: {
      ProgramPageForm,
      ContractForm,
      WorkClientForm,
      UpLoadComponent,
      ProjectForm
    },
    methods: {
      init (id) {
        this.method = 'view'
        this.title = '查看项目详情信息'
        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: ''
          },
		  reportType:''
        }
        this.baseFlag = false
        this.inputForm.id = id
        this.visible = true
        this.loading = false
        this.$nextTick(() => {
          this.$refs.inputForm.resetFields()
          this.loading = true
          financeInvoiceService.queryById(this.inputForm.id).then((data) => {
            this.inputForm = this.recover(this.inputForm, data)
            this.inputForm = JSON.parse(JSON.stringify(this.inputForm))
            if (!this.commonJS.isEmpty(this.inputForm.billingWorkplaceRealId)) {
              workClientService.queryById(this.inputForm.billingWorkplaceRealId).then((data) => {
                this.bankList = data.workClientBank
              })
            }
            if (this.commonJS.isEmpty(this.inputForm.financeInvoiceReceivablesDTOList) || this.inputForm.financeInvoiceReceivablesDTOList.length === 0) {
              this.inputForm.financeInvoiceReceivablesDTOList = []
            }
            if (this.commonJS.isEmpty(this.inputForm.workAttachmentDtoList)) {
              this.inputForm.workAttachmentDtoList = []
            }
            if (this.commonJS.isNotEmpty(this.inputForm.financeInvoiceBaseDTOList)) {
              if (this.inputForm.financeInvoiceBaseDTOList.length === 1 && this.commonJS.isEmpty(this.inputForm.financeInvoiceBaseDTOList[0].programId)) {
                this.baseFlag = true
                this.programName = this.inputForm.financeInvoiceBaseDTOList[0].programName
              }
            }
            this.loading = false
          })
        })
      },
      openProjectForm (id) {
        this.$refs.projectForm.init('view', id)
      },
      // 表单提交
      async doSubmit () {
        if (this.commonJS.isEmpty(this.inputForm.financeInvoiceBaseDTOList)) {
          this.$message.error('至少新增一条基本信息')
          return
        } else {
          if (this.inputForm.financeInvoiceBaseDTOList.length === 0) {
            this.$message.error('至少新增一条基本信息')
            return
          }
        }
        let acc = 0
        this.inputForm.financeInvoiceDetailDTOList.forEach((item, index) => {
          if (this.commonJS.isEmpty(item.number)) {
            this.$message.warning('发票明细中第 ' + (index + 1) + ' 条数据的 “发票号” 为空')
            throw new Error()
          }
          if (this.commonJS.isEmpty(item.account)) {
            this.$message.warning('发票明细中第 ' + (index + 1) + ' 条数据的 “开票金额” 为空')
            throw new Error()
          }
          acc = (acc + parseFloat(parseFloat(item.account).toFixed(2)))
        })
        if (acc !== this.inputForm.account) {
          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.$message.warning('发票明细中第 ' + (index + 1) + ' 条数据的 “发票号” 存在重复')
                throw new Error()
              }
            }
          })
        })
        for await (let [index, item] of this.inputForm.financeInvoiceDetailDTOList.entries()) {
          if (this.commonJS.isEmpty(item.number)) {
            this.$message.warning('发票明细中第 ' + (index + 1) + ' 条数据的 “发票号” 为空')
            this.err = true
          }
          await financeInvoiceService.queryByNumber(item.number, item.id).then((data) => {
            if (data === true) {
              this.$message.warning('发票明细中第 ' + (index + 1) + ' 条数据的 “发票号” 存在重复')
              this.err = data
            }
          })
        }
        if (this.err === true) {
          this.err = ''
          return
        }
        if (this.receivablesFlag === true) {
          this.inputForm.financeInvoiceReceivablesDTOList.forEach((item, index) => {
            if (this.commonJS.isEmpty(item.remittanceUnit)) {
              this.$message.warning('收款明细中第 ' + (index + 1) + ' 条数据的 “汇款单位” 为空，请重新输入')
              throw new Error()
            }
            if (this.commonJS.isEmpty(item.remittanceAmount) || item.remittanceAmount === 0 || item.remittanceAmount === '0') {
              this.$message.warning('收款明细中第 ' + (index + 1) + ' 条数据的 “汇款金额” 为空，请重新输入')
              throw new Error()
            }
            if (this.commonJS.isEmpty(item.remittanceDate)) {
              this.$message.warning('收款明细中第 ' + (index + 1) + ' 条数据的 “汇款时间” 为空，请重新输入')
              throw new Error()
            }
          })
        }
        this.$refs['inputForm'].validate((valid) => {
          if (valid) {
            this.loading = true
            if (this.$refs.uploadComponent.checkProgress()) {
              this.loading = false
              return
            }
            this.inputForm.workAttachmentDtoList = this.$refs.uploadComponent.getDataList()
            financeInvoiceService.save(this.inputForm).then((data) => {
              this.close()
              this.$message.success(data)
              this.$emit('refreshDataList')
              this.loading = false
            }).catch(() => {
              this.loading = false
            })
          }
        })
      },
      close () {
        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: {},
			reportType:''
        }
        this.bankList = []
        this.detailFlag = false
        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()
              }
            }
          })
          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
        }
      },
      // 下载模板
      downloadTpl () {
        this.loading = true
        financeInvoiceService.exportTemplate().then((res) => {
          // 将二进制流文件写入excel表，以下为重要步骤
          this.$utils.downloadExcel(res, '发票明细导入模板')
          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
        financeInvoiceService.importDetail(formBody).then(async (result) => {
          if (this.commonJS.isEmpty(result)) {
            this.importVisible = false
            this.loading = false
            throw new Error()
          }
          for await (let item of result) {
            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)
          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) {
        console.log('110', this.inputForm.taxpayerIdentificationNo)
        await this.checkIdentificationNo()
        const formBody = new FormData()
        formBody.append('file', file.raw)
        this.loading = true
        financeInvoiceService.importDetail(formBody).then(async result => {
          if (this.commonJS.isEmpty(result)) {
            this.importVisible = false
            this.loading = false
            throw new Error()
          }
          for await (let item of result) {
            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)
          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('导入完成')
      }
    }
  }
</script>
<style scoped>
  /deep/ .el-input-number .el-input__inner {
    text-align: left;
  }
</style>
