<template xmlns:v-slot="http://www.w3.org/1999/XSL/Transform">
  <div>
    <el-dialog :title="title" :close-on-click-modal="false" draggable width="1400px" height="500px" @close="close"
      append-to-body v-model="visible">
      <el-row>
        <el-col :span="24">
          <el-form :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 :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="`/system-server/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="[
                                {required: true, message:'业务类型不能为空', trigger:'blur'}]">
                    <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="[{ required: true, message: '项目规模不能为空', trigger: 'blur' }
                ]">
                  <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 prop="isHaveReport" :rules="[
                  { required: true, message: '有无报告不能为空', trigger: 'blur' }
                ]">
                  <template #label>
                    <el-tooltip placement="top">
                      <!-- 使用插槽自定义内容 -->
                      <template #content>
                        <div>
                          注：<br>
                          选择“有报告”则开票时仅可通过报告进行开票。<br>
                          选择“无报告”则开票时仅可通过项目进行开票，且该项目无法创建报告信息
                        </div>
                      </template>
                      <span style="color: #F56C6C">有无报告</span>
                    </el-tooltip>
                  </template>

                  <el-radio @change="preInvoice()" :disabled="isReport" v-model="inputForm.isHaveReport"
                    v-for="item in $dictUtils.getDictList('is_have_report')" :label="item.value"
                    style="margin-right: 20px">
                    {{ item.label }}
                  </el-radio>
                </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%;"
                    @change="reportTypeChange">
                    <el-option v-for="item in $dictUtils.getDictList('cw_work_client_report_type')" :key="item.value"
                      :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="this.reportTypeFlag">
                <el-form-item label="项目分类" prop="projectClassification" :rules="[
                  { required: true, message: '项目分类不能为空', trigger: 'blur' }
                ]">
                  <el-select @change="preInvoice()" v-model="inputForm.projectClassification" placeholder="请选择项目分类类型"
                    clearable style="width: 100%;">
                    <el-option v-for="item in $dictUtils.getDictList('project_classification')" :key="item.value"
                      :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12"
                v-if="hasPermission('project:info:preInvoice') && inputForm.isHaveReport === '1' && (inputForm.projectClassification === '16' || inputForm.projectClassification === '17') && inputForm.reportType === '10'">
                <el-form-item label="是否预开票" prop="isPreInvoice" :rules="[

                ]">
                  <el-radio :disabled="ifCheck" v-model="inputForm.isPreInvoice"
                    v-for="item in $dictUtils.getDictList('is_pre_invoice')" :label="item.value"
                    style="margin-right: 20px">
                    {{ item.label }}</el-radio>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="审计期间" prop="auditYear" :rules="[
                  { required: true, message: '项目规模不能为空', trigger: 'blur' }
                ]">
                  <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="planDate" :rules="[
                  { required: true, message: '项目预计时间不能为空', trigger: 'blur' }
                ]">
                  <el-date-picker style="width: 100%" placement="bottom-start" format="YYYY-MM-DD h:m:s"
                    value-format="YYYY-MM-DD h:m:s" 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 :readonly="true" :disabled="status === 'audit' || status === 'taskFormDetail'" :limit='1'
                    :modelValue="inputForm.projectLeaderId"
                    @update:modelValue='(value) => { inputForm.projectLeaderId = value }'>
                  </UserSelect>
                  <!--<el-input @click="openUserDia1" v-model="inputForm.projectLeaderName" placeholder="请选择现场负责人">
						  <template #suffix>
							  <el-button style="background-color: white;color: #1b1e25;border-color: white;" type="primary" slot="append" icon="el-icon-search" @click="openUserDia1">
							  </el-button>
						  </template>
					  </el-input>-->
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="项目经理1" prop="projectMasterName" :rules="[
                ]">
                  <!--                    <UserSelectSignatory style="width: 100%" ref="userSelect1" :disabled="status === 'audit' || status === 'taskFormDetail'"-->
                  <!--										 :readonly="true" :limit='1' :modelValue="inputForm.projectMasterId"-->
                  <!--										 @update:modelValue='(value) => {changeSignatory1(value)}'></UserSelectSignatory>-->
                  <el-input @blur="changeSignatory1(inputForm.projectMasterName)" @click="openUserDia2"
                    v-model="inputForm.projectMasterName" placeholder="请选择项目经理1" @clear="clearUser2" clearable>
                    <template #suffix>
                      <el-button style="background-color: white;color: #1b1e25;border-color: white;" type="primary"
                        slot="append" icon="el-icon-search" @click.stop="openUserDia2">
                      </el-button>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="项目经理2" prop="realHeaderName" :rules="[
                ]">
                  <!--                    <UserSelectSignatory style="width: 100%" ref="userSelect2" :disabled="status === 'audit' || status === 'taskFormDetail'"-->
                  <!--										 :readonly="true" :limit='1' :modelValue="inputForm.realHeader"-->
                  <!--										 @update:modelValue='(value) => {changeSignatory2(value)}'></UserSelectSignatory>-->
                  <el-input @blur="changeSignatory2(inputForm.realHeader)" @click="openUserDia3"
                    v-model="inputForm.realHeaderName" placeholder="请选择项目经理2" @clear="clearUser3" clearable>
                    <template #suffix>
                      <el-button style="background-color: white;color: #1b1e25;border-color: white;" type="primary"
                        slot="append" icon="el-icon-search" @click.stop="openUserDia3">
                      </el-button>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>


				<!-- 审核阶段：渲染可编辑版本 -->
				<el-col :span="12">
					<el-form-item
						label="项目执行人"
						prop="projectExecutorName"
						:rules="[{ required: true, message: '请选择项目执行人', trigger: 'blur' }]"
					>
						<el-input @click="openProjectExecutorDia1"
								  v-model="inputForm.projectExecutorName" placeholder="请选择项目执行人" @clear="clearUser2" clearable>
							<template #suffix>
								<el-button style="background-color: white;color: #1b1e25;border-color: white;" type="primary"
										   slot="append" icon="el-icon-search" @click.stop="openProjectExecutorDia1">
								</el-button>
							</template>
						</el-input>
					</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-tabs v-model="activeName" type="border-card" @tab-click="tabHandleClick">
              <el-tab-pane name="client">
                <template v-slot:label>
                  <span><span style="color: red;border-top: 20px">*</span> 被服务单位</span>
                </template>
                <el-row :gutter="15">
                  <el-button type="primary" style="margin-bottom: 15px"
                    :disabled="status === 'audit' || status === 'taskFormDetail'" @click="openWorkClient">
                    新增被服务单位
                  </el-button>
                </el-row>
                <el-row :gutter="15">
                  <el-form :disabled="status === 'audit' || status === 'taskFormDetail'" style="width: 100%;">
                    <vxe-table border show-overflow show-footer :column-config="{ resizable: true }" ref="clientTable"
                      :key="tableKeyClient" class="vxe-table-element" :data="inputForm.cwProjectClientInfoDTOList"
                      style="" highlight-current-row>
                      <vxe-table-column align="center" field="name" title="客户名称" :edit-render="{}"></vxe-table-column>
                      <vxe-table-column align="center" field="no" title="客户编号" :edit-render="{}"></vxe-table-column>
                      <vxe-table-column align="center" title="操作" width="100">
                        <template v-slot="scope">
                          <el-button 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 name="contact">
                <template v-slot:label>
                  <span><span style="color: red;border-top: 20px">*</span> 客户联系人</span>
                </template>
                <el-row :gutter="15">
                  <el-button type="primary" style="margin-bottom: 15px"
                    :disabled="status === 'audit' || status === 'taskFormDetail'" @click="insertEvent('contact')">
                    新增客户联系人
                  </el-button>
                  <el-button style="margin-left: 20px" type="primary"
                    :disabled="status === 'audit' || status === 'taskFormDetail'"
                    @click="openProjectClientContactPageForm()" plain>
                    选择联系人
                  </el-button>
                </el-row>
                <el-row :gutter="15">
                  <el-form :disabled="status === 'audit' || status === 'taskFormDetail'" style="width: 100%;">
                    <vxe-table border show-overflow show-footer :column-config="{ resizable: true }" ref="contactTable"
                      :key="tableKeyContact" class="vxe-table-element" :data="inputForm.cwProjectClientContactDTOList"
                      keep-source style="" highlight-current-row :edit-rules="validContactRules"
                      :edit-config="{ trigger: 'click', mode: 'row', showStatus: false, autoClear: true, icon: '-' }">
                      <vxe-table-column align="center" field="name" title="姓名" :edit-render="{}">
                        <template v-slot:edit="scope">
                          <el-input v-model="scope.row.name" placeholder="姓名" clearable></el-input>
                        </template>
                      </vxe-table-column>
                      <vxe-table-column align="center" field="sex" title="性别"
                        :edit-render="{ name: '$select', options: $dictUtils.getDictList('sex') }">
                        <template v-slot:edit="scope">
                          <vxe-select :disabled="status === 'audit' || status === 'taskFormDetail'"
                            v-model="scope.row.sex" placeholder="性别" clearable style="width: 100%;" transfer>
                            <vxe-option v-for="item in $dictUtils.getDictList('sex')" :key="item.value"
                              :label="item.label" :value="item.value">
                            </vxe-option>
                          </vxe-select>
                        </template>
                      </vxe-table-column>
                      <vxe-table-column align="center" field="officeId" title="部门" :edit-render="{}">
                        <template v-slot:edit="scope">
                          <el-input v-model="scope.row.officeId" placeholder="部门" clearable></el-input>
                        </template>
                      </vxe-table-column>
                      <vxe-table-column align="center" field="position" title="职务" :edit-render="{}">
                        <template v-slot:edit="scope">
                          <el-input v-model="scope.row.position" placeholder="职务" clearable></el-input>
                        </template>
                      </vxe-table-column>
                      <vxe-table-column align="center" field="contactFirst" title="联系方式1" :edit-render="{}">
                        <template v-slot:edit="scope">
                          <el-input v-model="scope.row.contactFirst" oninput="value=value.replace(/[^\d]/g,'')"
                            placeholder="联系方式1" clearable></el-input>
                        </template>
                      </vxe-table-column>
                      <vxe-table-column align="center" field="contactSecond" title="联系方式2" :edit-render="{}">
                        <template v-slot:edit="scope">
                          <el-input v-model="scope.row.contactSecond" oninput="value=value.replace(/[^\d]/g,'')"
                            placeholder="联系方式2" clearable></el-input>
                        </template>
                      </vxe-table-column>
                      <vxe-table-column align="center" field="fax" title="传真" :edit-render="{}">
                        <template v-slot:edit="scope">
                          <el-input v-model="scope.row.fax" placeholder="传真" clearable></el-input>
                        </template>
                      </vxe-table-column>
                      <vxe-table-column align="center" field="email" title="邮箱" :edit-render="{}">
                        <template v-slot:edit="scope">
                          <el-input v-model="scope.row.email" @change="$forceUpdate()"
                            @blur="blurEmail(scope.$rowIndex)" placeholder="邮箱" clearable></el-input>
                        </template>
                      </vxe-table-column>
                      <vxe-table-column align="center" field="remarks" title="备注" :edit-render="{}">
                        <template v-slot:edit="scope">
                          <el-input maxlength="500" v-model="scope.row.remarks" placeholder="备注" clearable></el-input>
                        </template>
                      </vxe-table-column>
                      <vxe-table-column align="center" title="操作" width="100">
                        <template v-slot="scope">
                          <el-button type="danger"
                            @click="removeEvent(scope.row, scope.$rowIndex, 'contact')">删除</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-form>
        </el-col>
      </el-row>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="close()" icon="el-icon-circle-close">关闭</el-button>
          <el-button v-if="method === 'edit' || method === 'add'" type="primary" icon="el-icon-circle-check"
            @click="save()">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <WorkContractChooseCom ref="workContractChooseCom" @getContract="getContract"></WorkContractChooseCom>
    <WorkClientChooseForm ref="workClientChooseForm" @getWorkClientChoose="getWorkClientChoose"></WorkClientChooseForm>
    <CwProjectBusinessTypeListForm ref="cwProjectBusinessTypeListForm" @getBusinessType="getBusinessType">
    </CwProjectBusinessTypeListForm>
    <ContractNameForm ref="contractNameForm"></ContractNameForm>
    <CwClientPageForm ref="cwClientPageForm" @getProgram="getProgram"></CwClientPageForm>
    <user-select1 ref="userSelect1" @doSubmit="selectUser1"></user-select1>
	<user-select1 ref="selectProjectExecutorUser" @doSubmit="selectProjectExecutorUser"></user-select1>
    <user-select2 ref="userSelect2" @doSubmit="selectUser2"></user-select2>
    <user-select3 ref="userSelect3" @doSubmit="selectUser3"></user-select3>
  </div>




