<!-- 用户编辑弹窗 -->
<template>
  <ele-modal
    width="800px"
    :visible="visible"
    :close-on-click-modal="true"
    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="所属机构:">
            <org-select
              :data="organizationList"
              placeholder="请选择所属机构"
              v-model="form.groupId"
            />
          </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="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-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-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"
              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="postName">
            <el-input
              clearable
              :maxlength="100"
              v-model="form.postName"
              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';
  export default {
    components: { OrgSelect, RoleSelect, RegionsSelect },
    props: {
      // 弹窗是否打开
      visible: Boolean,
      // 修改回显的数据
      data: Object,
      // 全部机构
      organizationList: Array,
      // 机构id
      organizationId: [Number, String]
    },
    data() {
      const defaultForm = {
        id: null,
        groupId: null,
        name: '',
        sex: null,
        email: '',
        phone: '',
        age: '',
        accountId: ''
      };
      return {
        defaultForm,
        // 表单数据
        form: { ...defaultForm },
        // 表单验证规则
        rules: {
          name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
          sex: [{ required: true, message: '请选择性别', trigger: 'blur' }],
          email: [
            { pattern: emailReg, message: '邮箱格式不正确', trigger: 'blur' }
          ],
          phone: [
            { 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: '',
        statusOptions: [
          { value: 1, label: '全职' },
          { value: 2, label: '兼职' },
          { value: 3, label: '实习' },
          { value: 4, label: '正式' },
          { value: 5, label: '试用' },
          { value: 6, label: '离职' }
        ],
        accountList: []
      };
    },
    computed: {
      // 是否开启响应式布局
      styleResponsive() {
        return this.$store.state.theme.styleResponsive;
      }
    },
    methods: {
      getAccountList() {
        getNotBoundAccount().then((res) => {
          this.accountList = res;
        });
      },
      /* 保存编辑 */
      save() {
        this.$refs.form.validate((valid) => {
          if (!valid) {
            return false;
          }
          this.loading = true;
          this.form.addressId = this.city
            ? this.city[this.city.length - 1]
            : '';
          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);
      }
    },
    watch: {
      visible(visible) {
        if (visible) {
          this.getAccountList();
          if (this.data) {
            getUserDetail(this.data.id).then((res) => {
              this.form = { ...res };
              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>
