<template>
  <view v-if="load" class="content p-2 bg-gray-100">
    <wd-toast />
    <wd-form ref="form" :model="model">
      <wd-cell-group border>

        <div class="rounded-md overflow-hidden">
          <div class="bg-gray-100 ">
            <div class="bg-gray-100 rounded mb-2">
              <div class="bg-white flex flex-col pt-3 pl-3">
                <div class="name mb-2 text-xs">缩略图</div>
                <myUpload v-model="model.pic_url"></myUpload>
              </div>
            </div>
          </div>

          <div class="bg-gray-100">
            <div class="bg-gray-100 rounded mb-2">
              <div class="bg-white flex flex-col pt-3 pl-3">
                <div class="name mb-2 text-xs">商品主图</div>
                <myUpload v-model="model.pic_list" :size="4"></myUpload>
              </div>
            </div>
          </div>
        </div>


        <view class="h-2 bg-gray-100"></view>

        <view class=" p-3 rounded mb-2">
          <div class="name mb-2 text-xs">商品名称</div>
          <view class="bg-white px-3 py-1 rounded">
            <wd-textarea v-model="model.name" auto-height />
          </view>
        </view>

        <view class="h-2 bg-gray-100"></view>

        <view class=" p-3 rounded mb-2">
          <div class="name mb-2 text-xs">商品分类</div>
          <view class="bg-white px-3 py-1 rounded">
            <wd-checkbox-group v-model="model.classify_list">

              <view class="flex overflow-auto flex-wrap">
                <div class="grid grid-cols-3">
                  <wd-checkbox style="width: 100%;" shape="button" v-for="cat of classifyList"
                    :modelValue="JSON.stringify(cat.parentIds)">
                    {{ cat.name }}
                  </wd-checkbox>
                </div>
              </view>

            </wd-checkbox-group>

          </view>
        </view>

        <view class="h-2 bg-gray-100"></view>

        <view class="bg-gray-100  rounded mb-2">
          <div class="p-2 bg-white">
            <div class="name mb-2 text-xs">服务内容</div>
            <view class="bg-white px-3 py-1 rounded">
              <wd-input type="text" v-model="model.server_project" placeholder="例子: 正品保障,极速发货,7天退换货。多个请使用英文逗号“,”分隔" />
            </view>
          </div>
        </view>

        <view class="h-2 bg-gray-100"></view>

        <view class=" p-3 rounded mb-2">
          <div class="name mb-2 text-xs">商品重量</div>
          <view class="bg-white px-3 py-2 rounded flex items-center mb-4">
            <wd-input-number v-model="model.weight" />
            <view class="text-xs from-neutral-300 ml-4">千克</view>
          </view>

          <wd-picker v-if="freightRules.length" class="w-full" :columns="freightRules" label="运费模板"
            v-model="model.freight_id" />

        </view>

        <view class="h-2 bg-gray-100"></view>

        <view class="p-3 rounded mb-2">
          <div class="name mb-2 text-xs">商品状态</div>
          <view class="bg-white px-3 py-2 rounded flex items-center">
            <wd-switch v-model="model.status" :active-value="1" :inactive-value="0" />
          </view>
        </view>

        <view class="h-2 bg-gray-100"></view>

        <view class="p-3 rounded mb-2">
          <div class="name mb-2 text-xs">规格</div>
          <view class="bg-white px-3 py-2 rounded flex items-center">
            <wd-radio-group shape="button" v-model="model.use_sku">
              <wd-radio :value="0">单规格</wd-radio>
              <wd-radio :value="1">多规格</wd-radio>
            </wd-radio-group>
          </view>
        </view>

        <view class="h-2 bg-gray-100"></view>

        <skuEdit ref="skuEditRef" :skuGroup="skuGroup"
          :Pdata="{ skuDefault, skuLibrary, skuGroup, use_sku: model.use_sku }">
        </skuEdit>

      </wd-cell-group>
      <view class="footer mt-4">
        <wd-button @click="saveGoods" type="primary" size="large" block>保存</wd-button>
      </view>
    </wd-form>
  </view>
</template>

