<script setup>
import { useVbenModal } from '@vben/common-ui';
import { Form, Input, Select, Button, message } from "ant-design-vue";
import { ref, reactive, computed, watch } from 'vue';

const formProps = ['user_id', 'user_name', 'nick_name', 'password', 'confirm_password', 'phone', 'user_role', 'white_list_ip'];

const formRef = ref();

const addState = reactive({
  white_list_ip: '',
});

const editState = reactive({});
const editCache = {};

const rulesAdd = {
  user_name: [{ required: true, message: '请输入用户名', trigger: 'blur' }, { min: 3, max: 16, message: '用户名长度为3-16位', trigger: 'blur' }],
  nick_name: [{ required: true, message: '请输入昵称', trigger: 'blur' }, { min: 3, max: 16, message: '昵称长度为3-16位', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }, { min: 6, max: 16, message: '密码长度为6-16位', trigger: 'blur' }],
  confirm_password: [{ required: true, trigger: 'blur',
    validator: (rule, value) => {
      if (!value) {
        return Promise.reject(new Error('请确认密码'));
      }
      if (value !== addState.password) {
        return Promise.reject(new Error('两次密码不一致'));
      }
      return Promise.resolve();
    }
   }, { min: 6, max: 16, message: '密码长度为6-16位', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }, { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }],
  user_role: [{ required: true, message: '请选择角色', trigger: 'blur' }],
};

const rulesEdit = {
  nick_name: [{ min: 3, max: 16, message: '昵称长度为3-16位', trigger: 'blur' }],
  password: [{ min: 6, max: 16, message: '密码长度为6-16位', trigger: 'blur' }],
  confirm_password: [{
    trigger: 'blur',
    validator: (rule, value) => {
      if (value !== editState.password) {
        return Promise.reject(new Error('两次密码不一致'));
      }
      return Promise.resolve();
    }
  }, { min: 6, max: 16, message: '密码长度为6-16位', trigger: 'blur' }],
  phone: [{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }],
}

const rules = computed(() => {
  return editState.user_id ? rulesEdit : rulesAdd;
});

const formState = computed(() => {
  return isEdit.value ? editState : addState;
});

const isEdit = computed(() => {
  return !!editState.user_id;
});

const resetForm = () => {
  formRef.value.resetFields();
  Object.keys(editCache).forEach(key => {
    delete editCache[key];
  });
  delete editState.user_id;
};

const [Modal, modalApi] = useVbenModal({
  title: 'Account Info',
  onOpened() {
    const { formData } = modalApi.getData();
    if (formData) {
      Object.keys(formData).forEach(key => {
        if (formProps.includes(key)) {
          editState[key] = formData[key];
          editCache[key] = formData[key];
        }
      });
    }
    modalApi.setData({ formData: null });
  },
  onCancel() {
    modalApi.setData({ formData: null });
    modalApi.close();
  },
  onConfirm() {
    formRef.value.validate().then(() => {
      if (isEdit.value) {
        let needEdit = false;
        const editData = {};
        Object.keys(editState).forEach(key => {
          if (editState[key] !== editCache[key]) {
            editData[key] = editState[key];
            needEdit = true;
          }
        });
        if (needEdit) {
          editData.user_id = editState.user_id;
          delete editData.confirm_password;
          modalApi.setData({ formData: { ...editData } });
        }
      }
      else {
        const { confirm_password, ...formData } = addState;
        modalApi.setData({ formData: { ...formData } });
      }
      modalApi.close();
    })
    .catch(err => {
      console.log('请检查输入内容', err);
    });
  },
  onClosed() {
    resetForm();
  }
});

</script>
<template>
  <Modal>
    <Form ref="formRef" :model="formState" :label-col="{ span: 6 }" :wrapper-col="{ span: 12 }" :rules="rules">
      <Form.Item label="用户名" name="user_name">
        <Input v-model:value="formState.user_name" :disabled="isEdit" />
      </Form.Item>
      <Form.Item label="昵称" name="nick_name">
        <Input v-model:value="formState.nick_name" />
      </Form.Item>
      <Form.Item label="密码" name="password">
        <Input.Password v-model:value="formState.password" />
      </Form.Item>
      <Form.Item label="确认密码" name="confirm_password">
        <Input.Password v-model:value="formState.confirm_password" />
      </Form.Item>
      <Form.Item label="手机号" name="phone">
        <Input v-model:value="formState.phone" />
      </Form.Item>
      <Form.Item label="角色" name="user_role">
        <Select v-model:value="formState.user_role">
          <Select.Option :value="1">超级管理员</Select.Option>
          <Select.Option :value="100">业务管理员</Select.Option>
        </Select>
      </Form.Item>
      <Form.Item label="IP白名单" name="white_list_ip">
        <Input v-model:value="formState.white_list_ip" />
      </Form.Item>
    </Form>
  </Modal>
</template>