<template xmlns:v-slot="http://www.w3.org/1999/XSL/Transform">
  <div>
    <el-row>
      <el-col :span="24">
        <el-form size="middle" :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view'?'readonly':''"  :disabled="status === 'audit' || status === 'taskFormDetail'"
                     label-width="135px" @submit.native.prevent>
          <el-divider v-if="commonJS.isNotEmpty(inputForm.contractId) && formReadOnly" content-position="left">
            <el-link  type="primary" :underline="false" icon="el-icon-document" @click="viewContract(inputForm.contractId)"><b>查看合同详情</b></el-link>
          </el-divider>
          <el-divider v-else content-position="left"><i class="el-icon-document"></i> 选择合同</el-divider>
          <el-row  :gutter="15">
            <el-col :span="24">
              <el-form-item label="合同名称" prop="contractName"
                            :rules="[
                 ]">
                <el-input size="medium" :readonly="true" @focus="openContract()" v-model="inputForm.contractName" placeholder="请选择合同">
                  <el-button slot="append" icon="el-icon-search" @click="openContract()"></el-button>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="合同金额(元)" prop="contractAmount"
                            :rules="[
                 ]">
                <el-input :disabled="true" v-model="inputForm.contractAmount" placeholder="请填写合同金额"></el-input>
              </el-form-item>
            </el-col>
<!--            <el-col :span="12">-->
<!--              <el-form-item label="合同份数" prop="contractNum"-->
<!--                            :rules="[-->
<!--                 ]">-->
<!--                <el-input :disabled="true" v-model="inputForm.contractNum" placeholder="请填写合同份数"></el-input>-->
<!--              </el-form-item>-->
<!--            </el-col>-->
            <el-col :span="12">
              <el-form-item label="委托人" prop="clientContactsName"
                            :rules="[
                 ]">
                <el-input :disabled="true" v-model="inputForm.clientContactsName" placeholder="请填写委托人"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="付款主体" prop="payerSubject"
                            :rules="[
                 ]">
                <el-select :disabled="true" v-model="inputForm.payerSubject" placeholder="请选择付款主体" style="width:100%;">
                  <el-option
                    v-for="item in $dictUtils.getDictList('cw_payment_subject')"
                    :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="paymentMethod"
                            :rules="[
                 ]">
                <el-select :disabled="true" v-model="inputForm.paymentMethod" placeholder="请选择付款方式" style="width:100%;">
                  <el-option
                    v-for="item in $dictUtils.getDictList('cw_payment_method')"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </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="projectName"
                                :rules="[
                                {required: true, message:'项目名称不能为空', trigger:'blur'}
                   ]">
                    <el-input v-model="inputForm.projectName" placeholder="请填写项目名称" clearable></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="项目编号" prop="projectNumber"
                                :rules="[
                   ]">
                    <el-input :disabled="true" v-model="inputForm.projectNumber" placeholder="请填写项目编号" clearable></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="项目所属部门" prop="officeId"
                                :rules="[
                                {required: true, message:'项目所属部门不能为空', trigger:'blur'}
                   ]">
                    <SelectTree
                      ref="officeTree"
                      :props="{
                          value: 'id',             // ID字段名
                          label: 'name',         // 显示名称
                          children: 'children'    // 子级字段名
                        }"
                      :url="`/sys/office/treeData?type=2`"
                      :value="inputForm.officeId"
                      :accordion="true"
                      size="large"
                      @getValue="(value) => {inputForm.officeId=value}"/>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="业务类型" prop="businessTypeName"
                                :rules="[
                   ]">
                    <el-input :readonly="true" @focus="openBusinessTypeForm" v-model="inputForm.businessTypeName" placeholder="请填写业务类型" clearable></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="风险等级" prop="riskLevel"
                                :rules="[
                   ]">
                    <el-select v-model="inputForm.riskLevel" placeholder="请选择风险等级" style="width:100%;">
                      <el-option
                        v-for="item in $dictUtils.getDictList('cw_project_risk_level')"
                        :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="projectMoney"
                                :rules="[
                   ]">
                    <el-input-number
                      v-model="inputForm.projectMoney"
                      controls-position="right"
                      style="width:100%"
                      :precision="2"
                      :max="9999999999"
                      :step="0.01"
                      :min="0"
                      placeholder="请填写项目收费金额"
                      :controls="false"
                      clearable>
                    </el-input-number>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="报备类型" prop="reportType"
                                :rules="[
                                 {required: true, message:'报备类型不能为空', trigger:'blur'}
                  ]">
                    <el-select v-model="inputForm.reportType" placeholder="请选择报备类型" clearable style="width: 100%;">
                      <el-option
                        v-for="item in $dictUtils.getDictList('program_cost_audit_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="auditYear"
                                :rules="[
                   ]">
                    <el-date-picker
                      v-model="inputForm.auditYear"
                      type="year"
                      value-format="yyyy"
                      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="planStartDate"-->
