<template xmlns:v-slot="http://www.w3.org/1999/XSL/Transform">
  <div>
    <el-dialog
      :title="title"
      :close-on-click-modal="false"
	  draggable
      width="1100px"
      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="method==='view'"
                     label-width="135px" @submit.native.prevent>
              <el-divider content-position="left"><i class="el-icon-document"></i> 项目成员信息</el-divider>
              <el-row  :gutter="15">
                <el-col :span="24">
                  <el-form-item label="项目名称" prop="projectName"
                                :rules="[
                   ]">
                    <el-input :disabled="true" 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="projectLeaderId"
                                :rules="[
                   ]">
                    <UserSelect :disabled="true" :limit='1' :modelValue="inputForm.projectLeaderId" @update:modelValue='(value) => {inputForm.projectLeaderId = value}'></UserSelect>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="合同名称" prop="contractName"
                                :rules="[
                 ]">
                    <el-input :disabled="true" v-model="inputForm.contractName" 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-row>
        </el-form>
          <el-divider content-position="left"><i class="el-icon-document"></i> 项目组成员明细</el-divider>
            <el-row :gutter="15">
<!--              <el-button type="primary" style="margin-bottom: 15px" :disabled="method==='view'" @click="insertEvent('members')">-->
<!--                选择成员-->
<!--              </el-button>-->
              <UserSelectButton ref="userSelectButton" @getValue="(value) => {addMembers(value)}"></UserSelectButton>
            </el-row>
            <el-row :gutter="15" style="margin-top: 15px">
                  <el-form :disabled="method==='view'">
                    <vxe-table
                      border
                      show-overflow
                      show-footer
                      :column-config="{resizable: true}"
                      ref="membersTable"
                      :key="tableKeyMembers"
                      class="vxe-table-element"
                      :data="inputForm.cwProjectMembersDTOList"
                      style=""
                      highlight-current-row
                    >
                      <vxe-table-column min-width="176" align="center" field="name" title="姓名"></vxe-table-column>
                      <vxe-table-column min-width="176" align="center" field="officeName" title="部门"></vxe-table-column>
                      <vxe-table-column min-width="176" align="center" field="roleName" title="角色"></vxe-table-column>
                      <vxe-table-column min-width="176" align="center" field="mobile" title="手机号"></vxe-table-column>
                      <vxe-table-column min-width="176" align="center" field="status" title="状态">
                        <template #default="scope">
                          <span v-if="scope.row.status === '0'" style="color: #67C23A">正常</span>
                          <span v-else>移除</span>
                        </template>
                      </vxe-table-column>

                      <vxe-table-column align="center" title="操作" min-width="176">
                        <template #default="scope">
                          <el-button v-if="scope.row.status === '0'" type="info" @click="removeDate(scope.$rowIndex)">移除</el-button>
                          <el-button v-if="scope.row.status === '1'" type="primary" @click="aliveDate(scope.$rowIndex)">恢复</el-button>
                          <el-button type="danger" @click="removeEvent(scope.row,scope.$rowIndex,'members')">删除</el-button>
                        </template>
                      </vxe-table-column>
                    </vxe-table>
                  </el-form>
                </el-row>
      </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"></WorkContractChooseCom>
    <WorkClientChooseForm ref="workClientChooseForm"></WorkClientChooseForm>
    <CwProjectBusinessTypeListForm ref="cwProjectBusinessTypeListForm"></CwProjectBusinessTypeListForm>
    <ContractNameForm ref="contractNameForm"></ContractNameForm>
  </div>
</template>

