<!-- 用户编辑弹窗 -->
<template>
  <ele-modal width="800px" :visible="visible" :close-on-click-modal="false" custom-class="ele-dialog-form"
             :title="isUpdate ? '修改人员' : '添加人员'" @update:visible="updateVisible">
    <el-form ref="form" :model="form" :rules="rules" label-width="82px">
      <el-row :gutter="15">
        <el-col v-bind="styleResponsive ? { sm: 12 } : { span: 12 }">
          <el-form-item label="所属机构:" prop="groupId">
            <org-select :data="institutionList" placeholder="请选择所属机构" v-model="form.groupId"
                        @checkedKeys="checkedKeys"/>
          </el-form-item>

          <el-form-item label="负责部门:">
            <el-cascader class="ele-block" :options="organizationList" placeholder="请选择负责部门"
                         :props="defaultProps"
                         ref="deptRef"
                         :show-all-levels="false"
                         @change="handleChange"
                         collapse-tags v-model="form.deptIds" clearable></el-cascader>

          </el-form-item>

          <el-form-item label="所属工厂:">
            <el-select style="width: 100%" clearable v-model="form.factoryId" multiple  filterable placeholder="请选择所属工厂">
              <el-option
                v-for="item in factoryList"
                :label="item.name"
                :value="item.id"
                :key="item.id"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="性别:" prop="sex">
            <el-select clearable class="ele-block" v-model="form.sex" placeholder="请选择性别">
              <el-option label="男" :value="1"/>
              <el-option label="女" :value="2"/>
            </el-select>
          </el-form-item>
          <el-form-item label="员工状态:" prop="status">
            <el-select clearable class="ele-block" v-model="form.status" placeholder="请选择员工状态">
              <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="岗位:" prop="postName">
            <el-input clearable :maxlength="100" v-model="form.postName" placeholder="请输入岗位"/>
          </el-form-item>

          <el-form-item label="工种:" prop="workTypeId">
            <DictSelection dictName="工种" clearable filterable v-model="form.workTypeId">
            </DictSelection>
          </el-form-item>

          <el-form-item label="籍贯:" prop="city">
            <regions-select style="width: 100%" v-model="city" placeholder="请选择省市区"/>
          </el-form-item>
          <el-form-item label="生日:" prop="age">
            <el-date-picker style="width: 100%" clearable v-model="form.birthday" type="date" value-format="yyyy-MM-dd"
                            placeholder="请选择日期">
            </el-date-picker>
          </el-form-item>

        </el-col>
        <el-col v-bind="styleResponsive ? { sm: 12 } : { span: 12 }">
          <el-form-item label="工号:" prop="jobNumber">
            <el-input clearable type="text" :maxlength="10" v-model="form.jobNumber" placeholder="请输入工号"
                      onkeyup="value=value.replace(/[^\x00-\xff]/g, '')"/>
          </el-form-item>
          <el-form-item label="姓名:" prop="name">
            <el-input clearable :maxlength="20" v-model="form.name" placeholder="请输入姓名"/>
          </el-form-item>
          <el-form-item label="用户账号:">
            <el-input :disabled="true" :maxlength="11" v-model="form.loginName" v-if="isUpdate && data.accountId"/>
            <el-select clearable class="ele-block" v-model="form.accountId" filterable placeholder="请选择用户账号"
                       v-else>
              <el-option v-for="item in accountList" :key="item.id" :label="item.loginName" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="手机号:" prop="phone">
            <el-input clearable :maxlength="11" v-model="form.phone" placeholder="请输入手机号"/>
          </el-form-item>
          <el-form-item label="邮箱:" prop="email">
            <el-input clearable :maxlength="100" v-model="form.email" placeholder="请输入邮箱"/>
          </el-form-item>
          <el-form-item label="年龄:" prop="age">
            <el-input type="number" clearable :maxlength="100" v-model="form.age" placeholder="请输入年龄"
                      onkeyup="value=value.replace(/[^\d.]/g,'')"/>
          </el-form-item>


          <el-form-item label="入职时间:" prop="joinDate">
            <el-date-picker style="width: 100%" clearable v-model="form.joinDate" type="date" value-format="yyyy-MM-dd"
                            placeholder="请选择日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="毕业院校:" prop="school">
            <el-input clearable :maxlength="100" v-model="form.school" placeholder="请输入毕业院校"/>
          </el-form-item>
          <el-form-item label="微信号:" prop="wxId">
            <el-input clearable :maxlength="100" v-model="form.wxId" placeholder="请输入微信号"/>
          </el-form-item>
   

        </el-col>
      </el-row>
    </el-form>
    <template v-slot:footer>
      <el-button @click="updateVisible(false)">取消</el-button>
      <el-button type="primary" :loading="loading" @click="save">
        保存
      </el-button>
    </template>


  </ele-modal>
</template>

<script>
import {emailReg, phoneReg} from 'ele-admin';
import OrgSelect from './org-select.vue';
import RoleSelect from '@/views/system/user/components/role-select.vue';
import RegionsSelect from '@/components/RegionsSelect/index.vue';
import {getNotBoundAccount} from '@/api/system/user';
import {
  getUserDetail,
  saveOrUpdateUser,
  checkExistence
} from '@/api/system/organization';
import {getFactoryarea} from "@/api/factoryModel";

