<!-- 分类编辑弹窗 -->
<template>
  <ele-modal
    :width="620"
    :visible="visible"
    :confirm-loading="loading"
    :title="isUpdate ? '修改分类' : '添加分类'"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="styleResponsive ? { md: 7, sm: 4, xs: 24 } : { flex: '90px' }"
      :wrapper-col="
        styleResponsive ? { md: 18, sm: 20, xs: 24 } : { flex: '1' }
      "
    >
      <a-row :gutter="16">
        <a-col
          v-bind="styleResponsive ? { md: 12, sm: 24, xs: 24 } : { span: 12 }"
        >
          <a-form-item label="上级分类" name="parentId">
            <a-tree-select
              allow-clear
              :tree-data="categoryList"
              tree-default-expand-all
              placeholder="请选择上级分类"
              :value="form.parentId || undefined"
              :dropdown-style="{ maxHeight: '360px', overflow: 'auto' }"
              @update:value="(value?: number) => (form.parentId = value)"
            />
          </a-form-item>
          <a-form-item label="分类名称" name="title">
            <a-input
              allow-clear
              placeholder="请输入分类名称"
              v-model:value="form.title"
              @pressEnter="save"
            />
          </a-form-item>
        </a-col>
        <a-col
          v-bind="styleResponsive ? { md: 12, sm: 24, xs: 24 } : { span: 12 }"
        >
          <a-form-item label="排序号" name="sortNumber">
            <a-input-number
              :min="0"
              :max="99999"
              class="ele-fluid"
              placeholder="请输入排序号"
              v-model:value="form.sortNumber"
            />
          </a-form-item>
          <a-form-item label="是否展示" name="status">
            <a-switch
              checked-children="是"
              un-checked-children="否"
              :checked="form.status === 0"
              @update:checked="updateHideValue"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <div style="margin-bottom: 22px">
        <a-divider />
      </div>
      <a-form-item
        label="备注"
        name="comments"
        :label-col="
          styleResponsive ? { md: 3, sm: 4, xs: 24 } : { flex: '90px' }
        "
        :wrapper-col="
          styleResponsive ? { md: 21, sm: 20, xs: 24 } : { flex: '1' }
        "
      >
        <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 } from 'ele-admin-pro';
  import {
    addArticleCategory,
    updateArticleCategory
  } from '@/api/cms/category';
  import type { ArticleCategory } from '@/api/cms/category/model';
  import { useThemeStore } from '@/store/modules/theme';
  import { storeToRefs } from 'pinia';
  import { Design } from '@/api/cms/design/model';
  import type { Rule } from 'ant-design-vue/es/form';

  const useForm = Form.useForm;

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

  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    data?: ArticleCategory | null;
    // 分类id
    categoryId?: number;
    // 全部分类
    categoryList: ArticleCategory[];
  }>();

  // 是否开启响应式布局
  const themeStore = useThemeStore();
  const { styleResponsive } = storeToRefs(themeStore);

  // 是否是修改
  const isUpdate = ref(false);

  // 提交状态
  const loading = ref(false);

  // 表单数据
  const form = reactive<ArticleCategory>({
    categoryId: undefined,
    type: 0,
    title: '',
    parentId: undefined,
    image: '',
    path: '/article/:id',
    component: '/article/index',
    pageId: undefined,
    pageName: '',
    status: 0,
    showIndex: 0,
    recommend: 0,
    sortNumber: 100
  });

  // 表单验证规则
  const rules = reactive({
    type: [
      {
        required: true,
        message: '请选择分类类型',
        type: 'number',
        trigger: 'blur'
      }
    ],
    title: [
      {
        required: true,
        message: '请输入分类名称',
        type: 'string',
        trigger: 'blur'
      }
    ],
    sortNumber: [
      {
        required: true,
        message: '请输入排序号',
        type: 'number',
        trigger: 'blur'
      }
    ],
    status: [
      {
        required: true,
        message: '请设置是否展示',
        type: 'number',
        trigger: 'blur'
      }
    ],
    meta: [
      {
        type: 'string',
        validator: async (_rule: Rule, value: string) => {
          if (value) {
            const msg = '请输入正确的JSON格式';
            try {
              const obj = JSON.parse(value);
              if (typeof obj !== 'object' || obj === null) {
                return Promise.reject(msg);
              }
            } catch (_e) {
              return Promise.reject(msg);
            }
          }
          return Promise.resolve();
        },
        trigger: 'blur'
      }
    ]
  });

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

  const onType = (index: number) => {
    if (index == 0) {
      form.path = '/article/:id';
      form.component = '/article/index';
    }
    if (index == 1) {
      form.path = '/page/:id';
      form.component = '/about/index';
    }
    if (index == 2) {
      form.path = undefined;
      form.component = '';
    }
  };

  const choosePageId = (data: Design) => {
    form.pageName = data.name;
    form.pageId = data.pageId;
    form.title = data.name;
  };

  const updateHideValue = (value: boolean) => {
    form.status = value ? 0 : 1;
  };

  const updateIndexValue = (value: boolean) => {
    form.showIndex = value ? 1 : 0;
  };

  const updateRecommendValue = (value: boolean) => {
    form.recommend = value ? 1 : 0;
  };

  /* 保存编辑 */
  const save = () => {
    validate()
      .then(() => {
        loading.value = true;
        const categoryData = {
          ...form,
          parentId: form.parentId || 0
        };
        const saveOrUpdate = isUpdate.value
          ? updateArticleCategory
          : addArticleCategory;
        saveOrUpdate(categoryData)
          .then((msg) => {
            loading.value = false;
            message.success(msg);
            updateVisible(false);
            emit('done');
          })
          .catch((e) => {
            loading.value = false;
            message.error(e.message);
          });
      })
      .catch(() => {});
  };

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

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        if (props.data) {
          assignObject(form, props.data);
          isUpdate.value = true;
        } else {
          form.parentId = props.categoryId;
          isUpdate.value = false;
        }
      } else {
        resetFields();
      }
    }
  );
</script>
