<!-- 用户编辑弹窗 -->
<template>
  <a-drawer
    :width="880"
    :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-row :gutter="16">
        <a-col
          v-bind="styleResponsive ? { md: 12, sm: 24, xs: 24 } : { span: 12 }"
        >
          <a-form-item label="所属商户" name="merchantCode">
            <MerchantSelect
              dict-code="merchantCode"
              placeholder="请选择所属商户"
              v-model:value="form.merchantCode"
            />
          </a-form-item>
          <a-form-item label="投资人" name="touziUserId">
            <UserSelect
              v-model:value="form.touziUserId"
              :placeholder="`请选择用户`"
            />
          </a-form-item>
          <!-- 1锂电池租赁 3电动车租赁 -->
          <a-form-item label="设备名称" name="equipmentName">
            <DictSelect
              dict-code="equipmentName"
              placeholder="请选择设备"
              v-model:value="form.equipmentName"
            />
          </a-form-item>
          <a-form-item label="电池型号" name="batteryModel">
            <DictSelect
              dict-code="equipmentModel"
              placeholder="请选择电池型号"
              v-model:value="form.batteryModel"
            />
          </a-form-item>
          <a-form-item label="工作状态" name="workingStatus">
            <DictSelect
              dict-code="workingStatus"
              v-model:value="form.workingStatus"
              placeholder="选择工作状态"
            />
          </a-form-item>
          <a-form-item label="电池状态" name="batteryStatus">
            <DictSelect
              dict-code="batteryStatus"
              v-model:value="form.batteryStatus"
              placeholder="选择电池状态"
            />
          </a-form-item>
          <a-form-item label="是否在线" name="isOnline">
            <DictSelect
              dict-code="isOnline"
              v-model:value="form.isOnline"
              placeholder="是否在线"
            />
          </a-form-item>
          <a-form-item label="BMS板供应商" name="bmsBrand">
            <DictSelect
              dict-code="bmsBrand"
              v-model:value="form.bmsBrand"
              placeholder="选择供应商"
            />
          </a-form-item>
          <a-form-item label="ICCID" name="iccid">
            <a-input
              allow-clear
              placeholder="请输入剩余容量"
              v-model:value="form.iccid"
            />
          </a-form-item>
          <a-form-item label="电池出厂时间" name="batteryDeliveryTime">
            <a-date-picker
              class="ele-fluid"
              placeholder="请选择时间"
              v-model:value="batteryDeliveryTime"
            />
          </a-form-item>
        </a-col>
        <a-col
          v-bind="styleResponsive ? { md: 12, sm: 24, xs: 24 } : { span: 12 }"
        >
          <a-form-item label="设备编码" name="equipmentCode">
            <a-input
              allow-clear
              placeholder="请输入设备编码"
              :disabled="isUpdate"
              v-model:value="form.equipmentCode"
            />
          </a-form-item>
          <a-form-item label="bms" name="bms">
            <a-input
              allow-clear
              placeholder="请输入设备BMS"
              v-model:value="form.bms"
            />
          </a-form-item>
          <a-form-item label="是否激活" name="isCtive">
            <DictSelect
              dict-code="ctiveStatus"
              v-model:value="form.isCtive"
              placeholder="是否激活"
            />
          </a-form-item>
          <a-form-item label="租赁状态" name="leaseStatus">
            <DictSelect
              dict-code="leaseStatus"
              v-model:value="form.leaseStatus"
              placeholder="是否激活"
            />
          </a-form-item>
          <a-form-item label="电池电量" name="batteryPower">
            <a-input
              allow-clear
              placeholder="请输入电池电量"
              v-model:value="form.batteryPower"
            />
          </a-form-item>
          <a-form-item label="总电压" name="totalVoltage">
            <a-input
              allow-clear
              placeholder="请输入总电压"
              v-model:value="form.totalVoltage"
            />
          </a-form-item>
          <a-form-item label="剩余容量" name="surplusCapacity">
            <a-input
              allow-clear
              placeholder="请输入剩余容量"
              v-model:value="form.surplusCapacity"
            />
          </a-form-item>
          <a-form-item label="设备激活时间" name="ctiveTime">
            <a-date-picker
              class="ele-fluid"
              placeholder="请选择时间"
              v-model:value="ctiveTime"
            />
          </a-form-item>
          <a-form-item label="设备开关" name="status">
            <a-switch :checked="form.status === 0" @change="editStatus" />
          </a-form-item>
        </a-col>
      </a-row>
      <!--      <a-form-item label="设备图片" name="images">-->
      <!--        <ele-image-upload-->
      <!--          v-model:value="images"-->
      <!--          :limit="14"-->
      <!--          :drag="true"-->
      <!--          :multiple="true"-->
      <!--          :upload-handler="uploadHandler"-->
      <!--          @upload="onUpload"-->
      <!--        />-->
      <!--      </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-tabs v-model:activeKey="activeKey" type="card">-->
    <!--      <a-tab-pane key="1" tab="基本信息" />-->
    <!--      <a-tab-pane key="2" tab="设备详情">-->
    <!--        <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="content">-->
    <!--            &lt;!&ndash; 编辑器 &ndash;&gt;-->
    <!--            <tinymce-editor-->
    <!--              v-model:value="content"-->
    <!--              :disabled="disabled"-->
    <!--              :init="config"-->
    <!--            />-->
    <!--          </a-form-item>-->
    <!--        </a-form>-->
    <!--      </a-tab-pane>-->
    <!--    </a-tabs>-->
  </a-drawer>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { message } from 'ant-design-vue';
  import type { Equipment } from '@/api/apps/equipment/model';
  import { addEquipment, updateEquipment } from '@/api/apps/equipment';
  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, FILE_THUMBNAIL } from '@/config/setting';
  import useFormData from '@/utils/use-form-data';
  import TinymceEditor from '@/components/TinymceEditor/index.vue';
  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 MerchantSelect from '@/components/MerchantSelect/index.vue';
  import { createCode } from '@/utils/common';
  import dayjs, { Dayjs } from 'dayjs';
  import UserSelect from "@/views/system/appstore/components/dict/user-select.vue";
  // import MultiSpec from './MultiSpec.vue';

  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    data?: Equipment | 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 themeStore = useThemeStore();
  const { styleResponsive } = storeToRefs(themeStore);

  // 提交状态
  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<Equipment>({
    equipmentType: 1,
    equipmentName: undefined,
    equipmentCode: `E${createCode()}`,
    batteryModel: undefined,
    equipmentCategory: undefined,
    bms: undefined,
    isCtive: undefined,
    workingStatus: undefined,
    leaseStatus: undefined,
    batteryStatus: undefined,
    batteryPower: undefined,
    isOnline: undefined,
    totalVoltage: undefined,
    bmsBrand: undefined,
    surplusCapacity: undefined,
    iccid: undefined,
    ctiveTime: undefined,
    batteryDeliveryTime: undefined,
    image: '',
    files: '',
    createTime: '',
    comments: '',
    sortNumber: 100,
    status: 0,
    equipmentId: 0,
    content: '',
    merchantCode: undefined,
    batteryRent: 300,
    batteryDeposit: 300,
    batteryInsurance: 0,
    batteryPrice: 0,
    touziUserId: null,
    tenantId: Number(localStorage.getItem('tenantId'))
  });

  /* 上传事件 */
  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_THUMBNAIL + data.path,
          status: 'done'
        });
        message.success('上传成功');
      })
      .catch((e) => {
        message.error(e.message);
      });
  };

  // 表单验证规则
  const rules = reactive<Record<string, Rule[]>>({
    merchantCode: [
      {
        required: true,
        message: '请选择商户',
        type: 'string',
        trigger: 'blur'
      }
    ],
    equipmentName: [
      {
        required: true,
        message: '请输入设备名称',
        type: 'string',
        trigger: 'blur'
      }
    ],
    batteryModel: [
      {
        required: true,
        type: 'string',
        message: '请选择电池型号',
        trigger: 'blur'
      }
    ],
    batteryPrice: [
      {
        required: true,
        message: '请输入销售价格',
        type: 'number',
        trigger: 'blur'
      }
    ],
    batteryRent: [
      {
        required: true,
        message: '请输入租金金额',
        type: 'number',
        trigger: 'blur'
      }
    ],
    equipmentCategory: [
      {
        required: true,
        type: 'string',
        message: '请选择设备分类',
        trigger: 'blur'
      }
    ],
    equipmentCode: [
      {
        required: true,
        type: 'string',
        message: '请填写设备编号',
        trigger: 'blur'
      }
    ],
    isCtive: [
      {
        required: true,
        type: 'string',
        message: '请选择是否激活',
        trigger: 'blur'
      }
    ],
    equipmentType: [
      {
        required: true,
        type: 'number',
        message: '请选择设备类型',
        trigger: 'blur'
      }
    ],
    deliveryType: [
      {
        required: true,
        type: 'number',
        message: '请选择配送方式',
        trigger: 'blur'
      }
    ],
    equipmentPriceMin: [
      {
        required: true,
        type: 'number',
        message: '请输入设备价格',
        trigger: 'blur'
      }
    ],
    stockTotal: [
      {
        required: true,
        type: 'number',
        message: '请输入设备库存',
        trigger: 'blur'
      }
    ],
    specType: [
      {
        required: true,
        type: 'number',
        message: '请选择规格类型',
        trigger: 'blur'
      }
    ],
    deliveryId: [
      {
        required: true,
        type: 'number',
        message: '请选择运费模板',
        trigger: 'blur'
      }
    ],
    status: [
      {
        required: true,
        type: 'number',
        message: '请选择设备状态',
        trigger: 'blur'
      }
    ],
    sortNumber: [
      {
        required: true,
        type: 'number',
        message: '请输入排序号',
        trigger: 'blur'
      }
    ],
    deductStockType: [
      {
        required: true,
        type: 'number',
        message: '请设置库存计算方式',
        trigger: 'blur'
      }
    ],
    purchaseLimit: [
      {
        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();
    //     }
    //   }
    // ],
    customerId: [
      {
        required: true,
        type: 'number',
        message: '请选择客户'
      }
    ],
    linePriceMin: [
      {
        required: true,
        type: 'number',
        message: '请输入设备划线价',
        trigger: 'blur'
      }
    ],
    content: [
      {
        required: true,
        type: 'string',
        message: '请输入文章内容',
        trigger: 'blur',
        validator: async (_rule: RuleObject, value: string) => {
          if (content.value == '') {
            return Promise.reject('请输入文字内容');
          }
          return Promise.resolve();
        }
      }
    ],
    brand: [
      {
        required: true,
        type: 'string',
        message: '请选项设备厂商',
        trigger: 'blur'
      }
    ]
  });

  const editorRef = ref<InstanceType<typeof TinymceEditor> | null>(null);
  const config = ref({
    height: 500,
    // 自定义文件上传(这里使用把选择的文件转成 blob 演示)
    file_picker_callback: (callback: any, _value: any, meta: any) => {
      const input = document.createElement('input');
      input.setAttribute('type', 'file');
      // 设定文件可选类型
      if (meta.filetype === 'image') {
        input.setAttribute('accept', 'image/*');
      } else if (meta.filetype === 'media') {
        input.setAttribute('accept', 'video/*');
      }
      input.onchange = () => {
        const file = input.files?.[0];
        if (!file) {
          return;
        }
        if (meta.filetype === 'media') {
          if (!file.type.startsWith('video/')) {
            editorRef.value?.alert({ content: '只能选择视频文件' });
            return;
          }
        }
        if (file.size / 1024 / 1024 > 20) {
          editorRef.value?.alert({ content: '大小不能超过 20MB' });
          return;
        }
        const reader = new FileReader();
        reader.onload = (e) => {
          if (e.target?.result != null) {
            const blob = new Blob([e.target.result], { type: file.type });
            callback(URL.createObjectURL(blob));
          }
        };
        reader.readAsArrayBuffer(file);
      };
      input.click();
    }
  });

  /* 控制放店开关 */
  const editStatus = () => {
    if (form.status == 0) {
      form.status = 1;
    } else {
      form.status = 0;
    }
    updateEquipment(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 equipmentForm = {
          ...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')
        };
        console.log(equipmentForm, 'equipmentForm');
        const saveOrUpdate = isUpdate.value ? updateEquipment : addEquipment;
        saveOrUpdate(equipmentForm)
          .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>