</template>

<script>
import CwClientPageForm from './CwClientPageForm'
import UpLoadComponent from '@/views/common/UpLoadComponent'
import SelectTree from '@/components/treeSelect/treeSelect.vue'
import UserSelect from '@/components/userSelect'
import projectRecordsService from '@/api/cw/projectRecords/ProjectRecordsService'
import WorkClientChooseForm from '../workClientInfo/WorkClientChooseForm'
import WorkContractChooseCom from './WorkContractChooseCom'
import CwProjectBusinessTypeListForm from '@/views/cw/projectBusinessType/CwProjectBusinessTypeListForm1'
import ContractNameForm from '../workContract/ContractNameForm'
import workClientService from '@/api/cw/workClientInfo/WorkClientService'
import contractInfoService from '@/api/cw/workContract/ContractInfoService'
import UserSelectSignatory from '../workClientInfo/clientUserSelect'
import CwProjectBusinessTypeService from '@/api/cw/projectBusinessType/CwProjectBusinessTypeService'
import projectReportService from "@/api/cw/reportManagement/ProjectReportService";
import cwFinanceInvoiceService from "@/api/cw/invoice/CwFinanceInvoiceService";
import UserSelect1 from '@/views/utils/UserTreeSelect'
import UserSelect2 from '@/views/utils/UserTreeSelectBySignatureScribe'
import UserSelect3 from '@/views/utils/UserTreeSelectBySignatureScribe'
import SelectProjectExecutorUser from "@/views/utils/UserTreeSelect.vue";
export default {
  props: {
    businessId: {
      type: String,
      default: ''
    },
    formReadOnly: {
      type: Boolean,
      default: false
    },
    status: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      showChildDialog: false,
      typeVisible: false,
      title: '',
      method: '',
      loading: false,
      inputForm: {
        id: '',
        createDate: '',
        createBy: {
          id: '',
          name: ''
        },
        remarks: '',
        projectNumber: '',
        projectName: '',
        officeId: '',
        projectMoney: '',
        auditYear: '',
        planStartDate: '',
        planEndDate: '',
        projectMasterId: '',
        projectMasterName: '',
        projectLeaderId: '',
        projectLeaderName: '',
		projectExecutor: '',
		projectExecutorName: '',
        procInsId: '',
        processDefinitionId: '',
        status: '',
        workAttachmentDtoList: [],
        cwProjectClientInfoDTOList: [],
        contractName: '',
        contractAmount: '',
        contractNum: '',
        payerSubject: '',
        paymentMethod: '',
        contractId: '',
        businessType: '',
        riskLevel: '',
        businessTypeName: '',
        planDate: [],
        realHeader: '',
        realHeaderName: '',
        clientContactsName: '',
        reportType: '',
        projectClassification: '',
        programRow: '',
        cwProjectClientContactDTOList: [],
        isHaveReport: '1',
        isPreInvoice: '0'
      },
      keyWatch: '',
      activeName: 'client',
      tableKey: '',
      tableKeyClient: '1',
      tableKeyContact: '2',
      visible: false,
      reportTypeFlag: false,
      validContactRules: {
        name: [
          { required: true, message: '姓名不可以为空' }
        ],
        sex: [
          { required: true, message: '性别不可以为空' }
        ],
        officeId: [
          { required: true, message: '部门不可以为空' }
        ],
        position: [
          { required: true, message: '职务不可以为空' }
        ],
        contactFirst: [
          { required: true, message: '联系方式1不可以为空' }
        ]
      },
      typeDataList: [],
      typeSearchForm: {
        name: ''
      },
      tablePage: {
        total: 0,
        currentPage: 1,
        pageSize: 10,
        orders: []
      },
      isReport: false,
      ifCheck: true
    }
  },
  cwProjectBusinessTypeService: null,
  created() {
    this.cwProjectBusinessTypeService = new CwProjectBusinessTypeService()
  },
  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: {
    CwClientPageForm,
    UpLoadComponent,
    SelectTree,
    UserSelect,
    WorkClientChooseForm,
    WorkContractChooseCom,
    CwProjectBusinessTypeListForm,
    ContractNameForm,
    UserSelectSignatory,
    CwProjectBusinessTypeService,
    UserSelect1,
    UserSelect2,
    UserSelect3,
    SelectProjectExecutorUser,
  },
  methods: {
    getKeyWatch(keyWatch) {
      this.keyWatch = keyWatch
    },
    forUpdate() {
      this.$forceUpdate()
    },
    init(method, id) {
      if (method === 'add') {
        this.title = '新建项目'
      } else {
        this.title = '修改项目'
      }
      this.visible = true
      this.activeName = 'client'
      this.method = method
      this.inputForm = {
        id: '',
        createDate: '',
        createBy: {
          id: '',
          name: this.$store.state.user.name
        },
        remarks: '',
        projectNumber: '',
        projectName: '',
        officeId: '',
        projectMoney: '',
        auditYear: '',
        planStartDate: '',
        planEndDate: '',
        projectMasterId: '',
        projectMasterName: '',
        projectLeaderName: '',
        projectLeaderId: '',
        procInsId: '',
        processDefinitionId: '',
        status: '',
        workAttachmentDtoList: [],
        cwProjectClientInfoDTOList: [],
        contractName: '',
        contractAmount: '',
        contractNum: '',
        payerSubject: '',
        paymentMethod: '',
        contractId: '',
        businessType: '',
        riskLevel: '',
        businessTypeName: '',
        planDate: [],
        realHeader: '',
        realHeaderName: '',
        clientContactsName: '',
        reportType: '',
        projectClassification: '',
        cwProjectClientContactDTOList: [],
        isHaveReport: '1',
        isPreInvoice: '0'
      }
      this.inputForm.id = id
      this.loading = false
      this.$nextTick(() => {
        this.$refs.inputForm.resetFields()
        this.loading = true
        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(data.reportType)) {
            this.reportTypeFlag = false
          } else {
            if ('10' === data.reportType) {
              this.reportTypeFlag = true
            } else {
              this.reportTypeFlag = false
            }
          }
          if (this.commonJS.isEmpty(this.inputForm.cwProjectClientContactDTOList)) {
            this.inputForm.cwProjectClientContactDTOList = []
          }
          if (this.commonJS.isEmpty(this.inputForm.isHaveReport)) {
            this.inputForm.isHaveReport = '1'
          }
          if (this.commonJS.isEmpty(this.inputForm.isPreInvoice)) {
            this.inputForm.isPreInvoice = '0'
          }
          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 = this.$store.state.user.name
          }
          if (this.commonJS.isEmpty(this.inputForm.officeId)) {
            this.inputForm.officeId = this.$store.state.user.office.id
          }
          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.projectLeaderId)) {
            this.inputForm.projectLeaderId = this.$store.state.user.id
            this.inputForm.projectLeaderName = this.$store.state.user.name
          }
          if (this.commonJS.isEmpty(this.inputForm.projectMoney)) {
            this.inputForm.projectMoney = ''
          }
          this.checkProject()
          // this.preInvoice()
          this.loading = false
        })
      })
    },
    reportTypeChange(value) {
      if (value && value === '10') {
        this.reportTypeFlag = true;
      } else {
        this.reportTypeFlag = false;
      }
      // this.preInvoice()
    }
    ,
    // 表单提交
    save() {
      this.$refs['inputForm'].validate((valid) => {
        if (valid) {
          this.loading = true
          if (this.commonJS.isEmpty(this.inputForm.cwProjectClientContactDTOList)) {
            this.loading = false
            this.$message.error('“客户联系人”中至少填写一条信息')
            throw new Error('“客户联系人”中至少填写一条信息')
          }
          this.contactSubmit()
          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”至少填写一项')
          } else {
            if (this.inputForm.projectMasterName === this.inputForm.realHeaderName) {
              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')
          }

          console.log('input', this.inputForm)
          projectRecordsService.saveForm(this.inputForm).then((data) => {
            this.$emit('refreshList')
            this.loading = false
            this.close()
          }).catch(() => {
            this.loading = false
          })
        }
      })
    },
    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: '',
        cwProjectClientContactDTOList: [],
        contactFirst: '',
        contactSecond: '',
        email: '',
        fax: '',
        name: '',
        position: '',
        sex: '',
        isHaveReport: '1',
        isPreInvoice: '0'
      }
      this.$refs.uploadComponent.clearUpload()
      this.$refs.inputForm.resetFields()
      this.visible = false
    },
    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()
      }
      if (type === 'contact') {
        let d = {
          contactFirst: '',
          contactSecond: '',
          email: '',
          fax: '',
          name: '',
          officeId: '',
          position: '',
          remarks: '',
          sex: ''
        }
        if (this.commonJS.isEmpty(this.inputForm.cwProjectClientContactDTOList)) {
          this.inputForm.cwProjectClientContactDTOList = []
        }
        this.$refs.contactTable.insertAt(d)
        this.inputForm.cwProjectClientContactDTOList.push(d)
        this.tableKeyContact = Math.random()
      }
    },

    openProjectClientContactPageForm() {
      console.log(this.inputForm.contractId);

      this.$refs.cwClientPageForm.init(this.inputForm.contractId)
      if (this.inputForm.cwProjectClientContactDTOList.length > 0) {
        this.programRow = this.inputForm.cwProjectClientContactDTOList.length
      } else {
        this.programRow = this.inputForm.cwProjectClientContactDTOList.length
      }
    },
    getProgram(rows) {
      rows.forEach((item, index) => {
        if (index === 0) {
          console.log(this.programRow)
          let d = {
            contactFirst: '',
            contactSecond: '',
            email: '',
            fax: '',
            name: '',
            officeId: '',
            position: '',
            remarks: '',
            sex: '',
            clientId: ""
          }
          this.$refs.contactTable.insertAt(d)
          this.inputForm.cwProjectClientContactDTOList.push(d)
          this.tableKeyContact = Math.random()

          let r = this.inputForm.cwProjectClientContactDTOList[this.programRow]
          r.name = item.name
          r.contactFirst = item.contactFirst
          r.contactSecond = item.contactSecond
          r.email = item.email
          r.fax = item.fax
          r.officeId = item.officeId
          r.position = item.position
          r.remarks = item.remarks
          r.sex = item.sex
          r.clientId = item.clientId
          this.inputForm.cwProjectClientContactDTOList[this.programRow] = r
        } else {
          let r = {
            name: item.name,
            contactFirst: item.contactFirst,
            contactSecond: item.contactSecond,
            email: item.email,
            fax: item.fax,
            officeId: item.officeId,
            position: item.position,
            remarks: item.remarks,
            sex: item.sex,
            clientId: item.clientId
          }
          this.inputForm.cwProjectClientContactDTOList.push(r)
        }
      })
      this.$forceUpdate()
      this.programRow = ''
      // this.inputForm.reconciliationArea = this.inputForm.financeInvoiceBaseDTOList[0].location
    },
    // 删除
    removeEvent(row, rowIndex, type) {
      if (type === 'client') {
        this.$refs.clientTable.remove(row)
        this.inputForm.cwProjectClientInfoDTOList.splice(rowIndex, 1)
      }
      if (type === 'contact') {
        this.$refs.contactTable.remove(row)
        this.inputForm.cwProjectClientContactDTOList.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) {
      // 首先删除之前合同与被服务单位的关联（委托方联系人）
      let _this = this
      const waitDelClient = function () {
        return new Promise(async (resolve, reject) => {
          if (_this.commonJS.isNotEmpty(_this.inputForm.contractId)) {
            // 根据合同id查询合同信息
            contractInfoService.findById(_this.inputForm.contractId).then((data) => {
              if (_this.commonJS.isNotEmpty(data.customerId)) {
                // 根据合同的委托人联系人id查询客户信息
                workClientService.queryById(data.customerId).then((client) => {
                  if (_this.commonJS.isNotEmpty(client.no)) {
                    // 将被服务单位中与合同委托人联系人相同删除
                    _this.inputForm.cwProjectClientInfoDTOList.forEach((item, index) => {
                      if (item.no === client.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 = []
          }
          workClientService.queryById(row.clientContacts).then((data) => {
            if (this.commonJS.isNotEmpty(data.id)) {
              let _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)
                this.inputForm.cwProjectClientInfoDTOList.push(data)
                this.tableKeyClient = Math.random()
              })
            }
          })
        }
      })
    },
    // 打开合同选择组件
    openContract() {
      this.$refs.workContractChooseCom.init()
    },
    openBusinessTypeForm() {
      this.$refs.cwProjectBusinessTypeListForm.init()
    },
    // 查看合同详情
    viewContract(id) {
      this.$refs.contractNameForm.init('view', id)
    },
    // 项目经理1改变事件
    changeSignatory1(value) {
      console.log('项目经理1', value)
      if (this.inputForm.realHeaderName === value && this.commonJS.isNotEmpty(value)) {
        this.$message.warning('项目经理1和项目经理2不可以相同')
        this.$nextTick(() => {
          this.inputForm.projectMasterId = ''
          this.inputForm.projectMasterName = ''
          // this.$refs.userSelect1.changeNameValue('')
          // this.$refs.userSelect1.clearSelectData()
          this.$forceUpdate()
        })
      } else {
        this.inputForm.projectMasterName = value
      }
    },
    // 项目经理2改变事件
    changeSignatory2(value) {
      if (this.inputForm.projectMasterId === value && this.commonJS.isNotEmpty(value)) {
        this.$message.warning('项目经理1和项目经理2不可以相同')
        this.$nextTick(() => {
          this.inputForm.realHeader = ''
          this.inputForm.realHeaderName = ''
          // this.$refs.userSelect2.changeNameValue('')
          // this.$refs.userSelect2.clearSelectData()
          this.$forceUpdate()
        })
      } else {
        this.inputForm.realHeader = value
      }
    },

	  selectProjectExecutorUser(user) {
		  console.log(user[0].name)
		  this.inputForm.projectExecutor = user[0].id
		  this.inputForm.projectExecutorName = user[0].name
	  },
	  openProjectExecutorDia1() {
		  this.$refs.selectProjectExecutorUser.init()
	  },
    blurEmail(index) {
      if (this.commonJS.isNotEmpty(this.inputForm.cwProjectClientContactDTOList[index].email)) {
        if (!this.validateXG.isEmail(this.inputForm.cwProjectClientContactDTOList[index].email)) {
          this.$message.error('客户联系人中，第' + (index + 1) + '条数据的“邮箱”填写错误，请重新填写')
          this.inputForm.cwProjectClientContactDTOList[index].email = ''
          throw new Error('客户联系人中，第' + (index + 1) + '条数据的“邮箱”填写错误，请重新填写')
        }
      }
    },
    contactSubmit() {
      this.inputForm.cwProjectClientContactDTOList.forEach((item, index) => {
        if (this.commonJS.isNotEmpty(item.email)) {
          if (!this.validateXG.isEmail(item.email)) {
            this.$message.error('客户联系人中，第' + (index + 1) + '条数据的“邮箱”填写错误')
            this.loading = false
            throw new Error('客户联系人中，第' + (index + 1) + '条数据的“邮箱”填写错误')
          }
        }
        if (this.commonJS.isEmpty(item.name)) {
          this.$message.error('客户联系人中，第' + (index + 1) + '条数据的“姓名”未填写')
          this.loading = false
          throw new Error('客户联系人中，第' + (index + 1) + '条数据的“姓名”未填写')
        }
        if (this.commonJS.isEmpty(item.sex)) {
          this.$message.error('客户联系人中，第' + (index + 1) + '条数据的“性别”未填写')
          this.loading = false
          throw new Error('客户联系人中，第' + (index + 1) + '条数据的“性别”未填写')
        }
        if (this.commonJS.isEmpty(item.officeId)) {
          this.$message.error('客户联系人中，第' + (index + 1) + '条数据的“部门”未填写')
          this.loading = false
          throw new Error('客户联系人中，第' + (index + 1) + '条数据的“部门”未填写')
        }
        if (this.commonJS.isEmpty(item.position)) {
          this.$message.error('客户联系人中，第' + (index + 1) + '条数据的“职务”未填写')
          this.loading = false
          throw new Error('客户联系人中，第' + (index + 1) + '条数据的“职务”未填写')
        }
        if (this.commonJS.isEmpty(item.contactFirst)) {
          this.$message.error('客户联系人中，第' + (index + 1) + '条数据的“联系方式1”未填写')
          this.loading = false
          throw new Error('客户联系人中，第' + (index + 1) + '条数据的“联系方式1”未填写')
        }
      })
    },
    businessTypeList() {
      this.cwProjectBusinessTypeService.findListByIsShow({
        'current': this.tablePage.currentPage,
        'size': this.tablePage.pageSize,
        'orders': this.tablePage.orders,
        ...this.typeSearchForm
      }).then((data) => {
        console.log(data)
        this.typeDataList = data.records
        this.tablePage.total = data.total
        this.loading = false
      })
    },
    getBusinessType(row) {
      this.inputForm.businessType = row.id
      this.inputForm.businessTypeName = row.name
    },
    //校验当前项目是否生成报告或根据项目开票
    checkProject() {
      projectReportService.getIdByProjectId2(this.inputForm.id, '').then((data) => {
        console.log('report', data)
        if (data.length === 0) {
          this.isReport = false
          this.ifCheck = false
        } else {
          this.isReport = true
          this.ifCheck = true
        }
      })
      cwFinanceInvoiceService.getByIds2(this.inputForm.id, '').then((data) => {
        console.log('invoice', data)
        if (data.length === 0) {
          this.isReport = false
          this.ifCheck = false
        } else {
          this.isReport = true
          this.ifCheck = true
        }
      })
    },
    preInvoice() {
      if (this.commonJS.isNotEmpty(this.inputForm.isHaveReport) && this.commonJS.isNotEmpty(this.inputForm.projectClassification) && this.commonJS.isNotEmpty(this.inputForm.reportType)) {
        if (this.inputForm.isHaveReport === '1' && (this.inputForm.projectClassification === '16' || this.inputForm.projectClassification === '17') && this.inputForm.reportType === '10') {
          this.ifCheck = false
        } else {
          this.ifCheck = true
        }
      } else {
        this.ifCheck = true
      }
    },
    openUserDia1() {
      this.$refs.userSelect1.init()
    },
    selectUser1(user) {
      console.log(user[0].name)
      this.inputForm.projectLeaderId = user[0].id
      this.inputForm.projectLeaderName = user[0].name
    },

    openUserDia2() {
      this.$refs.userSelect2.init()
    },
    selectUser2(user) {
      console.log(user[0].name)
      this.inputForm.projectMasterId = user[0].id
      this.inputForm.projectMasterName = user[0].name
    },
    clearUser2() {
      this.inputForm.projectMasterId = ""
      this.inputForm.projectMasterName = ""
    },
    openUserDia3() {
      this.$refs.userSelect3.init()
    },
    selectUser3(user) {
      console.log(user[0].name)
      this.inputForm.realHeader = user[0].id
      this.inputForm.realHeaderName = user[0].name
    },
    clearUser3() {
      this.inputForm.realHeader = ""
      this.inputForm.realHeaderName = ""
    },
  }
}
</script>
<style scoped>
/deep/ .el-input-number .el-input__inner {
  text-align: left;
}
</style>
<style>
.vxe-select--panel {
  z-index: 9997 !important
}
</style>
