<!-- 编辑弹窗 -->
<template>
  <ele-modal
    :width="600"
    :visible="visible"
    :maskClosable="false"
    :title="isUpdate ? '编辑场馆账号' : '添加场馆账号'"
    :body-style="{ paddingBottom: '28px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="styleResponsive ? { md: 4, sm: 5, xs: 24 } : { flex: '90px' }"
      :wrapper-col="
        styleResponsive ? { md: 19, sm: 19, xs: 24 } : { flex: '1' }
      "
    >
      <a-form-item label="账号" name="username">
        <a-input
          allow-clear
          placeholder="请输入登录账号"
          :disabled="isUpdate"
          v-model:value="form.username"
        />
      </a-form-item>
      <a-form-item label="手机号码" name="phone">
        <a-input
          allow-clear
          placeholder="请输入手机号码"
          maxlength="11"
          :disabled="isUpdate && !isSuperAdmin"
          v-model:value="form.phone"
        />
      </a-form-item>
      <a-form-item label="密码" name="password" v-if="!isUpdate">
        <a-input
          allow-clear
          placeholder="请输入登录密码"
          :disabled="isUpdate"
          v-model:value="form.password"
        />
      </a-form-item>
      <a-form-item label="真实姓名" name="realName">
        <a-input
          allow-clear
          placeholder="请输入真实姓名"
          v-model:value="form.realName"
        />
      </a-form-item>
      <a-form-item label="选择角色" name="roles">
        <role-select v-model:value="form.roles" />
      </a-form-item>
      <a-form-item label="可管理场馆" name="merchantId">
        <MerchantSelect v-model:value="merchants" />
      </a-form-item>
    </a-form>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch, computed } from 'vue';
  import { Form, message } from 'ant-design-vue';
  import { assignObject } from 'ele-admin-pro';
  import { addUser, updateUser } from '@/api/system/user';
  import { User } from '@/api/system/user/model';
  import { useThemeStore } from '@/store/modules/theme';
  import { storeToRefs } from 'pinia';
  import { ItemType } from 'ele-admin-pro/es/ele-image-upload/types';
  import { FormInstance, RuleObject } from 'ant-design-vue/es/form';
  import RoleSelect from './role-select.vue';
  import MerchantSelect from './merchant-select.vue';
  import { getMerchantId } from '@/utils/common';
  import { getMerchantName } from '@/utils/merchant';
  import { useUserStore } from '@/store/modules/user';
  import { Merchant } from '@/api/shop/merchant/model';
  import { listMerchant } from '@/api/shop/merchant';

  const userStore = useUserStore();

  // 是否是修改
  const isUpdate = ref(false);
  const useForm = Form.useForm;
  // 是否开启响应式布局
  const themeStore = useThemeStore();
  const { styleResponsive } = storeToRefs(themeStore);
  // 当前用户信息
  const loginUser = computed(() => userStore.info ?? {});

  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    data?: User | null;
  }>();

  const emit = defineEmits<{
    (e: 'done'): void;
    (e: 'update:visible', visible: boolean): void;
  }>();

  // 提交状态
  const loading = ref(false);
  // 是否显示最大化切换按钮
  // const maxable = ref(true);
  // 表格选中数据
  const formRef = ref<FormInstance | null>(null);
  const images = ref<ItemType[]>([]);
  const isSuperAdmin = ref<boolean>(false);
  const merchants = ref<Merchant[]>([]);

  // 用户信息
  const form = reactive<User>({
    type: undefined,
    userId: undefined,
    username: '',
    nickname: '',
    realName: '',
    companyName: '',
    merchants: '',
    merchantId: getMerchantId(),
    merchantName: getMerchantName(),
    sex: undefined,
    roles: [],
    roleId: undefined,
    roleName: undefined,
    email: '',
    phone: '',
    mobile: '',
    password: '',
    introduction: '',
    organizationId: undefined,
    birthday: '',
    idCard: '',
    comments: '',
    gradeName: '',
    isAdmin: true,
    gradeId: undefined
  });

  /* 更新visible */
  const updateVisible = (value: boolean) => {
    emit('update:visible', value);
  };

  // 表单验证规则
  const rules = reactive({
    merchantAccountName: [
      {
        required: true,
        type: 'string',
        message: '请填写场馆账号名称',
        trigger: 'blur'
      }
    ],
    // merchantId: [
    //   {
    //     required: true,
    //     type: 'string',
    //     message: '请选择场馆',
    //     trigger: 'blur'
    //   }
    // ],
    roles: [
      {
        required: true,
        type: 'string',
        message: '请选择角色',
        trigger: 'blur',
        validator: async (_rule: RuleObject) => {
          if (form.roles?.length == 0) {
            return Promise.reject('请选择角色');
          }
          return Promise.resolve();
        }
      }
    ],
    username: [
      {
        required: true,
        type: 'string',
        message: '请填写登录账号',
        trigger: 'blur'
      }
    ],
    phone: [
      {
        required: true,
        type: 'string',
        message: '请填写手机号码',
        trigger: 'blur'
      }
    ],
    password: [
      {
        required: true,
        type: 'string',
        message: '请输入登录密码',
        trigger: 'blur'
      }
    ],
    realName: [
      {
        required: true,
        type: 'string',
        message: '请填写真实姓名',
        trigger: 'blur'
      }
    ]
  });

  /* 搜索 */
  const chooseMerchantId = (item) => {
    form.merchantId = item.merchantId;
    form.merchantName = item.merchantName;
  };

  const { resetFields } = useForm(form, rules);

  /* 保存编辑 */
  const save = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        const formData = {
          ...form,
          merchants: merchants.value?.map((d) => d.merchantId).join(',')
        };
        if (getMerchantId()) {
          form.merchantId = getMerchantId();
          form.merchantName = getMerchantName();
        }
        const saveOrUpdate = isUpdate.value ? updateUser : addUser;
        saveOrUpdate(formData)
          .then((msg) => {
            loading.value = false;
            message.success(msg);
            updateVisible(false);
            emit('done');
          })
          .catch((e) => {
            loading.value = false;
            message.error(e.message);
          });
      })
      .catch(() => {});
  };

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        images.value = [];
        merchants.value = [];
        if (props.data) {
          assignObject(form, props.data);
          if (props.data.merchants) {
            listMerchant({ merchantIds: props.data.merchants }).then((list) => {
              merchants.value = list;
            });
          }
          // if (props.data.comments) {
          //   listMerchant({ merchantCodes: props.data.comments }).then(
          //     (list) => {
          //       merchants.value = list;
          //     }
          //   );
          // }
          isUpdate.value = true;
        } else {
          resetFields();
          isUpdate.value = false;
        }
        const superAdmin = loginUser.value.roles?.filter(
          (d) => d.roleCode == 'superAdmin'
        );
        // 是否超级管理员
        if (superAdmin && superAdmin.length > 0) {
          isSuperAdmin.value = true;
        }
      } else {
        resetFields();
      }
    },
    { immediate: true }
  );
</script>
