<template>
  <div class="org-person">
    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="80px" label-position="top" class="rule-form-orange">
      <h2 style="font-weight: 400; width: 100%;">{{ title }}</h2>
      <!-- <el-form-item
        label="头像"
        prop="desc"
        style="width: 100%;"
        class="form-required"
      >
        <cy-upload
          ref="fileStorage"
          :upload-params="uploadParams"
          :file-data="ruleForm.fileStorageList"
          :upload-from-orange-status="true"
          :isPreviewFile="true"
          placeholder="请上传头像"
        />
      </el-form-item> -->
      <el-form-item label="姓名" prop="name">
        <el-input
          v-model="ruleForm.name"
          placeholder="请输入姓名"
        ></el-input>
      </el-form-item>
      <el-form-item label="身份证号" prop="idCard">
        <el-input
          v-model="ruleForm.idCard"
          placeholder="请输入身份证号"
        ></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input
          v-model="ruleForm.mobile"
          placeholder="请输入手机号"
        ></el-input>
      </el-form-item>
      <el-form-item label="企业邮箱" prop="email">
        <el-input
          v-model="ruleForm.email"
          placeholder="请输入企业邮箱"
        ></el-input>
      </el-form-item>
      <el-form-item label="登录名" prop="loginName">
        <el-input
          v-model="ruleForm.loginName"
          placeholder="请输入登录名"
        ></el-input>
      </el-form-item>
      <el-form-item label="登录密码" prop="password" v-if="!personInfo || !personInfo.id">
        <el-input
          v-model="ruleForm.password"
          placeholder="请输入登录密码"
        ></el-input>
      </el-form-item>
      <el-form-item label="部门" prop="orgIdList" style="width: 100%;">
        <el-cascader
          v-model="orgIds"
          style="width: 100%;"
          :options="orgListInfo"
          ref="cascader"
          :props="{ multiple: true, checkStrictly: true, emitPath: false, value: 'id', label: 'name' }"
          :show-all-levels="false"
          @change="chooseOrg"
          @remove-tag="chooseOrg"
          placeholder="请选择"
          clearable>
        </el-cascader>
      </el-form-item>
      <el-form-item label="职级" prop="rank">
        <el-select v-model="ruleForm.rank" placeholder="请选择职级">
          <el-option
            v-for="item in pList"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="职位" prop="position">
        <el-input
          v-model="ruleForm.position"
          placeholder="请输入职位"
        ></el-input>
      </el-form-item>
      <el-form-item label="推荐码" prop="referenceNumber">
        <el-input
          v-model="ruleForm.referenceNumber"
          placeholder="请输入推荐码"
          disabled
        ></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="enabled">
        <el-radio-group v-model="ruleForm.enabled">
          <el-radio :label="true">启用</el-radio>
          <el-radio :label="false">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <template v-if="ruleForm.orgIdList && ruleForm.orgIdList.length > 0">
        <el-form-item v-for="(item, index) in ruleForm.orgIdList" :key="item.id + '_' + index" 
          :label="`${item.name || item.label}身份`" style="width: 100%;">
          <el-radio-group v-model="item.userIdentity">
            <el-radio :label="false">普通员工</el-radio>
            <el-radio :label="true">负责人</el-radio>
          </el-radio-group>
        </el-form-item>
      </template>
    </el-form>
    <div class="submit-btn">
      <el-button type="primary" @click="save(1)">保存并继续添加</el-button>
      <el-button type="primary" @click="save">保存</el-button>
      <el-button type="normal" @click="$emit('close', 1)">取消</el-button>
    </div>
  </div>
</template>