<!--                                :rules="[-->
<!--                                {required: true, message:'项目预计开始时间不能为空', trigger:'blur'}-->
<!--                   ]">-->
<!--                    <el-date-picker-->
<!--                      v-model="inputForm.planStartDate"-->
<!--                      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="planEndDate"-->
<!--                                :rules="[-->
<!--                                {required: true, message:'项目预计结束时间不能为空', trigger:'blur'}-->
<!--                   ]">-->
<!--                    <el-date-picker-->
<!--                      v-model="inputForm.planEndDate"-->
<!--                      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="planDate"
                                :rules="[
                                {required: true, message:'项目预计时间不能为空', trigger:'blur'}
                   ]">
                    <el-date-picker
                      style="width: 100%"
                      placement="bottom-start"
                      format="yyyy-MM-dd HH:mm:ss"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      v-model="inputForm.planDate"
                      type="datetimerange"
                      range-separator="至"
                      start-placeholder="开始日期"
                      @change="forUpdate"
                      end-placeholder="结束日期">
                    </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="现场负责人" prop="projectLeaderId"
                                :rules="[
                   ]">
                    <UserSelect size="medium" :readonly="true" :disabled="status === 'audit' || status === 'taskFormDetail'" :limit='1' :modelValue="inputForm.projectLeaderId" @update:modelValue='(value) => {inputForm.projectLeaderId = value}'></UserSelect>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="项目经理1" prop="projectMasterId"
                                :rules="[
                   ]">
                    <UserSelectSignatory size="medium" ref="userSelect1" :disabled="status === 'audit' || status === 'taskFormDetail'" :readonly="true" :limit='1' :value="inputForm.projectMasterId" @getValue='(value) => {changeSignatory1(value)}'></UserSelectSignatory>

                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="项目经理2" prop="realHeader"
                                :rules="[
                   ]">
                    <UserSelectSignatory size="medium" ref="userSelect2" :disabled="status === 'audit' || status === 'taskFormDetail'" :readonly="true" :limit='1' :value="inputForm.realHeader" @getValue='(value) => {changeSignatory2(value)}'></UserSelectSignatory>
                  </el-form-item>
                </el-col>


                <el-col :span="12">
                  <el-form-item label="创建人" prop="createBy.name"
                                :rules="[
                   ]">
                    <el-input :disabled="true" v-model="inputForm.createBy.name" placeholder="请填写创建人" clearable></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="创建时间" prop="createDate"
                                :rules="[
                   ]">
                    <el-input :disabled="true" v-model="inputForm.createDate" placeholder="请填写创建时间" clearable></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
        <el-tabs v-model="activeName" type="border-card" @tab-click="tabHandleClick">
          <el-tab-pane label="被服务单位" name="client">
            <span slot="label"><span style="color: red;border-top: 20px">*</span> 被服务单位</span>
            <el-row :gutter="15">
              <el-button type="primary" style="margin-bottom: 15px" size="mini" :disabled="status === 'audit' || status === 'taskFormDetail'" @click="openWorkClient">
                新增被服务单位
              </el-button>
            </el-row>
            <el-row  :gutter="15">
              <el-form :disabled="status === 'audit' || status === 'taskFormDetail'">
                <vxe-table
                  border
                  show-overflow
                  show-footer
                  :column-config="{resizable: true}"
                  ref="clientTable"
                  :key="tableKeyClient"
                  class="vxe-table-element"
                  :data="inputForm.cwProjectClientInfoDTOList"
                  style=""
                  @cell-click=""
                  @edit-closed=""
                  highlight-current-row
                  :edit-config="{trigger: 'click', mode: 'row', showStatus: false, autoClear: false}"
                >
                  <vxe-table-column align="center" field="name" title="客户名称" :edit-render="{}">
                    <template v-slot:edit="scope">
                      <el-input :readonly="true" v-model="scope.row.name" placeholder="客户名称" clearable></el-input>
                    </template>
                  </vxe-table-column>
                  <vxe-table-column align="center" field="no" title="客户编号" :edit-render="{}">
                    <template v-slot:edit="scope">
                      <el-input :readonly="true" v-model="scope.row.no" placeholder="客户编号" clearable></el-input>
                    </template>
                  </vxe-table-column>
