<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="projectLevel"
									:rules="[
                  {required: true, message:'请选择项目等级(500万及500万以上为A级，500万以下为B级)', trigger:'blur'}
               ]">
						  <el-radio-group v-model="inputForm.projectLevel">
							  <el-radio v-for="item in $dictUtils.getDictList('cw_project_level')" :label="item.value" >{{item.label}}</el-radio>
						  </el-radio-group>
					  </el-form-item>
					  <div style="color: red; display: block; margin-left: 140px;">500万及500万以上为A级，500万以下为B级</div>
				  </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 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_engineering_consultation_type')"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                      </el-option>
                    </el-select>
					  <div style="color: red; display: block; ">与归档资料关联，请仔细选择</div>
                  </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="[
                   ]">
                    <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="[
                   ]">
                    <UserSelectSignatory :readonly="true" :disabled="status === 'audit' || status === 'taskFormDetail'" :limit='1' :modelValue="inputForm.projectLeaderId" @update:modelValue='(value) => {inputForm.projectLeaderId = value}'></UserSelectSignatory>
					  <span style="color: red">必须拥有一级造价师证书</span>
				  </el-form-item>
                </el-col>
				  <el-col :span="12">
					  <el-form-item label="工程类型" prop="engineeringType"
									:rules="[
                                 {required: true, message:'工程类型不能为空', trigger:'blur'}
                  ]">
						  <el-tree-select
							  v-model="inputForm.engineeringType"
							  :data="engineeringTypeList"
							  :render-after-expand="false"
							  style="width: 100%"
						  />
					  </el-form-item>
				  </el-col>
				  <el-col :span="12">
					  <el-form-item label="项目经理1" prop="projectMasterId"
									:rules="[
                   ]">
<!--                    <UserSelectForQualification style="width: 100%" ref="userSelect1" :disabled="status === 'audit' || status === 'taskFormDetail'"-->
<!--										 :readonly="true" :limit='1' :modelValue="inputForm.projectMasterId"-->
<!--										 @update:modelValue='(value) => {changeSignatory1(value)}'></UserSelectForQualification>-->
						  <UserSelectSignatory :readonly="true" :disabled="status === 'audit' || status === 'taskFormDetail'"
											   :limit='1' :modelValue="inputForm.projectMasterId"
											   @update:modelValue='(value) => {inputForm.projectMasterId = value}'></UserSelectSignatory>
					  </el-form-item>
				  </el-col>
				  <el-col :span="12">
                  <el-form-item label="项目经理2" prop="realHeader"
                                :rules="[
                   ]">
<!--                    <UserSelectForQualification style="width: 100%" ref="userSelect2" :disabled="status === 'audit' || status === 'taskFormDetail'"-->
<!--										 :readonly="true" :limit='1' :modelValue="inputForm.realHeader"-->
<!--										 @update:modelValue='(value) => {changeSignatory2(value)}'></UserSelectForQualification>-->
					  <UserSelectSignatory :readonly="true" :disabled="status === 'audit' || status === 'taskFormDetail'"
										   :limit='1' :modelValue="inputForm.realHeader"
										   @update:modelValue='(value) => {inputForm.realHeader = 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-col :span="12">
					  <el-form-item label="项目开始时间" prop="projectStartTime"
									:rules="[
                   ]">
						  <el-date-picker
							  v-model="inputForm.projectStartTime"
							  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="projectEndTime"
									:rules="[
                   ]">
						  <el-date-picker
							  v-model="inputForm.projectEndTime"
							  type="date"
							  value-format="YYYY-MM-DD"
							  placeholder="选择项目结束时间"
							  style="width:100%"
							  placement="bottom-start"
							  clearable>
						  </el-date-picker>
					  </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 min-width="135" 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 min-width="135" 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 min-width="135" 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 min-width="137" 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 min-width="137" 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 min-width="137" 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 min-width="137" 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 min-width="137" 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 min-width="137" 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 name="construction">
					  <template v-slot:label>
						  <span> 施工方信息</span>
					  </template>
					  <el-row :gutter="15">
						  <el-button style="margin-bottom: 15px" type="primary" :disabled="status === 'audit' || status === 'taskFormDetail'" @click="openConstructionForm()"  plain>
							  添加施工方信息联系人
						  </el-button>
					  </el-row>
					  <el-row  :gutter="15">
						  <el-form :disabled="true" style="width: 100%;">
							  <vxe-table
								  border
								  show-overflow
								  show-footer
								  :column-config="{resizable: true}"
								  ref="construction"
								  :key="tableKeyConstruction"
								  class="vxe-table-element"
								  :data="inputForm.cwProjectConstructionList"
								  keep-source
								  style=""
								  highlight-current-row
								  :edit-config="{trigger: 'click', mode: 'row', showStatus: false, autoClear: true, icon: '-'}"
							  >
								  <vxe-table-column min-width="306" 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 min-width="306" align="center" field="clientName" title="联系人姓名" :edit-render="{}">
									  <template v-slot:edit="scope">
										  <el-input v-model="scope.row.clientName" placeholder="联系人姓名" clearable></el-input>
									  </template>
								  </vxe-table-column>
								  <vxe-table-column min-width="307" 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 min-width="308" 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" title="操作" width="100">
									  <template v-slot="scope">
										  <el-button type="danger" @click="removeEvent(scope.row,scope.$rowIndex,'construction')">删除</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>
	  <CwConstructionForm ref="cwConstructionForm" @getProgram2="getProgram2"></CwConstructionForm>
  </div>




