<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="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>

        <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";

const fileList = ref([])

const beforeRemove = ({ file, resolve, index }) => {
  fileList.value.splice(index, 1)
  resolve(true)
}

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, // 佣金
})

const load = ref(false)

const skuGroup = ref([])
const skuDefault = ref([])
const skuLibrary = ref([])

const skuEditRef = ref(null)

const freightRules = ref([{
  label: "默认",
  value: "99999999"
}])

onLoad(async (e) => {

  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) {
    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
  }


})

// const form = ref()

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.keywords.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'
    })

    console.log("规格不完整，请调整!");

    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 });

  console.log(res);


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

}

const classifyList = ref([])
const getClassify = () => {
  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)

    console.log(classifyList.value);
  })
}
getClassify()
</script>

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