<!-- 编辑弹窗 -->
<template>
  <ele-modal
    :width="740"
    :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: 6, 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-form-item label="使用年限" name="yearLife">
            <a-input
              allow-clear
              placeholder="请输入分类名称"
              v-model:value="form.yearLife"
              @pressEnter="save"
            />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { message } from 'ant-design-vue/es';
  import type { FormInstance, Rule } from 'ant-design-vue/es/form';
  import { storeToRefs } from 'pinia';
  import { useThemeStore } from '@/store/modules/theme';
  import useFormData from '@/utils/use-form-data';
  import type { TowerModel } from '@/api/tower/model/model';
  import { addTowerModel, updateTowerModel } from '@/api/tower/model';
  import { FILE_SERVER } from "@/config/setting";
  import { ItemType } from "ele-admin-pro/es/ele-image-upload/types";
  import { uploadFile } from "@/api/system/file";
  import { LoginRecordParam } from "@/api/system/login-record/model";

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

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

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

  // 表单数据
  const { form, resetFields, assignFields } = useFormData<TowerModel>({
    title: '',
    categoryId: undefined,
    parentId: undefined,
    image: '',
    status: 0,
    yearLife: undefined,
    sortNumber: 100
  });

  //
  const formRef = ref<FormInstance | null>(null);
  // 是否是修改
  const isUpdate = ref(false);
  // 提交状态
  const loading = ref(false);
  // 已上传数据, 可赋初始值用于回显
  const images = ref([]);

  // 表单验证规则
  const rules = reactive<Record<string, Rule[]>>({
    title: [
      {
        required: true,
        message: '请输入分类名称',
        type: 'string',
        trigger: 'blur'
      }
    ],
    sortNumber: [
      {
        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 onUpload = (d: ItemType) => {
    uploadFile(<File>d.file)
      .then((result) => {
        form.image = result.path;
        message.success('上传成功');
      })
      .catch((e) => {
        message.error(e.message);
      });
  };

  const onClose = () => {
    form.image = ''
  }
  /* 保存编辑 */
  const save = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        const categoryForm = {
          ...form,
          parentId: form.parentId || 0
        };
        const saveOrUpdate = isUpdate.value ? updateTowerModel : addTowerModel;
        saveOrUpdate(categoryForm)
          .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);
  };

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

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        if (props.data) {
          // 头像赋值
          images.value = [];
          if(props.data.image){
            images.value.push({ uid:1, url: props.data.image, status: '' });
          }
          assignFields({
            ...props.data,
            parentId:
              props.data.parentId === 0 ? undefined : props.data.parentId
          });
          isUpdate.value = true;
        } else {
          form.parentId = props.parentId;
          isUpdate.value = false;
        }
      } else {
        resetFields();
        formRef.value?.clearValidate();
      }
    }
  );
</script>

<script lang="ts">
  import * as icons from '@/layout/menu-icons';

  export default {
    components: icons,
    data() {
      return {
        iconData: [
          {
            title: '已引入的图标',
            icons: Object.keys(icons)
          }
        ]
      };
    }
  };
</script>