export default {
  components: {OrgSelect, RoleSelect, RegionsSelect},
  props: {
    // 弹窗是否打开
    visible: Boolean,
    // 修改回显的数据
    data: Object,
    // 全部机构
    organizationList: Array,
    //
    institutionList: Array,
    // 机构id
    organizationId: [Number, String]
  },
  data() {
    const defaultForm = {
      id: null,
      deptIds: [],
      deptName: '',

      groupId: null,
      groupName: null,
      name: '',
      sex: null,
      email: '',
      phone: '',
      age: '',
      accountId: '',
      factoryId: [],
      workTypeId: ''
    };
    return {
      defaultForm,
      // 表单数据
      form: {...defaultForm},
      // 表单验证规则
      rules: {
        groupId: [{required: true, message: '请选择所属机构', trigger: 'blur'}],
        name: [{required: true, message: '请输入姓名', trigger: 'blur'}],
        sex: [{required: true, message: '请选择性别', trigger: 'blur'}],

        email: [
          {pattern: emailReg, message: '邮箱格式不正确', trigger: 'blur'}
        ],
        phone: [
          {required: true, message: '请输入手机号', trigger: 'blur'},
          {pattern: phoneReg, message: '手机号格式不正确', trigger: 'blur'}
        ],
        jobNumber: [
          {
            required: true,
            trigger: 'blur',
            validator: (_rule, value, callback) => {
              if (!value) {
                return callback(new Error('请输入工号'));
              }
              checkExistence(this.form.jobNumber)
                .then((res) => {
                  if (res != true && res != this.form.id) {
                    callback(new Error('工号已经存在'));
                  } else {
                    callback();
                  }
                })
                .catch(() => {
                  callback();
                });
            }
          }
        ],
        status: [{required: true, message: '请选择员工状态', trigger: 'blur'}]
      },
      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false,
      city: '',
      factoryList: [],
      statusOptions: [
        {value: 1, label: '全职'},
        {value: 2, label: '兼职'},
        {value: 3, label: '实习'},
        {value: 4, label: '正式'},
        {value: 5, label: '试用'},
        {value: 6, label: '离职'}
      ],
      accountList: [],

      deptTree: [],
      defaultProps: {
        multiple: true,
        checkStrictly: true,
        emitPath: false,
        children: 'children',
        value: 'id',
        label: 'name'
      }
    };
  },
  computed: {
    // 是否开启响应式布局
    styleResponsive() {
      return this.$store.state.theme.styleResponsive;
    }
  },
  created() {
    this.getFactoryList()
    console.log(this.institutionList, '========');
  },
  methods: {
    getAccountList() {
      getNotBoundAccount().then((res) => {
        this.accountList = res;
      });
    },
    async getFactoryList() {
      const {list} = await getFactoryarea({
        pageNum: 1,
        size: 999,
        type: 1
      });
      this.factoryList = list || []
    },
    /* 保存编辑 */
    save() {
      this.$refs.form.validate((valid) => {
        if (!valid) {
          return false;
        }
        this.loading = true;
        this.form.addressId = this.city ? this.city[this.city.length - 1] : '';

        // if (this.deptTree.length > 0) {
        //   this.deptTree.forEach(i => {
        //     this.form.deptIds.push(i[i.length - 1])
        //   })
        //
        //   this.form['deptTree'] = JSON.stringify(this.deptTree)
        // }


        const data = {
          ...this.form
        };
        if (!this.isUpdate) {
          delete data.id;
        }
        saveOrUpdateUser(data)
          .then((msg) => {
            this.loading = false;
            if (this.isUpdate) {
              this.$message.success('人员信息编辑成功');
            } else {
              this.$message.success('人员新增成功');
            }
            this.updateVisible(false);
            this.$emit('done');
          })
          .catch((e) => {
            this.loading = false;
            // this.$message.error(e.message);
          });
      });
    },
    /* 更新visible */
    updateVisible(value) {
      this.$emit('update:visible', value);
    },
    handleChange() {
      let arr = Array.from(this.$refs.deptRef.getCheckedNodes())
      this.form.deptName = arr.map(i => i.label).join('/') || ''
      this.form.deptIds = this.form.deptIds || []
    },
    checkedKeys(value) {
      this.getLabelName(this.institutionList, i => {
        if (i.id == this.form.groupId) {
          return this.form.groupName = i.name
        }
      })
    },
    getLabelName(data, callback) {
      data.some((i) => {
        callback(i)
        if (i.children) {
          this.getLabelName(i.children, callback)
        }
      })
    }

  },
  watch: {
    visible(visible) {
      if (visible) {
        this.getAccountList();
        if (this.data) {
          getUserDetail(this.data.id).then((res) => {
            this.form = {...res};

            // this.deptTree = []
            // this.form.deptIds = []
            // if (this.form.deptTree) {
            //   this.deptTree = JSON.parse(this.form.deptTree)
            // }


            this.city = res.addressId ? res.addressId.toString() : null;
            this.isUpdate = true;
          });
          // this.$util.assignObject(this.form, {
          //   ...this.data,
          //   password: ''
          // });
          // this.form = {...this.data}
          // this.form.address = ["130000","130300","130304"]
          // this.form.address = "130304"
          // console.log('this.form',this.form)
        } else {
          this.city = null;
          this.form.groupId = this.organizationId;
          this.isUpdate = false;
        }
      } else {
        this.city = null;
        this.$refs.form.clearValidate();
        this.form = {...this.defaultForm};
      }
    }
  }
};
</script>
