<template>
  <a-button
    v-permission="['system:user:create']"
    v-if="props.isCreate"
    type="primary"
    @click="handleClick"
  >
    <template #icon><icon-plus /></template>
    新建
  </a-button>
  <a-button
    v-permission="['system:user:update']"
    v-if="!props.isCreate"
    type="outline"
    size="small"
    :style="{ marginRight: '10px', padding: '7px' }"
    @click="handleClick"
  >
    <template #icon><icon-edit /></template>
    修改
  </a-button>

  <a-modal
    width="700px"
    :visible="visible"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <template #title>{{ modalTitle }}</template>
    <a-form ref="CreateRef" :model="formData" :style="{ width: '650px' }">
      <a-form-item
        field="username"
        label="用户名"
        :validate-trigger="['change', 'input']"
        :rules="[
          { required: true, message: '用户名不能为空' },
          {
            match: /^[a-zA-Z0-9\u4e00-\u9fa5]{1,20}$/,
            message: '请输入正确格式的用户名',
          },
        ]"
      >
        <a-input
          v-if="props.isCreate"
          v-model="formData.username"
          placeholder="请输入用户名"
        />

        <div v-else>{{ formData.username }}</div>
      </a-form-item>
      <a-form-item
        field="email"
        label="Email"
        :rules="[
          {
            required: true,
            type: 'email',
            message: 'Email不能为空',
          },
        ]"
        :validate-trigger="['change', 'input']"
      >
        <a-input v-model="formData.email" placeholder="请输入Email" />
      </a-form-item>
      <a-form-item
        field="phone"
        label="电话"
        :rules="[
          { required: true, message: '电话不能为空' },
          { match: /^1[3-9]\d{9}$/, message: '请输入正确格式的电话' },
        ]"
        :validate-trigger="['change', 'input']"
      >
        <a-input v-model="formData.phone" placeholder="请输入电话" />
      </a-form-item>
      <a-form-item
        field="password"
        label="密码"
        v-if="isCreate"
        :validate-trigger="['change', 'input']"
        :rules="[{ required: true, message: '密码不能为空' }]"
      >
        <a-input v-model="formData.password" placeholder="请输入密码" />
      </a-form-item>
      <a-form-item field="nickName" label="昵称">
        <a-input v-model="formData.nickName" placeholder="请输入昵称" />
      </a-form-item>

      <a-form-item field="address" label="地址">
        <a-input v-model="formData.address" placeholder="请输入地址" />
      </a-form-item>
      <a-form-item
        field="deptId"
        label="部门"
        :rules="[{ required: true, message: '部门不能为空' }]"
        :validate-trigger="['change']"
      >
        <a-tree-select
          v-model="formData.deptId"
          :field-names="{
            key: 'id',
            title: 'name',
            children: 'children',
          }"
          :data="deptOptions"
          allow-clear
          placeholder="请选择所属部门"
        />
      </a-form-item>

      <a-form-item
        field="roleIds"
        label="角色"
        :rules="[{ required: true, message: '角色不能为空' }]"
        :validate-trigger="['change']"
      >
        <a-select
          v-model="formData.roleIds"
          :options="roleOptions"
          :field-names="{
            value: 'id',
            label: 'name',
          }"
          placeholder="请选择角色"
          multiple
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
  import useVisible from '@/hooks/visible';
  import { computed, PropType, ref } from 'vue';
  import { CreateRecord } from '@/api/user';
  import { FormInstance } from '@arco-design/web-vue/es/form';
  import { queryRoleList } from '@/api/role';
  import { getAllDeptTree } from '@/api/dept';
  import { Message } from '@arco-design/web-vue';
  import { useUserStore } from '@/store';

  const props = defineProps({
    prem: {
      type: Object as PropType<CreateRecord>,
    },
    isCreate: Boolean,
  });
  const emit = defineEmits(['refresh']);
  const modalTitle = computed(() => {
    return props.isCreate ? '新建用户' : '编辑用户';
  });
  const { visible, setVisible } = useVisible(false);
  const checkKeys = ref<number[]>([]);

  const CreateRef = ref<FormInstance>();

  const formData = ref<CreateRecord>({
    value: undefined,
    code: undefined,
    username: '',
    nickName: '',
    password: '',
    phone: '',
    email: '',
    enabled: '',
    address: '',
    deptId: undefined,
    roleIds: [],
    permissionIds: [],
    authorities: [],
  });

  let formDifer = {};
  const userStore = useUserStore();

  // 部门数据
  const deptOptions = ref();
  const getDeptData = async () => {
    const res = await getAllDeptTree(0);
    deptOptions.value = res.data;
  };
  // 角色数据
  const roleOptions = ref();
  const getRoleData = async () => {
    const res = await queryRoleList('');
    roleOptions.value = res.data.records.filter((item: any) => {
      return item.enabled !== false;
    });
  };

  // 组件被点击
  const handleClick = () => {
    getDeptData();
    getRoleData();
    const userId = props.prem?.id;
    // 编辑
    if (!props.isCreate && userId) {
      formData.value = props.prem;
      formDifer = { ...props.prem };
    }
    setVisible(true);
  };

  // 做出只修改的部分
  const diffDataForm = (newData: any, oldData: any) => {
    const result = {}; // 报错修改的字段内容
    Object.keys(oldData).forEach((key) => {
      if (oldData[key] !== newData[key]) {
        result[key] = newData[key];
      }
    });
    return result;
  };

  // 提交
  const handleSubmit = async () => {
    const valid = await CreateRef.value?.validate();
    if (!valid) {
      formData.value.permissionIds = checkKeys.value;
      // 新增
      if (props.isCreate) {
        // formData.value.username = formData.value.email;
        const res = await userStore.createUser(formData.value);
        if (res.status === 200) {
          Message.success({
            content: '新建成功',
            duration: 5 * 1000,
          });
        }
        CreateRef.value?.resetFields();
      } else {
        // 编辑
        // formDifer = diffDataForm(formData.value, formDifer);
        // if (Object.keys(formDifer).length === 0) {
        //   Message.success({
        //     content: '未编辑',
        //     duration: 3 * 1000,
        //   });
        // } else {
        //   formDifer.id = formData.value.id;
        //   const res = await userStore.updateUser(formData.value);
        //   if (res.status === 200) {
        //     Message.success({
        //       content: '修改成功',
        //       duration: 5 * 1000,
        //     });
        //   }
        // }
        const res = await userStore.updateUser(formData.value);
        if (res.status === 200) {
          Message.success({
            content: '修改成功',
            duration: 5 * 1000,
          });
        }
      }
      checkKeys.value = [];
      emit('refresh');
      setVisible(false);
    }
  };

  // 关闭
  const handleCancel = async () => {
    checkKeys.value = [];
    setVisible(false);
  };
</script>

<style scoped></style>
