<template>
  <my-dialog
    :visible="visible"
    :header="`${isEdit ? '修改' : '新增'}用户`"
    :width="600"
    :closeOnOverlayClick="false"
    :callBacks="[run1, run2.bind(null, { pageNumber: 1, pageSize: 1000 })]"
    @close="emit('update:visible', false)"
  >
    <t-form ref="formRef" :data="formData" :rules="rules" labelAlign="top">
      <t-row :gutter="[20, 20]">
        <t-col :span="6">
          <t-form-item label="登录名" name="loginName">
            <t-input v-model="formData.loginName"></t-input>
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="姓名" name="realName">
            <t-input v-model="formData.realName"></t-input>
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="性别" name="gender">
            <t-radio-group v-model="formData.gender">
              <t-radio
                v-for="(val, key) in GENDER_TYPE"
                :value="key"
                :label="val"
                :key="val"
              ></t-radio>
            </t-radio-group>
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="手机" name="mobileNumber">
            <t-input v-model="formData.mobileNumber"></t-input>
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="所属机构" name="orgId">
            <t-tree-select
              v-model="formData.orgId"
              :data="treeData"
              :treeProps="treeProps"
            />
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="角色" name="roleIds">
            <t-select
              v-model="formData.roleIds"
              :options="roleList"
              :min-collapsed-num="10"
              multiple
            ></t-select>
          </t-form-item>
        </t-col>
      </t-row>
    </t-form>
    <template #foot>
      <t-button theme="default" @click="emit('update:visible', false)"
        >取消</t-button
      >
      <t-button theme="primary" @click="save">保存</t-button>
    </template>
  </my-dialog>
</template>
<script setup name="AddUserDialog">
import useClearDialog from '@/hooks/useClearDialog';
import { ref, computed } from 'vue';
import { getOrgStructList, getRoleList, addUser } from '@/api/user';
import { useRequest } from 'vue-request';
import { GENDER_TYPE } from '@/config/constants';

const props = defineProps({
  visible: Boolean,
  curRow: Object,
});
const emit = defineEmits(['close', 'success']);
const formRef = ref(null);
const getDetail = async () => {
  //编辑状态下获取回显数据的接口请求业务,如果curRow里的字段够用，就直接把curRow里的字段赋值给formData
  for (let key in formData) {
    if (key !== 'roleIds') {
      formData[key] = props.curRow[key];
    }
  }
  formData.roleIds = props.curRow.roles.map((item) => item.id);
};
const { formData, isEdit } = useClearDialog(
  {
    loginName: '',
    realName: '',
    gender: '',
    mobileNumber: '',
    orgId: '',
    roleIds: [],
  },
  props,
  formRef,
  getDetail
);
const { data: treeData, run: run1 } = useRequest(getOrgStructList);
const { data: roleData, run: run2 } = useRequest(getRoleList);
const roleList = computed(() => {
  return roleData.value?.records.map((item) => ({
    label: item.name,
    value: item.id,
  }));
});
const treeProps = {
  keys: {
    label: 'name',
    value: 'id',
    children: 'children',
  },
};
const rules = {
  loginName: [
    {
      required: true,
      message: '请填写登录名',
      type: 'error',
      trigger: 'blur',
    },
  ],
  realName: [
    {
      required: true,
      message: '请填写真实姓名',
      type: 'error',
      trigger: 'blur',
    },
  ],
  mobileNumber: [
    {
      required: true,
      message: '请填写手机号',
    },
  ],
  orgId: [
    {
      required: true,
      message: '请选择机构',
    },
  ],
  gender: [
    {
      required: true,
      message: '请选择性别',
    },
  ],
  roleIds: [
    {
      required: true,
      message: '请选择角色',
    },
    {
      validator: (val) => {
        if (!val?.length) {
          return {
            result: false,
            message: '请选择角色',
          };
        }
        return {
          result: true,
          type: 'success',
        };
      },
    },
  ],
};
const addHandler = () => {
  addUser({ ...formData, id: props.curRow?.id || undefined }).then(() => {
    emit('success');
  });
};
const save = () => {
  formRef.value.validate().then(async (result) => {
    if (result === true) {
      addHandler();
    }
  });
};
</script>
