<!-- 用户编辑弹窗 -->
<template>
  <a-drawer
    :width="600"
    :visible="visible"
    :confirm-loading="loading"
    :maxable="maxAble"
    :title="isUpdate ? '编辑' : '新建'"
    :body-style="{ paddingBottom: '8px' }"
    :footer-style="{ textAlign: 'right' }"
    @update:visible="updateVisible"
    :maskClosable="isUpdate"
    @ok="save"
  >
    <a-form
      ref="formRef"
      :label-col="{ md: { span: 8 }, sm: { span: 24 } }"
      :wrapper-col="{ md: { span: 24 }, sm: { span: 24 } }"
      layout="vertical"
      :model="form"
      :rules="rules"
    >
      <a-form-item label="选择设备" name="equipmentCode">
        <EquipmentSelect
          dict-code="equipmentCode"
          placeholder="请选择设备"
          v-model:value="form.equipmentCode"
        />
      </a-form-item>
      <a-form-item label="事件类型" name="eventType">
        <DictSelect
          dict-code="eventType"
          v-model:value="form.eventType"
          placeholder="选择事件类型"
        />
      </a-form-item>
      <!--      <a-form-item label="上传图片" name="images">-->
      <!--        <ele-image-upload-->
      <!--          v-model:value="images"-->
      <!--          :limit="1"-->
      <!--          :drag="true"-->
      <!--          :multiple="true"-->
      <!--          :upload-handler="uploadHandler"-->
      <!--          @upload="onUpload"-->
      <!--        />-->
      <!--      </a-form-item>-->
      <a-form-item label="设备参数" name="params">
        <a-textarea
          :rows="10"
          :maxlength="200"
          placeholder="请输入备注"
          v-model:value="form.params"
        />
      </a-form-item>
    </a-form>
    <template #footer>
      <a-space>
        <a-button @click="onClose">取消</a-button>
        <a-button type="primary" @click="save">保存</a-button>
      </a-space>
    </template>
  </a-drawer>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { message } from 'ant-design-vue';
  import type { EquipmentRecord } from '@/api/apps/equipment/record/model';
  import {
    addEquipmentRecord,
    updateEquipmentRecord
  } from '@/api/apps/equipment/record';
  import { FormInstance, Rule, RuleObject } from 'ant-design-vue/es/form';
  import { ItemType } from 'ele-admin-pro/es/ele-image-upload/types';
  import { uploadFile } from '@/api/system/file';
  import { FILE_SERVER } from '@/config/setting';
  import useFormData from '@/utils/use-form-data';
  import { Category } from '@/api/goods/category/model';
  import { useThemeStore } from '@/store/modules/theme';
  import { storeToRefs } from 'pinia';
  import DictSelect from '@/components/DictSelect/index.vue';
  import dayjs, { Dayjs } from 'dayjs';
  // import MultiSpec from './MultiSpec.vue';

  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    data?: EquipmentRecord | null;
  }>();
  const emit = defineEmits<{
    (e: 'done'): void;
    (e: 'update:visible', visible: boolean): void;
  }>();

  // 是否是修改
  const isUpdate = ref(false);
  // 是否显示最大化切换按钮
  const maxAble = ref(true);
  const disabled = ref(false);
  // 选择日期
  const batteryDeliveryTime = ref<Dayjs>();
  const ctiveTime = ref<Dayjs>();

  // 提交状态
  const loading = ref(false);
  // 已上传数据
  const images = ref<ItemType[]>([]);

  const formRef = ref<FormInstance | null>(null);
  // 选项卡位置
  // const activeKey = ref('1');
  // 编辑器内容，双向绑定
  const content = ref<any>('');
  /* 更新visible */
  const updateVisible = (value: boolean) => {
    emit('update:visible', value);
  };

  // 表单数据
  const { form, resetFields, assignFields } = useFormData<EquipmentRecord>({
    id: undefined,
    equipmentCode: undefined,
    eventType: undefined,
    comments: '',
    sortNumber: 100,
    status: 0,
    merchantCode: undefined
  });

  /* 上传事件 */
  const uploadHandler = (file: File) => {
    const item: ItemType = {
      file,
      uid: (file as any).uid,
      name: file.name
    };
    if (!file.type.startsWith('image')) {
      message.error('只能选择图片');
      return;
    }
    if (file.size / 1024 / 1024 > 2) {
      message.error('大小不能超过 2MB');
      return;
    }
    onUpload(item);
  };

  // 上传文件
  const onUpload = (item) => {
    const { file } = item;
    uploadFile(file)
      .then((data) => {
        images.value.push({
          uid: data.id,
          url: FILE_SERVER + data.path,
          status: 'done'
        });
        message.success('上传成功');
      })
      .catch((e) => {
        message.error(e.message);
      });
  };

  // 表单验证规则
  const rules = reactive<Record<string, Rule[]>>({
    equipmentCode: [
      {
        required: true,
        message: '请选择设备',
        type: 'string',
        trigger: 'blur'
      }
    ],
    eventType: [
      {
        required: true,
        message: '请选择事件类型',
        type: 'string',
        trigger: 'blur'
      }
    ],
    params: [
      {
        required: true,
        message: '请填写设备参数',
        type: 'string',
        trigger: 'blur'
      }
    ],
    status: [
      {
        required: true,
        type: 'number',
        message: '请选择设备状态',
        trigger: 'blur'
      }
    ],
    sortNumber: [
      {
        required: true,
        type: 'number',
        message: '请输入排序号',
        trigger: 'blur'
      }
    ],
    // images: [
    //   {
    //     required: true,
    //     type: 'string',
    //     message: '请选择设备图片',
    //     trigger: 'blur',
    //     validator: async (_rule: RuleObject, value: string) => {
    //       if (images.value.length == 0) {
    //         return Promise.reject('请上传设备图片');
    //       }
    //       return Promise.resolve();
    //     }
    //   }
    // ],
    content: [
      {
        required: true,
        type: 'string',
        message: '请输入文章内容',
        trigger: 'blur',
        validator: async (_rule: RuleObject, value: string) => {
          if (content.value == '') {
            return Promise.reject('请输入文字内容');
          }
          return Promise.resolve();
        }
      }
    ]
  });

  /* 控制放店开关 */
  const editStatus = () => {
    if (form.status == 0) {
      form.status = 1;
    } else {
      form.status = 0;
    }
    updateEquipmentRecord(form)
      .then(() => {
        message.success('操作成功');
      })
      .catch((e) => {
        message.error(e.message);
      });
  };

  const onClose = () => {
    updateVisible(false);
  };

  /* 保存编辑 */
  const save = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        // 获取第一张图片作为封面图
        images.value.map((d, i) => {
          if (i === 0) {
            form.image = d.url;
          }
        });
        const equipmentFaultForm = {
          ...form,
          files: JSON.stringify(images.value),
          content: content.value,
          batteryDeliveryTime: batteryDeliveryTime.value?.format(
            'YYYY-MM-DD HH:mm:ss'
          ),
          ctiveTime: ctiveTime.value?.format('YYYY-MM-DD HH:mm:ss')
        };
        const saveOrUpdate = isUpdate.value
          ? updateEquipmentRecord
          : addEquipmentRecord;
        saveOrUpdate(equipmentFaultForm)
          .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) {
        if (props.data) {
          loading.value = false;
          assignFields({
            ...props.data
          });
          if (props.data.batteryDeliveryTime) {
            batteryDeliveryTime.value = dayjs(
              props.data.batteryDeliveryTime,
              'YYYY-MM-DD'
            );
            ctiveTime.value = dayjs(props.data.ctiveTime, 'YYYY-MM-DD');
          } else {
            batteryDeliveryTime.value = undefined;
            ctiveTime.value = undefined;
          }
          // images.value = JSON.parse(String(props.data.files));
          content.value = props.data.content;
          isUpdate.value = true;
        } else {
          isUpdate.value = false;
        }
      } else {
        resetFields();
        formRef.value?.clearValidate();
      }
    }
  );
</script>
<style lang="less">
  .tab-pane {
    min-height: 300px;
  }
  .ml-10 {
    margin-left: 5px;
  }
</style>