<script>
  import UserSelect from '@/components/userSelect'
  import projectRecordsService from '@/api/cw/projectRecords/ProjectRecordsService'
  import EnterpriseSearchService from '@/api/cw/common/EnterpriseSearchService'
  import WorkClientChooseForm from '../workClientInfo/WorkClientChooseForm'
  import WorkContractChooseCom from './WorkContractChooseCom'
  import CwProjectBusinessTypeListForm from '@/views/cw/projectBusinessType/CwProjectBusinessTypeListForm'
  import ContractNameForm from '../workContract/ContractNameForm'
  import UserSelectButton from '@/components/userSelectButton'
  import userService from '@/api/sys/UserService'
  export default {
    props: {
      businessId: {
        type: String,
        default: ''
      },
      formReadOnly: {
        type: Boolean,
        default: false
      }
    },
    data () {
      return {
        title: '',
        method: '',
        loading: false,
        inputForm: {
          id: '',
          createDate: '',
          createBy: {
            id: '',
            name: ''
          },
          remarks: '',
          projectNumber: '',
          projectName: '',
          officeId: '',
          projectMoney: '',
          auditYear: '',
          planStartDate: '',
          planEndDate: '',
          projectMasterId: '',
          projectLeaderId: '',
          procInsId: '',
          processDefinitionId: '',
          status: '',
          workAttachmentDtoList: [],
          cwProjectClientInfoDTOList: [],
          contractName: '',
          contractAmount: '',
          contractNum: '',
          payerSubject: '',
          paymentMethod: '',
          contractId: '',
          businessType: '',
          riskLevel: '',
          businessTypeName: '',
          planDate: [],
          realHeader: '',
          clientContactsName: '',
          reportType: '',
          cwProjectClientContactDTOList: [],
          cwProjectMembersDTOList: []
        },
        keyWatch: '',
        activeName: 'client',
        tableKey: '',
        tableKeyClient: '1',
        tableKeyContact: '2',
        tableKeyMembers: '3',
        visible: false,
        status: [
          {label: '正常', value: '0'},
          {label: '移除', value: '1'}
        ]
      }
    },
    enterpriseSearchService: null,
    created () {
      this.enterpriseSearchService = new EnterpriseSearchService()
    },
    computed: {
      bus: {
        get () {
          return this.businessId
        },
        set (val) {
          this.businessId = val
        }
      }
    },
    watch: {
      'keyWatch': {
        handler (newVal) {
          if (this.commonJS.isNotEmpty(this.bus)) {
            this.init('', this.bus)
          } else {
            this.$nextTick(() => {
              this.$refs.inputForm.resetFields()
            })
          }
        }
      }
    },
    components: {
      UserSelect,
      WorkClientChooseForm,
      WorkContractChooseCom,
      CwProjectBusinessTypeListForm,
      ContractNameForm,
      UserSelectButton
    },
    methods: {
      getKeyWatch (keyWatch) {
        this.keyWatch = keyWatch
      },
      forUpdate () {
        this.$forceUpdate()
      },
      init (method, id) {
        if (method === 'view') {
          this.title = '项目组成员详情'
        } else if (method === 'edit') {
          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: '',
          projectLeaderId: '',
          procInsId: '',
          processDefinitionId: '',
          status: '',
          workAttachmentDtoList: [],
          cwProjectClientInfoDTOList: [],
          contractName: '',
          contractAmount: '',
          contractNum: '',
          payerSubject: '',
          paymentMethod: '',
          contractId: '',
          businessType: '',
          riskLevel: '',
          businessTypeName: '',
          planDate: [],
          realHeader: '',
          clientContactsName: '',
          reportType: '',
          cwProjectClientContactDTOList: [],
          cwProjectMembersDTOList: []
        }
        this.inputForm.id = id
        this.loading = false
        this.$nextTick(() => {
          this.$refs.inputForm.resetFields()
          this.loading = true
          projectRecordsService.queryById(this.inputForm.id).then((data) => {
            this.inputForm = this.recover(this.inputForm, data)
            this.inputForm = JSON.parse(JSON.stringify(this.inputForm))
            if (this.commonJS.isEmpty(this.inputForm.cwProjectMembersDTOList)) {
              this.inputForm.cwProjectMembersDTOList = []
            } else {
              this.inputForm.cwProjectMembersDTOList.forEach((member, index) => {
                userService.queryDetailById(member.userId).then((data) => {
                  member.name = this.commonJS.isEmpty(data.name) ? '' : data.name
                  member.mobile = this.commonJS.isEmpty(data.mobile) ? '' : data.mobile
                  member.officeName = this.commonJS.isEmpty(data.officeDTO) ? '' : this.commonJS.isEmpty(data.officeDTO.name) ? '' : data.officeDTO.name
                  member.roleName = this.commonJS.isEmpty(data.roleList) ? '' : data.roleList.map(role => { return this.commonJS.isEmpty(role.name) ? '' : role.name }).join(',')
                  this.tableKeyMembers = Math.random()
                })
              })
            }
            this.loading = false
          })
        })
      },
      // 表单提交
      save () {
        this.$refs['inputForm'].validate((valid) => {
          if (valid) {
            this.loading = true
            projectRecordsService.updateMembers(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: [],
          cwProjectMembersDTOList: []
        }
        // 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 === '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()
        }
      },
      // 删除
      removeEvent (row, rowIndex, type) {
        if (type === 'members') {
          this.$refs.membersTable.remove(row)
          this.inputForm.cwProjectMembersDTOList.splice(rowIndex, 1)
        }
      },
      removeDate (index) {
        this.inputForm.cwProjectMembersDTOList[index].status = '1'
      },
      aliveDate (index) {
        this.inputForm.cwProjectMembersDTOList[index].status = '0'
      },
      addMembers (value) {
        if (this.commonJS.isNotEmpty(value)) {
          userService.queryDetailList(value).then((data) => {
            data.forEach(item => {
              this.inputForm.cwProjectMembersDTOList.forEach(member => {
                if (this.commonJS.isEmpty(item.name) || member.name === item.name) {
                  this.$message.error('成员“ ' + item.name + ' ”已存在')
                  throw new Error('成员“ ' + item.name + ' ”已存在')
                }
              })
            })
            data.forEach(item => {
              let param = {
                userId: item.id,
                status: '0',
                name: this.commonJS.isEmpty(item.name) ? '' : item.name,
                mobile: this.commonJS.isEmpty(item.mobile) ? '' : item.mobile,
                officeName: this.commonJS.isEmpty(item.officeDTO) ? '' : this.commonJS.isEmpty(item.officeDTO.name) ? '' : item.officeDTO.name,
                roleName: this.commonJS.isEmpty(item.roleList) ? '' : item.roleList.map(role => { return this.commonJS.isEmpty(role.name) ? '' : role.name }).join(',')
              }
              this.inputForm.cwProjectMembersDTOList.push(param)
			  this.tableKeyMembers = Math.random()
            })
          })
        }
      }
    }
  }
</script>
<style scoped>
  /deep/ .el-input-number .el-input__inner {
    text-align: left;
  }
</style>