<script>
import request from '@/utils/request'
import md5 from 'js-md5'
export default {
  data() {
    this.pList = []
    for(let i = 0; i < 15; i += 1) {
      this.pList.push(`P${i + 1}`)
    }
    const validateLoginName = (rule, value, callback) => {
      if(!value) {
        callback(new Error('请输入登录名'))
      } else {
        if(this.infoId) {
          callback()
        } else {
          request({
            url: '/user/validatorLoginName',
            method: 'get',
            params: {
              loginName: this.ruleForm.loginName
            }
          }).then(({ data }) => {
            if(data === false) {
              callback(new Error('登录名重复'))
            } else {
              callback()
            }
          }, err => {
            callback(new Error('登录名校验失败'))
          })
        }
      }
    }
    return {
      ruleForm: {
        name: '',
        mobile: '',
        email: '',
        loginName: '',
        password: '',
        position: '',
        rank: '',
        orgIdList: [],
        referenceNumber: '',
        idCard: '',
        enabled: true
      },
      rules: {
        name: [{ required: true, message: '请请输入姓名', trigger: 'blur' }],
        mobile: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
        idCard: [{ required: true, message: '请输入身份证号', trigger: 'blur' }],
        email: [{ required: true, message: '请输入企业邮箱', trigger: 'blur' }],
        loginName: [{ required: true, trigger: 'blur', validator: validateLoginName }],
        password: [{ required: true, message: '请输入登录密码', trigger: 'blur' }],
        rank: [{ required: true, message: '请选择职级', trigger: 'change' }],
        orgIdList: [{ required: true, message: '请选择部门', trigger: 'change' }]
      },
      uploadParams: {},
      orgIds: [],
      orgListInfo: [],
      title: '添加成员',
      infoId: ''
    }
  },
  props: ["info", "orgList", "personInfo"],
  mounted() {
    this.orgListInfo = JSON.parse(JSON.stringify(this.orgList))
    this.setOrgName(this.orgListInfo)
    if(this.personInfo && this.personInfo.id) {
      this.getDetail(this.personInfo.id)
    } else {
      this.orgIds.push(this.info.id)
      this.ruleForm.orgIdList.push({name: this.info.name.split('（')[0], id: this.info.id, userIdentity: false})
      this.$nextTick(() => {
        if(this.$refs.cascader) {
          this.$refs.cascader.presentTags.push({text: this.info.name.split('（')[0], closable: true})
        }
      })
    }
    
  },
  methods: {
    addPerson(isNext) {
      let data = new FormData()
      Object.keys(this.ruleForm).forEach(key => {
        if(key == 'orgIdList') {
          this.ruleForm.orgIdList.forEach((item, index) => {
            data.append(`orgIdList[${index}]`, item.id)
            data.append(`userOrgRelList[${index}].orgId`, item.id)
            data.append(`userOrgRelList[${index}].userIdentity`, item.userIdentity)
          })
        } else if(key == 'password') {
          data.append('password', md5(this.ruleForm.password))
        } else {
          data.append(key, this.ruleForm[key])
        }
      })
      if(this.infoId) {
        data.append('id', this.infoId)
      }
      request({
        url: this.infoId ? '/user/do_update' : '/user/do_add',
        method: 'post',
        data
      }).then(() => {
        this.$message.success(this.infoId ? '修改成功' : '新增成功')
        if(isNext == 1) {
          this.clearInfo()
          this.$emit('close')
        } else {
          this.$emit('close', 1)
        }
      })
    },
    chooseOrg() {
      this.$nextTick(() => {
        this.ruleForm.orgIdList = this.$refs.cascader.getCheckedNodes().map(item => {
          return {name: item.data.name, id: item.data.id, userIdentity: false}
        })
        this.$refs.ruleForm.validateField('orgIdList', () => {})
      })
    },
    save(val) {
      this.$refs.ruleForm.validate(flag => {
        if(flag) {
          this.addPerson(val)
        } else {
          this.$message.error('必填项不能为空')
        }
      })
    },
    setOrgName(orgList) {
      if(!orgList || orgList.length === 0) return
      orgList.forEach(item => {
        if(item.children && item.children.length > 0) {
          item.name = item.name.split('（')[0]
          item.userIdentity = false
          this.setOrgName(item.children)
        } else {
          item.userIdentity = false
          item.name = item.name.split('（')[0]
        }
      })
    },
    clearInfo() {
      this.$refs.ruleForm.resetFields()
      this.$refs.cascader.handleClear()
      this.$nextTick(() => {
        this.orgIds = [this.info.id]
        this.ruleForm.orgIdList.push({name: this.info.name, id: this.info.id, userIdentity: false})
        this.$refs.cascader.presentTags.push({text: this.info.name.split('（')[0], closable: true})
        this.chooseOrg()
      })
    },
    getDetail(id) {
      request({
        url: '/user/do_get',
        method: 'get',
        params: {
          id: id,
          orgId: 1
        }
      }).then(({ data }) => {
        Object.keys(this.ruleForm).forEach(key => {
          if(key !== 'orgIdList' && (data[key] || data[key] === 0 || data[key] === false)) {
            this.ruleForm[key] = data[key]
          }
        })
        this.title = '修改成员'
        this.infoId = this.personInfo.id
        this.orgIds = [...data.orgIdList]
        this.ruleForm.orgIdList = data.userOrgRelList.map(item => {
          return {
            name: item.orgName,
            id: item.orgId,
            userIdentity: item.userIdentity
          }
        })
        this.$nextTick(() => {
          if(this.$refs.cascader) {
            this.$refs.cascader.presentTags = []
            data.userOrgRelList.forEach(item => {
              this.$refs.cascader.presentTags.push({text: item.orgName, closable: true})
            })
          }
        })
      })
    }
  },
  watch: {
    'personInfo.id': {
      handler(val) {
        if(val) {
          this.getDetail(this.personInfo.id)
        }
      },
      immediate: true
    }
  }
}
</script>

<style lang="scss">
.org-person {
  padding: 20px 0 20px 20px;
}
</style>