<!--                  <vxe-table-column align="center" field="companyLevel" title="层级" :edit-render="{}">-->
<!--                    <template v-slot:edit="scope">-->
<!--                      <el-input :readonly="true" v-model="scope.row.companyLevel" placeholder="层级" clearable></el-input>-->
<!--                    </template>-->
<!--                  </vxe-table-column>-->
                  <vxe-table-column align="center" title="操作" width="100">
                    <template v-slot="scope">
                      <el-button size="mini" type="danger" @click="removeEvent(scope.row,scope.$rowIndex,'client')">删除</el-button>
                    </template>
                  </vxe-table-column>
                </vxe-table>
              </el-form>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="附件" name="files">
            <!--        附件-->
            <UpLoadComponent ref="uploadComponent"></UpLoadComponent>
          </el-tab-pane>

        </el-tabs>
      </el-col>
    </el-row>
    <WorkContractChooseCom ref="workContractChooseCom" @getContract="getContract"></WorkContractChooseCom>
    <WorkClientChooseForm ref="workClientChooseForm" @getWorkClientChoose="getWorkClientChoose"></WorkClientChooseForm>
    <CwProjectBusinessTypeListForm ref="cwProjectBusinessTypeListForm" @getBusinessType="getBusinessType"></CwProjectBusinessTypeListForm>
    <ContractNameForm ref="contractNameForm"></ContractNameForm>
  </div>
</template>

