<!-- 用户编辑弹窗 -->
<template>
  <ele-modal
    :width="880"
    :visible="visible"
    :confirm-loading="loading"
    :maxable="maxAble"
    :title="isUpdate ? '编辑商品' : '添加商品'"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible="updateVisible"
    :maskClosable="false"
    @ok="save"
  >
    <a-tabs v-model:activeKey="activeKey" type="card">
      <a-tab-pane key="1" tab="基本信息">
        <a-form
          ref="formRef"
          :model="form"
          :rules="rules"
          :label-col="{ md: { span: 8 }, sm: { span: 24 } }"
          :wrapper-col="{ md: { span: 24 }, sm: { span: 24 } }"
          layout="vertical"
        >
          <a-row :gutter="16">
            <a-col
              v-bind="
                styleResponsive ? { md: 12, sm: 24, xs: 24 } : { span: 12 }
              "
            >
              <a-form-item label="商品名称" name="goodsName">
                <a-input
                  allow-clear
                  placeholder="请输入商品名称"
                  v-model:value="form.goodsName"
                />
              </a-form-item>
              <a-form-item label="商品分类" name="categoryId">
                <category-select
                  :data="categoryList"
                  placeholder="请选择商品分类"
                  v-model:value="form.categoryId"
                />
              </a-form-item>
              <a-form-item label="商品类型" name="goodsType">
                <a-radio-group v-model:value="form.goodsType">
                  <a-radio :value="1">实物商品</a-radio>
                  <a-radio :value="0">虚拟商品</a-radio>
                </a-radio-group>
              </a-form-item>
              <a-form-item
                label="配送方式"
                name="deliveryType"
                v-if="form.goodsType === 1"
              >
                <a-radio-group v-model:value="form.deliveryType">
                  <a-radio :value="0">系统默认</a-radio>
                  <a-radio :value="1">单独配送</a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>
            <a-col
              v-bind="
                styleResponsive ? { md: 12, sm: 24, xs: 24 } : { span: 12 }
              "
            >
              <a-form-item label="商品编码" name="goodsCode">
                <a-input
                  allow-clear
                  placeholder="请输入商品编码"
                  :disabled="isUpdate"
                  v-model:value="form.goodsCode"
                />
              </a-form-item>
              <a-form-item label="商品状态" name="status">
                <a-radio-group v-model:value="form.status">
                  <a-radio :value="0">上架</a-radio>
                  <a-radio :value="1">下架</a-radio>
                </a-radio-group>
              </a-form-item>
              <a-form-item
                label="运费模板"
                name="deliveryId"
                v-if="form.goodsType === 1"
              >
                <deliver-select v-model:value="form.deliveryId" />
              </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>
      </a-tab-pane>
      <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="specType">
            <a-radio-group v-model:value="form.specType">
              <a-radio :value="0">单规格</a-radio>
              <!--              <a-radio :value="1">多规格</a-radio>-->
            </a-radio-group>
          </a-form-item>
          <div style="margin-bottom: 22px">
            <a-divider />
          </div>
          <a-row :gutter="16">
            <a-col
              v-bind="
                styleResponsive ? { md: 12, sm: 24, xs: 24 } : { span: 12 }
              "
            >
              <a-form-item
                label="商品价格"
                name="goodsPriceMin"
                v-if="form.specType === 0"
              >
                <a-input-number
                  :min="0.01"
                  :precision="2"
                  style="width: 200px"
                  v-model:value="form.goodsPriceMin"
                />
                <span class="ml-10">元</span>
              </a-form-item>
              <a-form-item
                label="划线价"
                name="linePrice"
                v-if="form.specType === 0"
              >
                <a-input-number
                  :min="0.01"
                  :precision="2"
                  style="width: 200px"
                  v-model:value="form.linePriceMin"
                />
                <span class="ml-10">元</span>
              </a-form-item>
            </a-col>
            <a-col
              v-bind="
                styleResponsive ? { md: 12, sm: 24, xs: 24 } : { span: 12 }
              "
            >
              <a-form-item
                label="当前库存数量"
                name="stockTotal"
                v-if="form.specType === 0"
              >
                <a-input-number
                  :min="0"
                  :precision="0"
                  style="width: 200px"
                  v-model:value="form.stockTotal"
                />
                <span class="ml-10">件</span>
              </a-form-item>
              <a-form-item
                label="商品重量"
                name="goodsWeight"
                v-if="form.specType === 0"
              >
                <a-input-number
                  :min="0"
                  :precision="0"
                  style="width: 200px"
                  v-model:value="form.goodsWeight"
                />
                <span class="ml-10">千克 (Kg)</span>
              </a-form-item>
            </a-col>
          </a-row>
          <a-form-item
            label="商品规格"
            name="deductStockType"
            v-if="form.specType === 1"
          >
            <!--            <MultiSpec ref="MultiSpec" />-->
          </a-form-item>
          <div style="margin-bottom: 22px">
            <a-divider />
          </div>
          <a-form-item label="库存计算方式" name="deductStockType">
            <a-radio-group v-model:value="form.deductStockType">
              <a-radio :value="10">下单减库存</a-radio>
              <a-radio :value="20">付款减库存</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item label="商品限购" name="purchaseLimit">
            <a-radio-group v-model:value="form.purchaseLimit">
              <a-radio :value="0">关闭</a-radio>
              <a-radio :value="1">开启</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-form>
      </a-tab-pane>
      <a-tab-pane key="3" 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">
            <!-- 编辑器 -->
            <tinymce-editor
              v-model:value="content"
              :disabled="disabled"
              :init="config"
            />
          </a-form-item>
        </a-form>
      </a-tab-pane>
      <a-tab-pane key="4" 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="sellingPoint">
            <a-input
              allow-clear
              placeholder="【入手皆因热爱】限时限量领券至高立减400元，限时优惠，限量抢购！！赶快下单吧！"
              v-model:value="form.sellingPoint"
            />
          </a-form-item>
          <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>
      </a-tab-pane>
    </a-tabs>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { message } from 'ant-design-vue';
  import type { Goods } from '@/api/goods/model';
  import { addGoods, updateGoods } from '@/api/goods';
  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_THUMBNAIL } from '@/config/setting';
  import useFormData from '@/utils/use-form-data';
  import CategorySelect from './category-select.vue';
  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 DeliverSelect from './deliver-select.vue';
  import { createCode } from '@/utils/common';
  // import MultiSpec from './MultiSpec.vue';

  // 是否是修改
  const isUpdate = ref(false);
  // 是否显示最大化切换按钮
  const maxAble = ref(true);
  const disabled = ref(false);
  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    data?: Goods | null;
    categoryList?: Category[];
  }>();

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

  // 是否开启响应式布局
  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<Goods>({
    goodsType: 1,
    goodsName: '',
    goodsCode: `G${createCode()}`,
    categoryId: 0,
    image: '',
    files: '',
    goodsPriceMin: 0.01,
    linePriceMin: 0.01,
    createTime: '',
    comments: '',
    sortNumber: 100,
    status: 0,
    goodsId: 0,
    specType: 0,
    deliveryType: 0,
    content: '',
    deliveryId: 0,
    sellingPoint: '',
    purchaseLimit: 0,
    deductStockType: 10,
    salesActual: 180,
    goodsWeight: 0,
    stockTotal: 2000
  });

  /* 上传事件 */
  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[]>>({
    goodsName: [
      {
        required: true,
        message: '请输入商品名称',
        type: 'string',
        trigger: 'blur'
      }
    ],
    categoryId: [
      {
        required: true,
        type: 'number',
        message: '请选择商品分类',
        trigger: 'blur'
      }
    ],
    goodsCode: [
      {
        required: true,
        type: 'string',
        message: '请填写商品编号',
        trigger: 'blur'
      }
    ],
    goodsType: [
      {
        required: true,
        type: 'number',
        message: '请选择商品类型',
        trigger: 'blur'
      }
    ],
    deliveryType: [
      {
        required: true,
        type: 'number',
        message: '请选择配送方式',
        trigger: 'blur'
      }
    ],
    goodsPriceMin: [
      {
        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 onSelect = (item) => {
  //   form.goodsId = item.goodsId;
  // };

  /* 保存编辑 */
  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 goodsForm = {
          ...form,
          files: JSON.stringify(images.value),
          content: content.value
        };
        const saveOrUpdate = isUpdate.value ? updateGoods : addGoods;
        saveOrUpdate(goodsForm)
          .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,
            files: JSON.parse(String(props.data.files))
          });
          images.value = JSON.parse(String(props.data.files));
          content.value = props.data.content;
          isUpdate.value = true;
        } else {
          isUpdate.value = false;
          content.value = '';
        }
      } else {
        resetFields();
        formRef.value?.clearValidate();
      }
    }
  );
</script>
<style lang="less">
  .tab-pane {
    min-height: 300px;
  }
  .ml-10 {
    margin-left: 5px;
  }
</style>
