<!-- 编辑弹窗 -->
<template>
  <ele-modal
    :width="800"
    :visible="visible"
    :maskClosable="false"
    :maxable="maxable"
    :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="specName">
        <a-input
          allow-clear
          placeholder="请输入规格名称"
          v-model:value="form.specName"
        />
      </a-form-item>
      <a-form-item name="specValue">
        <a-space direction="vertical" class="ml-[124px]">
          <template v-for="(item, index) in spec" :key="index">
            <div class="text-left flex items-center leading-10 text-gray-400">
              <div class="mr-2">{{ item.value }} :</div>
              <CloseCircleOutlined
                class="cursor-pointer"
                @click="onClose(index)"
              />
            </div>
            <ele-edit-tag
              v-model:data="item.detail"
              size="middle"
              shape="round"
            />
          </template>
          <a-card class="ml-[124px]" v-if="showSpecForm">
            <a-form-item name="name">
              <a-input
                allow-clear
                placeholder="请输入规格"
                v-model:value="name"
              />
            </a-form-item>
            <a-form-item name="value">
              <a-input
                allow-clear
                placeholder="请输入规格值"
                v-model:value="value"
              />
            </a-form-item>
            <a-space>
              <a-button type="primary" @click="addSpecValue">确定</a-button>
              <a-button @click="openSpecForm">取消</a-button>
            </a-space>
          </a-card>
          <a-button type="primary" class="mt-5" v-else @click="openSpecForm"
            >添加新规格</a-button
          >
        </a-space>
      </a-form-item>
    </a-form>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { CloseCircleOutlined } from '@ant-design/icons-vue';
  import { ref, reactive, watch } from 'vue';
  import { Form, message } from 'ant-design-vue';
  import { assignObject } from 'ele-admin-pro';
  import { addSpec, updateSpec } from '@/api/shop/spec';
  import { Spec } from '@/api/shop/spec/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 { SpecValue } from '@/api/shop/specValue/model';

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

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

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

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

  // 用户信息
  const form = reactive<Spec>({
    specId: undefined,
    specName: undefined,
    specValue: undefined,
    status: 0,
    comments: '',
    sortNumber: 100
  });

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

  // 表单验证规则
  const rules = reactive({
    specName: [
      {
        required: true,
        type: 'string',
        message: '请填写规格名称',
        trigger: 'blur'
      }
    ]
  });

  // const validator = (value: string) => {
  //   return new Promise<void>((_resolve, reject) => {
  //     setTimeout(() => {
  //       reject(new Error(value + '不合法, 请重新输入'));
  //     }, 1000);
  //   });
  // };

  // 新增规格
  const addSpecValue = () => {
    if (!name.value || !value.value) {
      message.error(`请输入规格和规格值)`);
      return false;
    }
    const findIndex = spec.value.findIndex((d) => d.value == name.value);
    if (findIndex == 0) {
      message.error(`${name.value}已存在)`);
      return false;
    }
    spec.value.push({
      value: name.value,
      detail: [value.value]
    });
    name.value = '';
    value.value = '';
    openSpecForm();
  };

  const openSpecForm = () => {
    showSpecForm.value = !showSpecForm.value;
  };

  const onClose = (index) => {
    spec.value.splice(index, 1);
  };

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

  /* 保存编辑 */
  const save = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        if (spec.value.length === 0) {
          message.error('请添加规格');
          return;
        }
        const formData = {
          ...form,
          specValue: JSON.stringify(spec.value)
        };
        const saveOrUpdate = isUpdate.value ? updateSpec : addSpec;
        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);
          if (props.data.specValue) {
            spec.value = JSON.parse(props.data.specValue);
          }
          isUpdate.value = true;
        } else {
          spec.value = [];
          isUpdate.value = false;
        }
      } else {
        resetFields();
      }
    },
    { immediate: true }
  );
</script>
