<!-- 编辑弹窗 -->
<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="merchantId">
        <SelectMerchant
          :placeholder="`选择商户`"
          class="input-item"
          v-model:value="form.merchantName"
          @done="chooseMerchantId"
        />
      </a-form-item>
      <a-form-item label="选择角色" name="roleId">
        <SelectRole
          :placeholder="`选择角色`"
          class="input-item"
          :type="`merchant`"
          v-model:value="form.roleName"
          @done="chooseRoleId"
        />
      </a-form-item>
      <a-form-item label="账号" name="phone">
        <a-input
          allow-clear
          placeholder="请输入手机号码"
          maxlength="11"
          :disabled="isUpdate"
          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="comments">
        <a-textarea
          :rows="4"
          :maxlength="200"
          placeholder="请输入描述"
          v-model:value="form.comments"
        />
      </a-form-item>
    </a-form>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { Form, message } from 'ant-design-vue';
  import { assignObject, uuid } from 'ele-admin-pro';
  import { addMerchantAccount, updateMerchantAccount } from '@/api/shop/merchantAccount';
  import { MerchantAccount } from '@/api/shop/merchantAccount/model';
  import { useThemeStore } from '@/store/modules/theme';
  import { storeToRefs } from 'pinia';
  import { ItemType } from 'ele-admin-pro/es/ele-image-upload/types';
  import { FormInstance } from 'ant-design-vue/es/form';
  import { FileRecord } from '@/api/system/file/model';
  import {DictData} from "@/api/system/dict-data/model";
  import {Merchant} from "@/api/shop/merchant/model";
  import {Role} from "@/api/system/role/model";

  // 是否是修改
  const isUpdate = ref(false);
  const useForm = Form.useForm;
  // 是否开启响应式布局
  const themeStore = useThemeStore();
  const { styleResponsive } = storeToRefs(themeStore);

  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    data?: MerchantAccount | 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 form = reactive<MerchantAccount>({
    id: undefined,
    phone: undefined,
    realName: undefined,
    merchantId: undefined,
    merchantName: '',
    userId: undefined,
    roleId: undefined,
    roleName: '',
    comments: undefined,
    status: undefined,
    sortNumber: undefined,
    tenantId: undefined,
    createTime: 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: 'number',
        message: '请选择商户',
        trigger: 'blur'
      }
    ],
    roleId: [
      {
        required: true,
        type: 'number',
        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: Merchant) => {
    form.merchantName = item.merchantName;
    form.merchantId = item.merchantId;
  };

  const chooseRoleId = (item: Role) => {
    form.roleId = item.roleId;
    form.roleName = item.roleName;
  }

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

  /* 保存编辑 */
  const save = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        const formData = {
          ...form
        };
        const saveOrUpdate = isUpdate.value ? updateMerchantAccount : addMerchantAccount;
        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 = [];
        if (props.data) {
          assignObject(form, props.data);
          isUpdate.value = true;
        } else {
          resetFields();
          isUpdate.value = false;
        }
      } else {
        resetFields();
      }
    },
    { immediate: true }
  );
</script>