<script setup>
import { ref } from 'vue';
import { useToast, useMessage } from '@/uni_modules/wot-design-uni';
import goods from '@/api/store/goods.js';
import system from '@/api/modules/system.js';
import skuEdit from "./components/skuEdit.vue";
import myUpload from "@/components/myUpload/index.vue";
import { onLoad, onShow } from "@dcloudio/uni-app";

/**
 * @typedef {import('@/api/store/goods').GoodsItem} GoodsItem
 */

/**
 * @typedef {import('@/api/store/goods').FreightRule} FreightRule
 */

/**
 * @typedef {Object} Sku
 * @property {string} price - 商品价格
 * @property {string} stock - 商品库存
 * @property {string} original_price - 商品原价
 */

/**
 * @typedef {Object} Model
 * @property {number} id - 商品ID
 * @property {Array<string>} classify_list - 商品分类组
 * @property {string} name - 商品名称
 * @property {string} keywords - 商品关键词
 * @property {number} sort - 商品排序
 * @property {number} status - 商品状态
 * @property {number} freight_id - 运费规则ID
 * @property {number} weight - 商品重量
 * @property {string} pic_url - 商品缩略图
 * @property {Array<string>} pic_list - 商品图组
 * @property {string} video - 商品视频
 * @property {string} detail - 图文详情
 * @property {number} use_sku - 是否使用规格
 * @property {Array<Sku>} sku_list - 规格信息
 * @property {number} is_discount - 是否有折扣
 * @property {number} discount - 折扣比例（小数）
 * @property {number} dist_price - 分销价格
 * @property {number} limit - 限购
 * @property {number} is_check - 自定义核销佣金
 * @property {number} check_type - 佣金类型
 * @property {number} check_price - 佣金
 */

/**
 * @typedef {Object} FileItem
 * @property {string} pic_url - 图片URL
 */

/**
 * @typedef {Object} SkuGroup
 * @property {Array<Sku>} skuDefault - 默认规格
 * @property {Array<Sku>} skuLibrary - 规格库
 * @property {Array<Sku>} skuGroup - 规格组
 */

/**
 * @typedef {Object} SkuEditRef
 * @property {SkuGroup} skuGroup - 规格组
 * @property {number} skuDefault - 默认规格
 * @property {number} skuLibrary - 规格库
 */

/** @type {Ref<Array<FileItem>>} */
const fileList = ref([]);

/**
 * @param {Object} param0
 * @param {FileItem} param0.file - 要删除的文件
 * @param {Function} param0.resolve - 删除文件的回调函数
 * @param {number} param0.index - 文件索引
 * @returns {void}
 */
const beforeRemove = ({ file, resolve, index }) => {
  fileList.value.splice(index, 1);
  resolve(true);
};

/** @type {Ref<Model>} */
const model = ref({
  classify_list: [], // 商品分类组
  name: "", // 商品名称
  keywords: "", // 商品关键词
  sort: 1000,
  status: 0, // 商品状态
  freight_id: 99999999, //运费规则
  weight: 0, // 商品重量
  pic_url: "", // 商品缩略图
  pic_list: [], // 商品图组
  video: "", // 商品视频
  detail: "默认", // 图文详情
  use_sku: 0, // 是否使用规格
  sku_list: [], // 规格信息
  is_discount: 0, // 是否有折扣
  discount: 50, // 折扣比例（小数）
  dist_price: 0, // 分销价格
  limit: 0, // 限购
  is_check: 0, // 自定义核销佣金
  check_type: 0, // 佣金类型
  check_price: 0, // 佣金
});

/** @type {Ref<boolean>} */
const load = ref(false);

/** @type {Ref<SkuGroup>} */
const skuGroup = ref([]);
/** @type {Ref<Array<GoodsItem>>} */
const skuDefault = ref([]);
/** @type {Ref<Array<GoodsItem>>} */
const skuLibrary = ref([]);

/** @type {Ref<SkuEditRef>} */
const skuEditRef = ref(null);

/** @type {Ref<Array<FreightRule>>} */
const freightRules = ref([{
  label: "默认",
  value: "99999999"
}]);

