<!-- 用户编辑弹窗 -->
<template>
  <ele-modal
    width="820px"
    :visible="visible"
    :append-to-body="true"
    :close-on-click-modal="false"
    custom-class="ele-dialog-form"
    :title="isUpdate ? '修改用户' : '新建用户'"
    @update:visible="updateVisible"
    :maxable="true"
  >
    <el-form
      ref="form"
      :autoComplete="false"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="用户账号:" prop="loginName">
            <el-input
              clearable
              :maxlength="20"
              :disabled="isUpdate"
              v-model="form.loginName"
              placeholder="请输入用户账号"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="员工姓名:" prop="name">
            <el-input
              :maxlength="20"
              v-model="form.name"
              @click.native="setUsers"
              placeholder="选择人员"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item v-if="!isUpdate" label="登录密码:" prop="loginPwd">
            <el-input
              show-password
              :maxlength="20"
              v-model="form.loginPwd"
              placeholder="请输入登录密码"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="岗位:" prop="postName">
            <el-input
              placeholder=" "
              v-model="userInfo.postName"
              :disabled="true"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="启用状态:" prop="enable">
            <el-switch
              v-model="form.enable"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value="1"
              :inactive-value="0"
            >
            </el-switch>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-table
            :data="form.groupRolePOList"
            style="width: 100%"
            :border="true"
          >
            <el-table-column
              prop="groupName"
              label="组织机构"
              align="center"
              width="320"
            >
              <template slot-scope="scope">
                <el-cascader
                  class="ele-block organizationList"
                  :options="organizationList"
                  placeholder=" "
                  :props="defaultProps"
                  ref="deptRef"
                  :show-all-levels="true"
                  :disabled="true"
                  v-model="scope.row.groupId"
                ></el-cascader>
              </template>
            </el-table-column>
            <el-table-column prop="roleIds" label="角色" align="center">
              <template slot-scope="scope">
                <role-select v-model="scope.row.roleIds" />
              </template>
            </el-table-column>
          </el-table>
          <!-- <el-row>
            <el-col :span="12">
              <el-form-item label="部门:" prop="deptName">
                <el-input v-model="form.deptName" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="角色:" prop="roleId">
                <role-select v-model="form.roleId" />
              </el-form-item>
            </el-col>
          </el-row> -->
        </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>
    <add ref="addREf" @success="userBk"></add>
  </ele-modal>
</template>