<script>
  import UpLoadComponent from '@/views/common/UpLoadComponent'
  import SelectUserTree from '@/views/utils/treeUserSelect'
  import SelectTree from '@/components/treeSelect/treeSelect.vue'
  import UserSelect from '@/components/userSelect'
  import ProjectRecordsService from '@/api/cw/projectRecords/ProjectRecordsService'
  import EnterpriseSearchService from '@/api/cw/common/EnterpriseSearchService'
  import WorkClientChooseForm from '../workClientInfo/WorkClientChooseForm'
  import WorkContractChooseCom from './WorkContractChooseCom'
  import CwProjectBusinessTypeListForm from '@/views/cw/projectBusinessType/CwProjectBusinessTypeListForm'
  import ContractNameForm from '../workContract/ContractNameForm'
  import WorkClientService from '@/api/cw/workClientInfo/WorkClientService'
  import ContractInfoService from '@/api/cw/workContract/ContractInfoService'
  import UserSelectSignatory from '../workClientInfo/clientUserSelect'
  export default {
    props: {
      businessId: {
        type: String,
        default: ''
      },
      formReadOnly: {
        type: Boolean,
        default: false
      },
      status: {
        type: String,
        default: ''
      }
    },
    data () {
      return {
        title: '',
        method: '',
        loading: false,
        inputForm: {
          id: '',
          createDate: '',
          createBy: {
            id: '',
            name: ''
          },
          remarks: '',
          projectNumber: '',
          projectName: '',
          officeId: '',
          projectMoney: '',
          auditYear: '',
          planStartDate: '',
          planEndDate: '',
          projectMasterId: '',
          projectLeaderId: '',
          procInsId: '',
          processDefinitionId: '',
          status: '',
          workAttachmentDtoList: [],
          cwProjectClientInfoDTOList: [],
          contractName: '',
          contractAmount: '',
          contractNum: '',
          payerSubject: '',
          paymentMethod: '',
          contractId: '',
          businessType: '',
          riskLevel: '',
          businessTypeName: '',
          planDate: [],
          realHeader: '',
          clientContactsName: '',
          reportType: ''
        },
        keyWatch: '',
        activeName: 'client',
        tableKey: '',
        tableKeyClient: '1'
      }
    },
    projectRecordsService: null,
    enterpriseSearchService: null,
    workClientService: null,
    contractInfoService: null,
    created () {
      this.enterpriseSearchService = new EnterpriseSearchService()
      this.projectRecordsService = new ProjectRecordsService()
      this.workClientService = new WorkClientService()
      this.contractInfoService = new ContractInfoService()
    },
    computed: {
      bus: {
        get () {
          this.$refs.uploadComponent.setDividerName('附件', false)
          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()
            })
          }
        }
      }
    },
    components: {
      SelectUserTree,
      UpLoadComponent,
      SelectTree,
      UserSelect,
      WorkClientChooseForm,
      WorkContractChooseCom,
      CwProjectBusinessTypeListForm,
      ContractNameForm,
      UserSelectSignatory
    },
    methods: {
      getKeyWatch (keyWatch) {
        this.keyWatch = keyWatch
      },
      forUpdate () {
        this.$forceUpdate()
      },
      init (method, id) {
        this.activeName = 'client'
        this.projectRecordsService = new ProjectRecordsService()
        this.method = method
        this.inputForm = {
          id: '',
          createDate: '',
          createBy: {
            id: '',
            name: JSON.parse(localStorage.getItem('user')).name
          },
          remarks: '',
          projectNumber: '',
          projectName: '',
          officeId: '',
          projectMoney: '',
          auditYear: '',
          planStartDate: '',
          planEndDate: '',
          projectMasterId: '',
          projectLeaderId: '',
          procInsId: '',
          processDefinitionId: '',
          status: '',
          workAttachmentDtoList: [],
          cwProjectClientInfoDTOList: [],
          contractName: '',
          contractAmount: '',
          contractNum: '',
          payerSubject: '',
          paymentMethod: '',
          contractId: '',
          businessType: '',
          riskLevel: '',
          businessTypeName: '',
          planDate: [],
          realHeader: '',
          clientContactsName: '',
          reportType: ''
        }
        this.inputForm.id = id
        this.loading = false
        this.$nextTick(() => {
          this.$refs.inputForm.resetFields()
          this.loading = true
          this.projectRecordsService.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.workAttachmentDtoList)) {
              this.inputForm.workAttachmentDtoList = []
            }
            if (this.commonJS.isEmpty(this.inputForm.createDate)) {
              this.inputForm.createDate = this.moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
            }
            if (this.commonJS.isEmpty(this.inputForm.createBy.name)) {
              this.inputForm.createBy.name = JSON.parse(localStorage.getItem('user')).name
            }
            if (this.commonJS.isEmpty(this.inputForm.officeId)) {
              this.inputForm.officeId = JSON.parse(localStorage.getItem('user')).officeDTO.id
            }
            if (this.status === 'audit' || this.status === 'taskFormDetail') {
              this.method = 'view'
            }
            this.$refs.uploadComponent.newUpload(this.method, this.inputForm.workAttachmentDtoList, 'cw_project_records', null, null, null, null, false)
            if (this.commonJS.isEmpty(this.inputForm.cwProjectClientInfoDTOList)) {
              this.inputForm.cwProjectClientInfoDTOList = []
            }
            // if (this.commonJS.isEmpty(this.inputForm.projectMasterId)) {
            //   this.inputForm.projectMasterId = JSON.parse(localStorage.getItem('user')).id
            // }
            if (this.commonJS.isEmpty(this.inputForm.projectLeaderId)) {
              this.inputForm.projectLeaderId = JSON.parse(localStorage.getItem('user')).id
            }
            if (this.commonJS.isEmpty(this.inputForm.projectMoney)) {
              this.inputForm.projectMoney = 0
            }
            this.loading = false
          })
        })
      },
      saveForm (callback) {
        this.doSubmit('save', callback)
      },
      startForm (callback) {
        // if (this.commonJS.isNotEmpty(this.inputForm.planEndDate) && this.commonJS.isNotEmpty(this.inputForm.planStartDate)) {
        //   if (this.moment(this.inputForm.planEndDate).format('YYYY-MM-DD') < this.moment(this.inputForm.planStartDate).format('YYYY-MM-DD') || this.moment(this.inputForm.planEndDate).format('YYYY-MM-DD') === this.moment(this.inputForm.planStartDate).format('YYYY-MM-DD')) {
        //     this.$message.error('项目预计开始时间要小于项目预计结束时间')
        //     this.loading = false
        //     throw new Error('项目预计开始时间要小于项目预计结束时间')
        //   } else {
        //     this.doSubmit('start', callback)
        //   }
        // } else {
        //   this.doSubmit('start', callback)
        // }
        this.doSubmit('start', callback)
      },
      async agreeForm (callback) {
        await this.projectRecordsService.queryById(this.inputForm.id).then(({data}) => {
          if (data.status !== '2') { // 审核状态不是“待审核”，就弹出提示
            this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
            throw new Error()
          } else {
            this.doSubmit('agree', callback)
          }
        })
      },
      reapplyForm (callback) {
        this.projectRecordsService.queryById(this.inputForm.id).then(({data}) => {
          if (data.status !== '4') { // 审核状态不是“驳回”，就弹出提示
            this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
            throw new Error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
          } else {
            this.doSubmit('reapply', callback)
          }
        })
      },
      // 表单提交
      doSubmit (status, callback) {
        if (status === 'save') {
          // 暂存
          this.inputForm.status = '1'
          this.loading = true
          if (this.$refs.uploadComponent.checkProgress()) {
            this.loading = false
            return
          }
          if (this.commonJS.isNotEmpty(this.inputForm.planDate)) {
            this.inputForm.planStartDate = this.inputForm.planDate[0]
            this.inputForm.planEndDate = this.inputForm.planDate[1]
          } else {
            this.inputForm.planStartDate = ''
            this.inputForm.planEndDate = ''
          }
          this.inputForm.workAttachmentDtoList = this.$refs.uploadComponent.getDataList()
          this.inputForm.createDate = this.moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
          this.projectRecordsService.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.agreeDate = this.moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
          this.inputForm.agreeUserId = this.$store.state.user.id
          this.inputForm.status = '5'
        } else if (status === 'reapply') {
          this.inputForm.status = '2'
        }
        this.$refs['inputForm'].validate((valid) => {
          if (valid) {
            this.loading = true
            if (this.commonJS.isEmpty(this.inputForm.projectMasterId) && this.commonJS.isEmpty(this.inputForm.realHeader)) {
              this.loading = false
              this.$message.error('“项目经理1”与“项目经理2”至少填写一项')
              throw new Error('“项目经理1”与“项目经理2”至少填写一项')
            }
            if (this.commonJS.isEmpty(this.inputForm.cwProjectClientInfoDTOList)) {
              this.loading = false
              this.$message.error('“被服务单位”中至少填写一条信息')
              throw new Error('“被服务单位”中至少填写一条信息')
            }
            if (this.$refs.uploadComponent.checkProgress()) {
              this.loading = false
              throw new Error()
            }
            this.inputForm.planStartDate = this.inputForm.planDate[0]
            this.inputForm.planEndDate = this.inputForm.planDate[1]
            this.inputForm.workAttachmentDtoList = this.$refs.uploadComponent.getDataList()
            if (this.commonJS.isEmpty(this.inputForm.createDate)) {
              this.inputForm.createDate = this.moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
            }
            this.projectRecordsService.saveForm(this.inputForm).then(({data}) => {
              callback(data.businessTable, data.businessId, this.inputForm)
              this.loading = false
            }).catch(() => {
              this.loading = false
            })
          }
        })
      },
      async updateStatusById (type, callback) {
        if (await this.$refs.uploadComponent.checkProgress()) {
          this.loading = false
          throw new Error()
        } else {
          if (type === 'reject' || type === 'reback') {
            await this.projectRecordsService.queryById(this.inputForm.id).then(({data}) => {
              if (data.status !== '2') { // status的值不等于“审核中”就弹出提示
                this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
                throw new Error()
              } else {
                if (type === 'reject') {
                  // 驳回
                  this.inputForm.status = '4'
                  let param = {status: '4', id: this.inputForm.id}
                  this.projectRecordsService.updateStatusById(param).then(() => {
                    callback()
                  })
                }
                if (type === 'reback') {
                  // 撤回
                  let param = {status: '3', id: this.inputForm.id}
                  this.projectRecordsService.updateStatusById(param)
                }
              }
            })
          } else if (type === 'hold') {
            this.projectRecordsService.queryById(this.inputForm.id).then(({data}) => {
              if (data.status !== '4') { // status的值不等于“驳回”就弹出提示
                this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
                throw new Error()
              } else {
                // 终止
                let param = {status: '1', id: this.inputForm.id}
                this.projectRecordsService.updateStatusById(param).then(() => {
                  callback()
                })
              }
            })
          }
        }
      },
      close () {
        this.inputForm = {
          id: '',
          createDate: '',
          createBy: {
            id: '',
            name: ''
          },
          remarks: '',
          projectNumber: '',
          projectName: '',
          officeId: '',
          projectMoney: '',
          auditYear: '',
          planStartDate: '',
          planEndDate: '',
          projectMasterId: '',
          projectLeaderId: '',
          procInsId: '',
          processDefinitionId: '',
          status: '',
          workAttachmentDtoList: [],
          cwProjectClientInfoDTOList: [],
          contractName: '',
          contractAmount: '',
          contractNum: '',
          payerSubject: '',
          paymentMethod: '',
          contractId: '',
          businessType: '',
          riskLevel: '',
          businessTypeName: '',
          planDate: [],
          realHeader: '',
          clientContactsName: '',
          reportType: ''
        }
        this.$refs.uploadComponent.clearUpload()
        this.$refs.inputForm.resetFields()
      },
      tabHandleClick (event) {
        // console.log(event)
      },
      // 新增
      // eslint-disable-next-line no-dupe-keys
      insertEvent (type) {
        if (type === 'client') {
          let d = {
            no: '',
            name: '',
            companyLevel: ''
          }
          if (this.commonJS.isEmpty(this.inputForm.cwProjectClientInfoDTOList)) {
            this.inputForm.cwProjectClientInfoDTOList = []
          }
          this.$refs.clientTable.insertAt(d)
          this.inputForm.cwProjectClientInfoDTOList.push(d)
          this.tableKeyClient = Math.random()
        }
      },
      // 删除
      removeEvent (row, rowIndex, type) {
        if (type === 'client') {
          this.$refs.clientTable.remove(row)
          this.inputForm.cwProjectClientInfoDTOList.splice(rowIndex, 1)
        }
      },
      // 打开客户选择组件
      openWorkClient () {
        this.$refs.workClientChooseForm.init()
      },
      getWorkClientChoose (list) {
        if (this.commonJS.isEmpty(this.inputForm.cwProjectClientInfoDTOList)) {
          this.inputForm.cwProjectClientInfoDTOList = []
        }
        let _this = this
        let _list = list
        const waitForEach = function () {
          return new Promise(function (resolve, reject) {
            _list.forEach((item) => {
              _this.inputForm.cwProjectClientInfoDTOList.forEach(client => {
                if (item.no === client.no) {
                  _this.$message.error('已存在客户 “' + client.name + '”，请重新选择')
                  throw new Error('已存在客户 “' + client.name + '”，请重新选择')
                }
              })
            })
            resolve()
          })
        }
        waitForEach().then(() => {
          list.forEach(item => {
            this.$refs.clientTable.insertAt(item)
            this.inputForm.cwProjectClientInfoDTOList.push(item)
            this.tableKeyClient = Math.random()
          })
        })
      },
      getContract (row) {
        console.log('111')
        // 首先删除之前合同与被服务单位的关联（委托方联系人）
        let _this = this
        const waitDelClient = function () {
          return new Promise(async (resolve, reject) => {
            if (_this.commonJS.isNotEmpty(_this.inputForm.contractId)) {
              // 根据合同id查询合同信息
              _this.contractInfoService.findById(_this.inputForm.contractId).then(({data}) => {
                if (_this.commonJS.isNotEmpty(data.customerId)) {
                  // 根据合同的委托人联系人id查询客户信息
                  _this.workClientService.queryById(data.customerId).then((client) => {
                    if (_this.commonJS.isNotEmpty(client.data.no)) {
                      // 将被服务单位中与合同委托人联系人相同删除
                      _this.inputForm.cwProjectClientInfoDTOList.forEach((item, index) => {
                        if (item.no === client.data.no) {
                          _this.$refs.clientTable.remove(item)
                          _this.inputForm.cwProjectClientInfoDTOList.splice(index, 1)
                        }
                      })
                      setTimeout(() => {
                        resolve()
                      }, 400)
                    } else {
                      resolve()
                    }
                  })
                } else {
                  resolve()
                }
              })
            } else {
              resolve()
            }
          })
        }
        waitDelClient().then(() => {
          this.inputForm.contractName = row.contractName
          this.inputForm.contractAmount = row.contractAmount
          this.inputForm.contractNum = row.contractNum
          this.inputForm.payerSubject = row.payerSubject
          this.inputForm.paymentMethod = row.paymentMethod
          this.inputForm.contractId = row.id
          this.inputForm.clientContactsName = row.clientContactsName
          if (this.commonJS.isNotEmpty(row.clientContacts)) {
            if (this.commonJS.isEmpty(this.inputForm.cwProjectClientInfoDTOList)) {
              this.inputForm.cwProjectClientInfoDTOList = []
            }
            this.workClientService.queryById(row.clientContacts).then((data) => {
              if (this.commonJS.isNotEmpty(data.data.id)) {
                let _data = data.data
                const waitForEach = function () {
                  return new Promise(function (resolve, reject) {
                    _this.inputForm.cwProjectClientInfoDTOList.forEach(client => {
                      if (_data.no === client.no) {
                        // _this.$message.error('已存在客户 “' + client.name + '”')
                        throw new Error('已存在客户 “' + client.name + '”')
                      }
                    })
                    resolve()
                  })
                }
                waitForEach().then(() => {
                  this.$refs.clientTable.insertAt(data.data)
                  this.inputForm.cwProjectClientInfoDTOList.push(data.data)
                  this.tableKeyClient = Math.random()
                })
              }
            })
          }
        })
      },
      // 打开合同选择组件
      openContract () {
        this.$refs.workContractChooseCom.init()
      },
      getBusinessType (row) {
        this.inputForm.businessType = row.id
        this.inputForm.businessTypeName = row.name
      },
      // 打开业务类型选择组件
      openBusinessTypeForm () {
        this.$refs.cwProjectBusinessTypeListForm.init()
      },
      // 查看合同详情
      viewContract (id) {
        this.$refs.contractNameForm.init('view', id)
      },
      changeSignatory1 (value) {
        if (this.inputForm.realHeader === value && this.commonJS.isNotEmpty(value)) {
          this.$message.warning('项目经理1和项目经理2不可以相同')
          this.$nextTick(() => {
            this.inputForm.projectMasterId = ''
            this.$refs.userSelect1.changeNameValue('')
            this.$refs.userSelect1.clearSelectData()
            this.$forceUpdate()
          })
        } else {
          this.inputForm.projectMasterId = value
        }
      },
      changeSignatory2 (value) {
        if (this.inputForm.projectMasterId === value && this.commonJS.isNotEmpty(value)) {
          this.$message.warning('项目经理1和项目经理2不可以相同')
          this.$nextTick(() => {
            this.inputForm.realHeader = ''
            this.$refs.userSelect2.changeNameValue('')
            this.$refs.userSelect2.clearSelectData()
            this.$forceUpdate()
          })
        } else {
          this.inputForm.realHeader = value
        }
      }
    }
  }
</script>
<style scoped>
  /deep/ .el-input-number .el-input__inner {
    text-align: left;
  }
</style>