onLoad(async (e) => {
  model.value.id = e.id;

  /**
   * 获取运费规则
   * @returns {void}
   */
  const GetfreightRules = () => {
    goods.freightRules().then(res => {
      freightRules.value = [
        ...freightRules.value,
        ...res.data.rows.map(item => {
          return {
            label: item.name,
            value: item.id
          };
        })
      ];
    });
  };

  GetfreightRules();

  if (e.id > 0) {
    const res = await goods.goodsItem({
      id: e.id
    });

    model.value = res.data;
    model.value.pic_list = res.data.pic_list.map(({ pic_url }) => pic_url);

    if (!model.value.freight_id) {
      model.value.freight_id = 99999999;
    }
    model.value.classify_list = model.value.classify_list.map(item => JSON.stringify(item));

    if (res.data.use_sku == 0) {
      skuDefault.value = res.data.goods_sku;
    } else {
      skuLibrary.value = res.data.goods_sku;
    }
    skuGroup.value = res.data.sku_group ? res.data.sku_group : [];
    load.value = true;
  } else {
    load.value = true;
  }
});

/**
 * 保存商品信息
 * @returns {Promise<void>}
 */
const saveGoods = async () => {
  // 判断商品分类是否为空
  if (model.value.classify_list.length === 0) {
    return uni.showToast({
      title: '请选择商品分类!',
      icon: 'none'
    });
  }

  // 判断商品名称是否为空
  if (model.value.name.trim() === "") {
    return uni.showToast({
      title: '请输入商品名称!',
      icon: 'none'
    });
  }

  // 判断商品重量是否为非负数
  if (model.value.weight < 0) {
    return uni.showToast({
      title: '请输入合法的商品重量!',
      icon: 'none'
    });
  }

  // 判断商品缩略图是否为空
  if (String(model.value.pic_url).trim() === "") {
    return uni.showToast({
      title: '请上传商品缩略图!',
      icon: 'none'
    });
  }

  // 判断商品图组是否为空
  if (model.value.pic_list.length === 0) {
    return uni.showToast({
      title: '请上传商品图片组!',
      icon: 'none'
    });
  }

  model.value.sku_group = [];
  model.value.sku_list = [];
  model.value.dist_price = Number.parseInt(model.value.dist_price);

  if (model.value.use_sku == 1) {
    model.value.sku_group = skuEditRef.value.skuGroup;
    model.value.sku_list = skuEditRef.value.skuLibrary;
  } else {
    model.value.sku_list = skuEditRef.value.skuDefault;
  }

  if (!model.value.sku_list.length) {
    uni.showToast({
      title: '规格不完整，请调整!',
      icon: 'none'
    });
  }

  if (!model.value.sku_list.every(item => Boolean(item.price !== "" && item.stock !== "" && item.original_price !== ""))) {
    uni.showToast({
      title: '规格不完整，请调整!',
      icon: 'none'
    });

    return;
  }

  let freight_id = model.value.freight_id;
  if (freight_id = 99999999) {
    freight_id = 0;
  }

  const pic_list = model.value.pic_list.map(item => ({
    pic_url: item
  }));

  const classify_list = model.value.classify_list.map(item => JSON.parse(item));

  const res = await goods.goodsEdit({ ...model.value, pic_list, freight_id, classify_list });

  if (res.code == 0) {
    uni.showToast({
      title: '商品信息保存成功!',
      icon: 'success'
    });

    uni.navigateBack();
  }
};

/** @type {Ref<Array<Object>>} */
const classifyList = ref([]);

/**
 * 获取商品分类
 * @returns {void}
 */
const getClassify = () => {
  /**
   * 递归展平商品分类
   * @param {Array<GoodsItem>} categories - 商品分类数组
   * @param {Array<number>} [parentIds=[]] - 父级分类ID数组
   * @returns {Array<Object>} - 展平后的商品分类数组
   */
  function flattenCategories(categories, parentIds = []) {
    let flatCategories = [];

    for (const category of categories) {
      const categoryWithParents = {
        ...category,
        parentIds: [...parentIds, category.id],
      };

      flatCategories.push(categoryWithParents);

      if (category.children && category.children.length > 0) {
        flatCategories = flatCategories.concat(flattenCategories(category.children, [...parentIds, category.id]));
      }
    }

    return flatCategories;
  }

  goods.classify.list().then(res => {
    classifyList.value = flattenCategories(res.data);
  });
};

getClassify();

</script>

<style lang="scss"></style>