<script>
  // import { emailReg, phoneReg } from 'ele-admin';
  import RoleSelect from './role-select.vue';
  import add from './add.vue';
  import { addUsers, putUsers, getById } from '@/api/system/user';
  import { getUserDetail } from '@/api/system/organization';
  export default {
    components: { RoleSelect, add },
    props: {
      // 弹窗是否打开
      visible: Boolean,
      // isUpdate: Boolean,
      // 修改回显的数据
      data: Object,
      organizationList: {
        type: Array,
        default: () => {
          return [];
        }
      }
    },
    data() {
      const defaultForm = {
        id: null,
        loginName: '',
        mainUserId: '',
        name: '',
        loginPwd: 123456,
        enable: 1,
        groupRolePOList: [],
        jobNumber: '',
        phone: ''
      };
      return {
        defaultForm,
        defaultProps: {
          multiple: true,
          checkStrictly: true,
          emitPath: false,
          children: 'children',
          value: 'id',
          label: 'name'
        },
        // 表单数据
        form: { ...defaultForm },
        // 表单验证规则
        rules: {
          loginName: [
            { required: true, message: '请输入用户账号', trigger: 'blur' }
          ],
          name: [{ required: true, message: '请选择员工', trigger: 'change' }],
          loginPwd: [
            {
              required: true,
              pattern: /^[\S]{5,18}$/,
              message: '密码必须为5-18位非空白字符',
              trigger: 'blur'
            }
          ]
        },
        // 提交状态
        loading: false,
        // 是否是修改
        isUpdate: false,
        userInfo: {
          postName: ''
        }
      };
    },
    computed: {
      // 是否开启响应式布局
      styleResponsive() {
        return this.$store.state.theme.styleResponsive;
      }
    },
    methods: {
      setUsers() {
        this.$refs.addREf.open('0');
      },
      async getUserDetail() {
        if (!this.form.mainUserId) {
          return;
        }
        this.userInfo = await getUserDetail(this.form.mainUserId);
      },
      userBk(data) {
        if (data) {
          this.form.name = data.name;
          this.form.mainUserId = data.id;
          this.getUserDetail();
          this.form.jobNumber = data.jobNumber;
          this.form.phone = data.phone;
          this.form.groupRolePOList = [];
          if (!data.deptIds.includes(data.groupId)) {
            this.form.groupRolePOList.push({
              groupName: data.groupName,
              groupId: data.groupId,
              roleIds: []
            });
          }

          if (data.deptIds.length > 0) {
            const deptNames = data.deptName.split('/');
            data.deptIds.forEach((item, index) => {
              this.form.groupRolePOList.push({
                groupName: deptNames[index],
                groupId: item,
                roleIds: []
              });
            });
          }
          this.$forceUpdate();
        }
      },
      /* 保存编辑 */
      save() {
        console.log(this.form.groupRolePOList,'this.form.groupRolePOList')
        this.$refs.form.validate((valid) => {
          let isRole = true;
          if (!valid) {
            return false;
          }
          this.form.groupRolePOList.forEach((item) => {
            if (item.roleIds.length == 0) {
              isRole = false;
            }
          });
          if (!isRole) {
            this.$message.warning('请选择角色！');
            return;
          }
          this.loading = true;
          if (!this.isUpdate) {
            delete this.form.id;
          }

          const data = {
            ...this.form
            // roleId: this.form.roleIds.map((d) => {
            //   return { roleId: d };
            // })
          };
          const saveOrUpdate = this.isUpdate ? putUsers : addUsers;
          saveOrUpdate(data)
            .then((msg) => {
              this.loading = false;
              this.$message.success(msg);
              this.updateVisible(false);
              this.$emit('done');
            })
            .catch((e) => {
              this.loading = false;
              // this.$message.error(e.message);
            });
        });
      },
      /* 更新visible */
      updateVisible(value) {
        this.$emit('update:visible', value);
      },
      getByData(userRow, currentRow) {
        // alert(1)
        let id = this.data?.id || userRow?.id;
        getById(id).then((res) => {
          this.form = res.data;
          // this.form.mainUserId = id;
          this.getUserDetail();
          this.form.groupRolePOList = [];
          res.data.groupRoleList.forEach((item) => {
            this.form.groupRolePOList.push({
              groupName: item.groupName,
              groupId: item.groupId,
              roleIds: item.roleVOList.map((ids) => ids.id)
            });
          });
          if (currentRow) {
            this.isUpdate = true;
            this.userBk(currentRow);
          }
        });
      }
    },
    watch: {
      visible(visible) {
        if (visible) {
          if (this.data) {
            this.getByData(this.data);
            // this.isUpdate = true;
          } else {
            // this.isUpdate = false;
          }
        } else {
          this.$refs.form.clearValidate();
          this.form = { ...this.defaultForm };
          this.isUpdate = false;
        }
      }
      // isUpdate(v){
      //   console.log(v,66666);
      //   this.isUpdate = v;
      // }
    }
  };
</script>
<style lang="scss" scoped>
  :deep(.el-input--medium .el-input__inner) {
    height: auto !important;
  }
  :deep(.el-table) {
    .el-form-item {
      margin-bottom: 0;
    }
  }
  :deep(.organizationList .el-input__inner) {
    border: 0;
    background: none;
  }
  :deep(.organizationList .el-input__suffix) {
    display: none;
  }
  :deep(.organizationList .el-tag) {
    background: none;
  }
</style>