</template>

<script>
	import CwConstructionForm from './CwConstructionForm'
  import CwClientPageForm from './CwClientPageForm'
  import UpLoadComponent from '@/views/common/UpLoadComponent'
  import SelectTree from '@/components/treeSelect/treeSelect.vue'
  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 '@/components/userSelect'
  import UserSelectForQualification from '@/components/userSelectForQualification'
  import CwProjectBusinessTypeService from '@/api/cw/projectBusinessType/CwProjectBusinessTypeService'
  export default {
    props: {
      businessId: {
        type: String,
        default: ''
      },
      formReadOnly: {
        type: Boolean,
        default: false
      },
      status: {
        type: String,
        default: ''
      }
    },
    data () {
      return {
		  engineeringTypeList: [],
	    showChildDialog: false,
	    typeVisible:false,
        title: '',
        method: '',
        loading: false,
        inputForm: {
			engineeringType: '',
			projectType: '',
          id: '',
          createDate: '',
			projectStartTime: '',
			projectEndTime: '',
          createBy: {
            id: '',
            name: ''
          },
          remarks: '',
          projectNumber: '',
          projectName: '',
          officeId: '',
          projectMoney: '',
          auditYear: '',
          planStartDate: '',
          planEndDate: '',
          projectMasterId: '',
          projectLeaderId: '',
          procInsId: '',
          processDefinitionId: '',
          status: '',
          workAttachmentDtoList: [],
			cwProjectConstructionList: [],
          cwProjectClientInfoDTOList: [],
          contractName: '',
          contractAmount: '',
          contractNum: '',
          payerSubject: '',
          paymentMethod: '',
          contractId: '',
          businessType: '',
          riskLevel: '',
			projectLevel: '',
          businessTypeName: '',
          planDate: [],
          realHeader: '',
          clientContactsName: '',
          reportType: '',
          cwProjectClientContactDTOList: []
        },
		  programRow: '',
		  programRow2: '',
        keyWatch: '',
        activeName: 'client',
        tableKey: '',
        tableKeyClient: '1',
        tableKeyContact: '2',
		  tableKeyConstruction: '3',
        visible: 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: []
		  },
      }
    },
	  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: {
		CwConstructionForm,
      CwClientPageForm,
      UpLoadComponent,
      SelectTree,
      WorkClientChooseForm,
      WorkContractChooseCom,
      CwProjectBusinessTypeListForm,
      ContractNameForm,
      UserSelectSignatory,
		UserSelectForQualification,
	  CwProjectBusinessTypeService
    },
    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 = {
			engineeringType: '',
			projectType: '',
          id: '',
          createDate: '',
			projectStartTime: '',
			projectEndTime: '',
          createBy: {
            id: '',
            name: this.$store.state.user.name
          },
          remarks: '',
          projectNumber: '',
          projectName: '',
          officeId: '',
          projectMoney: '',
          auditYear: '',
          planStartDate: '',
          planEndDate: '',
          projectMasterId: '',
          projectLeaderId: '',
          procInsId: '',
          processDefinitionId: '',
          status: '',
          workAttachmentDtoList: [],
          cwProjectClientInfoDTOList: [],
			cwProjectConstructionList: [],
          contractName: '',
          contractAmount: '',
          contractNum: '',
          payerSubject: '',
          paymentMethod: '',
          contractId: '',
          businessType: '',
          riskLevel: '',
			projectLevel: '',
          businessTypeName: '',
          planDate: [],
          realHeader: '',
          clientContactsName: '',
          reportType: '',
          cwProjectClientContactDTOList: []
        }
		  this.engineeringTypeList = []
        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.engineeringTypeList = data.engineeringTypeList
            this.inputForm = JSON.parse(JSON.stringify(this.inputForm))
            if (this.commonJS.isEmpty(this.inputForm.workAttachmentDtoList)) {
              this.inputForm.workAttachmentDtoList = []
            }
            if (this.commonJS.isEmpty(this.inputForm.cwProjectClientContactDTOList)) {
              this.inputForm.cwProjectClientContactDTOList = []
            }
            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.cwProjectConstructionList)) {
              this.inputForm.cwProjectConstructionList = []
            }
            if (this.commonJS.isEmpty(this.inputForm.projectLeaderId)) {
              this.inputForm.projectLeaderId = this.$store.state.user.id
            }
            if (this.commonJS.isEmpty(this.inputForm.projectMoney)) {
              this.inputForm.projectMoney = ''
            }
            this.loading = false
          })
        })
      },
      // 表单提交
      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”至少填写一项')
            }
            if (this.commonJS.isEmpty(this.inputForm.cwProjectClientInfoDTOList)) {
              this.loading = false
              this.$message.error('“被服务单位”中至少填写一条信息')
              throw new Error('“被服务单位”中至少填写一条信息')
            }
			  if (this.inputForm.projectLevel === '1') {
				  if (this.inputForm.projectMoney < 500) {
					  this.loading = false
					  this.$message.error('送审规模小于500万元,项目等级请选择B级!')
					  throw new Error('送审规模小于500万元,项目等级请选择B级!')
				  }

			  } else {
				  if (this.inputForm.projectMoney >= 500) {
					  this.loading = false
					  this.$message.error('送审规模大于500万元,项目等级请选择A级!')
					  throw new Error('送审规模大于500万元,项目等级请选择A级!')
				  }
			  }
            if (this.$refs.uploadComponent.checkProgress()) {
              this.loading = false
              throw new Error()
            }
            if (this.commonJS.isNotEmpty(this.inputForm.planDate)) {
				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.inputForm.projectType = '2'
            projectRecordsService.saveForm(this.inputForm).then((data) => {
              this.$emit('refreshList')
              this.loading = false
              this.close()
            }).catch(() => {
              this.loading = false
            })
          }
        })
      },
      close () {
		  this.engineeringTypeList = []
        this.inputForm = {
			engineeringType: '',
			projectType: '',
          id: '',
          createDate: '',
			projectStartTime: '',
			projectEndTime: '',
          createBy: {
            id: '',
            name: ''
          },
          remarks: '',
          projectNumber: '',
          projectName: '',
          officeId: '',
          projectMoney: '',
          auditYear: '',
          planStartDate: '',
          planEndDate: '',
          projectMasterId: '',
          projectLeaderId: '',
          procInsId: '',
          processDefinitionId: '',
          status: '',
          workAttachmentDtoList: [],
          cwProjectClientInfoDTOList: [],
			cwProjectConstructionList: [],
          contractName: '',
          contractAmount: '',
          contractNum: '',
          payerSubject: '',
          paymentMethod: '',
          contractId: '',
          businessType: '',
          riskLevel: '',
			projectLevel: '',
          businessTypeName: '',
          planDate: [],
          realHeader: '',
          clientContactsName: '',
          reportType: '',
          cwProjectClientContactDTOList: [],
          contactFirst: '',
          contactSecond: '',
          email: '',
          fax: '',
          name: '',
          position: '',
          sex: ''
        }
        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 () {
        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: ''
            }
            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
            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
            }
            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)
        }
		  if (type === 'construction') {
			  this.$refs.construction.remove(row)
			  this.inputForm.cwProjectConstructionList.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.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
        }
      },
      // 项目经理2改变事件
      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
        }
      },
      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
		},
		openConstructionForm () {
			this.$refs.cwConstructionForm.init()
			if (this.inputForm.cwProjectConstructionList.length > 0) {
				this.programRow2 = this.inputForm.cwProjectConstructionList.length
			} else {
				this.programRow2 = this.inputForm.cwProjectConstructionList.length
			}
		},
		getProgram2 (rows) {
			console.log('rows', rows)
			rows.forEach((item, index) => {
				if (index === 0) {
					let d = {
						name: '',
						clientName: '',
						contactFirst: '',
						contactSecond: '',
						clientId: ''
					}
					this.$refs.construction.insertAt(d)
					this.inputForm.cwProjectConstructionList.push(d)
					this.tableKeyConstruction = Math.random()

					let r = this.inputForm.cwProjectConstructionList[this.programRow2]
					r.name = item.name
					r.clientName = item.clientName
					r.contactFirst = item.contactFirst
					r.contactSecond = item.contactSecond
					r.clientId = item.clientId
					this.inputForm.cwProjectConstructionList[this.programRow2] = r
				} else {
					let r = {
						name: item.name,
						clientName: item.clientName,
						contactFirst: item.contactFirst,
						contactSecond: item.contactSecond,
						clientId: item.clientId
					}
					this.inputForm.cwProjectConstructionList.push(r)
					this.tableKeyConstruction = Math.random()
				}
			})
			this.$forceUpdate()
			this.programRow2 = ''
		},
    }
  }
</script>
<style scoped>
  /deep/ .el-input-number .el-input__inner {
    text-align: left;
  }
</style>
<style>
  .vxe-select--panel {
    z-index: 9997 !important
  }
</style>
