<template>
  <div class="addgoods">
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="150px" class="demo-ruleForm" status-icon>
      <el-form-item label="商品名称" required>
        <el-col :span="12">
          <el-form-item prop="name">
            <el-input v-model="ruleForm.name" placeholder="请输入商品名称" :disabled="isSyncStatus()" />
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item label="商品介绍">
        <el-col :span="12">
          <el-form-item>
            <el-input v-model="ruleForm.shortTitle" type="textarea" placeholder="请输入商品介绍" :disabled="isSyncStatus()" />
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item label="单位" required>
        <el-col :span="12">
          <el-form-item prop="unitId">
            <el-select v-model="ruleForm.unitId" placeholder="请选择单位" :disabled="isSyncStatus()">
              <el-option :label="item.name" :value="item.id" v-for="item in datas.Company" :key="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item label="商品分类" required>
        <el-col :span="12">
          <el-form-item prop="region">
            <el-select v-model="ruleForm.categoryId" placeholder="请选择商品分类" :disabled="isSyncStatus()">
              <el-option :label="item.name" :value="item.id" v-for="item in datas.classification" :key="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-form-item>
      <!-- <el-form-item label="商品图片" required prop="images">
        <MultiImageUpload v-model="ruleForm.images" />
      </el-form-item> -->
      <el-form-item label="商品图片" required prop="images">
        <div style="display: flex; flex-wrap: wrap">
          <div v-for="(item, index) in ruleForm.images" :key="index" style="position: relative" class="showStyle">
            <el-icon class="buttonstyle" @click="deleteEvent(item)">
              <DeleteFilled />
            </el-icon>
            <img style="width: 148px; height: 148px; margin-right: 6px" class="imgStyle" :src="item" alt="" />
          </div>
          <div class="upImgStyle" @click="addimgEvent">+</div>
        </div>
      </el-form-item>
      <el-form-item>
        <div class="tips">注：第一张图为商品封面图，图片尺寸为750×750</div>
      </el-form-item>
      <!-- 选择图片 -->
      <AddImg ref="addImg" @successEvent="successEvent"></AddImg>

      <el-form-item label="商品类型">
        <el-radio-group v-model="ruleForm.type" @change="changeTypeEnum(ruleForm.type)" :disabled="isSyncStatus()">
          <el-radio value="single">单规格商品</el-radio>
          <el-radio value="sku">多规格商品</el-radio>
          <el-radio value="package">套餐商品</el-radio>
          <el-radio value="weight">称重商品</el-radio>
          <!-- <el-radio label="coupon">团购券</el-radio> -->
        </el-radio-group>
      </el-form-item>
      <el-form-item label="套餐商品" v-if="ruleForm.type == 'package'">
        <div style="display: block; width: 100%">
          <div class="head-container">
            <el-radio-group v-model="ruleForm.groupType" @change="typeChange">
              <el-radio-button :label="0">固定套餐</el-radio-button>
              <el-radio-button :label="1">可选套餐</el-radio-button>
            </el-radio-group>
          </div>
          <div v-if="ruleForm.groupType == 0">
            <el-table border :data="item.goods" v-for="(item, index) in ruleForm.proGroupVo" :key="index">
              <el-table-column label="名称" prop="proName"></el-table-column>
              <el-table-column label="规格" prop="skuName"></el-table-column>
              <el-table-column label="价格" prop="price"></el-table-column>
              <el-table-column label="数量" prop="number">
                <template v-slot="scope">
                  <el-input-number v-model="scope.row.number" :min="0" />
                </template>
              </el-table-column>
              <el-table-column width="150">
                <template #header>
                  <el-button type="primary" @click="addgoods(-1)" :disabled="isSyncStatus()">
                    添加商品
                  </el-button>
                </template>
                <template v-slot="scope">
                  <el-button type="text" :disabled="scope.row.type != 'sku' && isSyncStatus()"
                    @click="showSelectSkuHandle(scope.row, scope.$index, index)">设置规格</el-button>
                  <el-button type="text"
                    @click="ruleForm.proGroupVo[index].goods.splice(scope.$index, 1)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div v-if="ruleForm.groupType == 1">
            <div class="group_wrap" v-for="(item, index) in ruleForm.proGroupVo" :key="index">
              <el-form inline :model="item">
                <el-form-item label="规格组名">
                  <el-input v-model="item.title" :disabled="isSyncStatus()" />
                </el-form-item>
                <el-form-item :label="`本组菜品${item.goods.length}选`">
                  <el-input v-model="item.number" :disabled="isSyncStatus()" />
                </el-form-item>
                <el-form-item>
                  <el-button @click="ruleForm.proGroupVo.splice(index, 1)" :disabled="isSyncStatus()">
                    删除
                  </el-button>
                </el-form-item>
              </el-form>
              <div style="margin-top: 20px">
                <el-table border :data="item.goods">
                  <el-table-column label="名称" prop="proName"></el-table-column>
                  <el-table-column label="规格" prop="skuName"></el-table-column>
                  <el-table-column label="价格" prop="price"></el-table-column>
                  <el-table-column label="数量" prop="number">
                    <template v-slot="scope">
                      <el-input-number v-model="scope.row.number" :min="0" :disabled="isSyncStatus()" />
                    </template>
                  </el-table-column>
                  <el-table-column width="150">
                    <template #header>
                      <el-button type="primary" @click="addgoods(index)" :disabled="isSyncStatus()">
                        添加商品
                      </el-button>
                    </template>
                    <template v-slot="scope">
                      <el-button type="text" :disabled="scope.row.type != 'sku' && isSyncStatus()"
                        @click="showSelectSkuHandle(scope.row, scope.$index, index)">设置规格</el-button>
                      <el-button type="text" @click="ruleForm.proGroupVo[index].goods.splice(scope.$index, 1)"
                        :disabled="isSyncStatus()">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
            <el-button type="primary" @click="addtaocan" :disabled="isSyncStatus()">
              添加套餐组
            </el-button>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="选择规格" v-if="ruleForm.type == 'sku'">
        <el-select v-model="ruleForm.specId" placeholder="请选择规格" style="width: 500px" @change="selectSpecHandle"
          :disabled="isSyncStatus()">
          <el-option :label="item.name" :value="item.id" v-for="item in datas.specificationsconfig"
            :key="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="ele.name" v-if="datas.selectSpeclist.length" v-for="ele in datas.selectSpeclist"
        :key="ele.name">
        <el-checkbox-group v-model="ele.selectSpecResult" @change="selectSpecResultChange">
          <el-checkbox :value="element.name" :label="element.name" v-for="(element, index) in ele.children"
            :key="index"></el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <!-- 规格属性 -->
      <!-- 单规格、称重 -->
      <SpecificationAttribute v-if="ruleForm.type != 'sku'" :info="ruleForm" :list="list"
        ref="specificationAttributeRef">
      </SpecificationAttribute>
      <SpecificationAttribute v-if="ruleForm.type == 'sku' && list.length" :specTableHeaders="datas.specTableHeaders"
        :info="ruleForm" :list="list" ref="specificationAttributeRef"></SpecificationAttribute>
      <el-form-item label="重量">
        <el-col :span="12">
          <div style="display: block">
            <el-input v-model="ruleForm.weight" placeholder="" :disabled="isSyncStatus()">
              <template #append>千克</template>
            </el-input>
            <!-- <div style="color: #999;">用于快递或配送运费计重</div> -->
          </div>
        </el-col>
      </el-form-item>
      <el-form-item label="是否允许临时改价">
        <el-radio-group v-model="ruleForm.isAllowTempModifyPrice" :disabled="isSyncStatus()">
          <el-radio :value="1">允许</el-radio>
          <el-radio :value="0">不允许</el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- <el-form-item label="每日销量上限">
        <el-input-number v-model="ruleForm.dayLimit" :min="0" />
      </el-form-item>
      <el-form-item label="每单限购">
        <el-input-number v-model="ruleForm.dayLimit" :min="0" />
      </el-form-item>
      <el-form-item label="每人限购">
        <el-input-number v-model="ruleForm.dayLimit" :min="0" />
      </el-form-item> -->
      <el-form-item label="定时上下架">
        <el-checkbox-group v-model="ruleForm.days">
          <el-checkbox v-for="(item, index) in datas.cycle" :key="item.value" :value="item.value">
            {{ item.label }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item>
        <el-col :span="20">
          <!-- <el-time-picker v-model="ruleForm.useTime" is-range range-separator="至" start-placeholder="开始时间"
            end-placeholder="结束时间" value-format="HH:mm:ss" format="HH:mm:ss"   />
 -->

          <el-time-picker v-model="ruleForm.startTime" value-format="HH:mm:ss" format="HH:mm:ss" placeholder="选择开始时间">
          </el-time-picker>-
          <el-time-picker v-model="ruleForm.endTime" value-format="HH:mm:ss" format="HH:mm:ss" placeholder="选择结束时间">
          </el-time-picker>
        </el-col>
      </el-form-item>
      <el-form-item label="上架">
        <el-switch v-model="ruleForm.isSale" :active-value="1" :inactive-value="0" />
      </el-form-item>
      <el-form-item label="库存开关">
        <div style="display: block;">
          <el-switch v-model="ruleForm.isStock" :active-value="1" :inactive-value="0" :disabled="isSyncStatus()" />
          <div style="color: #999;">注：关闭则不计算出库数据</div>
        </div>
      </el-form-item>
      <el-form-item label="设为推荐" prop="delivery">
        <el-switch v-model="ruleForm.isHot" :active-value="1" :inactive-value="0" />
      </el-form-item>
      <el-form-item label="库存数量">
        <el-input-number v-model="ruleForm.stockNumber" :min="0" />
      </el-form-item>

      <el-form-item label="打包费" prop="delivery">
        <div style="display: block;">
          <el-input-number v-model="ruleForm.packFee" controls-position="right"
            :disabled="isSyncStatus()"></el-input-number>
          <div style="color: #999;">单份商品打包费。注：店铺开启外卖模式下该数据才生效</div>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
        <el-button @click="resetForm(ruleFormRef)">取消</el-button>
      </el-form-item>
    </el-form>
    <!-- 选择商品 -->
    <shopList ref="shopListRef" @success="selectShopRes" />
    <el-dialog :title="datas.selectSkuItem.proName" v-model="datas.showSelectSku">
      <div class="pro_sku">
        <div class="item">
          <div class="row">
            <div class="title">选项值</div>
            <div class="tag" :class="{ active: item.active }" v-for="(item, index) in datas.selectSkuItem.skuList"
              :key="item.id" @click="selectSkuHandle(item, index)">
              {{ item.specInfo }}
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="datas.showSelectSku = false">取 消</el-button>
          <el-button type="primary" @click="showSelectSkuConfirm">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import type { FormInstance, FormRules } from "element-plus";
// 规格属性
import SpecificationAttribute from "./SpecificationAttribute.vue";
import { isSyncStatus } from "@/utils/index";
import UserAPI from "@/api/product/productclassification";
import UserAPI2 from "@/api/product/commonUnits";
import UserAPI3 from "@/api/product/index";
import UserAPI4 from "@/api/product/specificationsconfig";
import shopList from "@/components/mycomponents/shopList.vue";
import AddImg from "@/components/mycomponents/addImg.vue";
import { useRouter } from "vue-router";
import { useTagsViewStore } from "@/store";
const tagsViewStore = useTagsViewStore();
const router = useRouter();
let list = ref<any[]>([
  {
    originPrice: 0,
    costPrice: 0,
    salePrice: 0,
    memberPrice: 0,
    suitNum: 1,
    coverImg: "",
    weight: 0,
    barCode: "88888888888888888888",
  },
]);
let datas = reactive<datasForm>({
  cycle: [
    { label: "周一", value: "Monday" },
    { label: "周二", value: "Tuesday" },
    { label: "周三", value: "Wednesday" },
    { label: "周四", value: "Thursday" },
    { label: "周五", value: "Friday" },
    { label: "周六", value: "Saturday" },
    { label: "周七", value: "Sunday" },
  ],
  Company: [],
  classification: [],
  // 商品规格
  specificationsconfig: [],
  selectSpeclist: [],
  defaultSku: {
    originPrice: 0,
    costPrice: 0,
    salePrice: 0,
    memberPrice: 0,
    suitNum: 1,
    coverImg: "",
    weight: 0,
    barCode: "88888888888888888888",
  },
  specTableHeaders: [],
  // 套餐商品-单规格index
  selectSkuTableIndex: 0,
  selectSkuConfirmIndex: 0,
  showSelectSku: false,
  selectSkuItem: {},
  addGroupIndex: -1,
});
let shopListRef = ref(null);
let addImg = ref(null);
let isedit = ref(true);
interface datasForm {
  cycle: { label: string; value: string }[];
  Company: any[];
  classification: any[];
  specificationsconfig: any[];
  selectSpeclist: any[];
  defaultSku: any;
  specTableHeaders: any[];
  selectSkuTableIndex: any;
  selectSkuConfirmIndex: number;
  showSelectSku: boolean;
  selectSkuItem: any;
  addGroupIndex: any;
}
interface RuleForm {
  name: string;
  shortTitle: string;
  unitId: string;
  categoryId: string;
  coverImg: string;
  images: string[];
  type: string;
  specId: any;
  groupType: any;
  skuList: string[];
  weight: any;
  isAllowTempModifyPrice: any;
  days: any;
  useTime: string[];
  startTime: string;
  endTime: string;
  isSale: string;
  isStock: string;
  isHot: string;
  stockNumber: any;
  packFee: any;
  sort: Number;
  proGroupVo: any[];
  selectSpecInfo: any;
}
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  //商品名称
  name: "",
  //商品介绍
  shortTitle: "",
  // 单位id
  unitId: "",
  // 分类id
  categoryId: "",
  // 封面图url
  coverImg: "",
  // 详情图urls
  images: [],
  // 商品类型
  type: "single",
  // 规格id
  specId: "",
  // 套餐类型
  groupType: 0,
  // 套餐入参
  proGroupVo: [
    {
      title: "",
      count: "",
      number: "",
      goods: [],
    },
  ],
  // sku集合
  skuList: [],
  // 重量
  weight: 0,
  // 是否允许改价
  isAllowTempModifyPrice: 1,
  // 定时上下架周期
  days: ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
  useTime: ["00:00:00", "23:59:59"],
  // 开始时间
  startTime: "",
  // 结束时间
  endTime: "",
  // 是否上架
  isSale: "1",
  // 是否开启库存
  isStock: "1",
  // 设为推荐
  isHot: "1",
  // 库存数量
  stockNumber: 0,
  // 打包费
  packFee: 0,
  // 排序值
  sort: 1,
  selectSpecInfo: {},
});
const rules = reactive<FormRules<RuleForm>>({
  name: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
  unitId: [
    {
      required: true,
      message: "请选择单位",
      trigger: "change",
    },
  ],
  categoryId: [
    {
      required: true,
      message: "请选择商品分类",
      trigger: "change",
    },
  ],
  images: [
    {
      required: true,
      message: "请选择图片",
      trigger: "change",
    },
  ],
});
onMounted(() => {
  getList();
  if (router.currentRoute.value.query.goods_id) {
    tbProductGetDetail(router.currentRoute.value.query.goods_id);
  }
})
watch(() => router.currentRoute.value.query.goods_id, (val) => {
  tbProductGetDetail(val);
})

async function tbProductGetDetail(id: any) {
  // 获取商品详情
  const res = await UserAPI3.getDetail(id);
  changeTypeEnum(res.type);
  for (const key in res) {
    if (key !== "images" && key !== "days") {
      (ruleForm as any)[key] = res[key];
    }
  }
  ruleForm.images = res.images.map((item: any, index: number) => item);
  ruleForm.days = res.days.split(",");
  ruleForm.useTime = [res.startTime, res.endTime];
  ruleForm.proGroupVo = res.groupSnap;
  if (res.type === "sku") {
    await tbProductSpecGet();
    selectSpecHandle(ruleForm.specId);
    datas.selectSpeclist.forEach((item: any) => {
      item.selectSpecResult = res.selectSpecInfo[item.name];
      // if (item.name === res.selectSpecInfo.name
      // ) { }
      // item.children.forEach((ele: any) => {
      // item.selectSpecResult.push(ele.name)
      // })
    });
    selectSpecResultChange();
  } else {
    list.value = ruleForm.skuList;
  }
}
// 选择套餐商品sku
function selectSkuHandle(item: any, index: number) {
  // 把所有的设置为false
  datas.selectSkuItem.skuList.map((item: any, index: number) => {
    let nitem = { ...item };
    nitem.active = false;
    datas.selectSkuItem.skuList[index] = nitem;
  });

  if (item.active) {
    item.active = false;
  } else {
    item.active = true;
  }
  datas.selectSkuItem.skuList[index] = { ...item };

  // let arr = datas.selectSkuItem.skuList.filter((item:any) => item.active)

  // if (arr.length) {
  //   this.selectSkuConfirmDisabled = false
  // } else {
  //   this.selectSkuConfirmDisabled = true
  // }
}
function addimgEvent() {
  if (isSyncStatus()) {
    ElMessage.error('当前同步启用状态下不可修改')
    return
  }
  (addImg.value as any)?.show();
}
// 确认套餐商品设置规格
function showSelectSkuConfirm() {
  let item = datas.selectSkuItem.skuList.filter((item: any) => item.active);
  ruleForm.proGroupVo[datas.selectSkuTableIndex].goods[datas.selectSkuConfirmIndex] = {
    ...ruleForm.proGroupVo[datas.selectSkuTableIndex].goods[datas.selectSkuConfirmIndex],
    skuId: item[0].id,
  };
  ruleForm.proGroupVo[datas.selectSkuTableIndex].goods[datas.selectSkuConfirmIndex] = {
    ...ruleForm.proGroupVo[datas.selectSkuTableIndex].goods[datas.selectSkuConfirmIndex],
    skuName: item[0].specInfo,
  };
  datas.showSelectSku = false;
}
// 显示套餐商品设置规格
function showSelectSkuHandle(row: any, index: any, tabIndex: any) {
  datas.selectSkuTableIndex = tabIndex;
  datas.selectSkuConfirmIndex = index;
  datas.showSelectSku = true;

  let obj = { ...row };

  obj.skuList.map((item: any) => {
    item.active = false;
  });

  datas.selectSkuItem = obj;
}
// 添加商品
function addgoods(index: number = -1) {
  datas.addGroupIndex = index;
  (shopListRef.value as any)?.opens();
}
function deleteEvent(d: any) {
  if (isSyncStatus()) {
    ElMessage.error('当前同步启用状态下不可修改')
    return
  }
  let index = ruleForm.images.findIndex((ele) => ele == d);
  ruleForm.images.splice(index, 1);
}
function successEvent(d: any) {
  ruleForm.images.push(d[0].url);
}
// 分组选择商品
function selectShopRes(res: Array<any>) {
  let newres = res.map((item) => {
    item.proId = item.id;
    item.proName = item.name;
    item.price = item.lowPrice;
    item.skuId = item.skuList[0].id;
    item.skuName = "";
    item.number = 1;
    // 单规格skuid添加
    return item;
  });

  if (ruleForm.groupType == 0) {
    let obj = {
      title: "",
      count: newres.length,
      number: "",
      goods: newres,
    };
    ruleForm.proGroupVo = [{ ...obj }];
  } else {
    if (datas.addGroupIndex != -1) {
      ruleForm.proGroupVo[datas.addGroupIndex].count = newres.length;
      ruleForm.proGroupVo[datas.addGroupIndex].goods = newres;
    } else {
      let arr = [...ruleForm.proGroupVo];
      arr.push({
        title: "",
        count: newres.length,
        number: "",
        goods: newres,
      });
      ruleForm.proGroupVo = [...arr];
    }
  }
}
// 获取单位、分类数据
async function getList() {
  datas.Company = (await UserAPI2.getList(null)) as any[];
  datas.classification = (await UserAPI.getList(null)) as any[];
}
// 选择规格属性
function selectSpecResultChange() {
  createSkuHeader();
  createSkuBody();
}

function createSkuHeader() {
  const headers = [];
  for (let item of datas.selectSpeclist) {
    if (item.selectSpecResult.length) {
      headers.push({
        label: item.name,
        value: item.name,
      });
    }
  }
  datas.specTableHeaders = headers;
}

// 可选套餐弹窗
function addtaocan() {
  datas.addGroupIndex = -1;
  (shopListRef.value as any)?.opens();
}
// 生成多规格表体
function createSkuBody() {
  let bodys = [];
  for (let item of datas.selectSpeclist) {
    if (item.selectSpecResult.length) {
      let arr = [];
      for (let val of item.selectSpecResult) {
        arr.push({
          [item.name]: val,
        });
      }
      bodys.push(arr);
    }
  }
  let arr = cartesian(bodys);
  const m = {
    coverImg: "",
    ...datas.defaultSku,
  };
  let newarr = [];
  for (let item of arr) {
    if (Array.isArray(item)) {
      let obj: Record<string, any> = {};
      let specSnap = [];
      for (let v of item) {
        for (let key in v) {
          obj[`${key}`] = v[key];
          specSnap.push(v[key]);
        }
      }
      let specSnapStr = specSnap.join(",");
      newarr.push({
        specSnap: specSnapStr,
        specInfo: specSnapStr,
        ...m,
        ...obj,
        // barCode: `${dayjs().valueOf()}${RandomNumBoth(1, 9999)}`,
      });
    } else {
      let specSnap = [];
      for (let key in item) {
        specSnap.push(item[key]);
      }
      let specSnapStr = specSnap.join(",");
      newarr.push({
        specSnap: specSnapStr,
        specInfo: specSnapStr,
        ...m,
        ...item,
        // barCode: `${dayjs().valueOf()}${RandomNumBoth(1, 9999)}`,
      });
    }
  }
  if (ruleForm.skuList.length) {
    if (isedit.value) {
      let arr: any[] = [];
      ruleForm.skuList.forEach((item: any, index: number) => {
        newarr.forEach((val: any, i: number) => {
          if (item.specInfo == val.specInfo) {
            //       newarr[i] = item
            Object.assign(val, item);
            arr.push(val);
          }
        });
      });
      list.value = arr;
      isedit.value = false;
    } else {
      list.value = newarr;
    }
  } else {
    list.value = newarr;
  }
}
// 切换类型
function changeTypeEnum(item: string) {
  // single-单规格商品 sku-多规格商品 package-套餐商品 weight-称重商品 coupon-团购券
  list.value = [];
  if (item == "sku") {
    tbProductSpecGet();
  } else {
    ruleForm.specId = "";
    datas.selectSpeclist = [];
    list.value = [datas.defaultSku];
  }
}
// 笛卡尔积算法
function cartesian(arr) {
  if (arr.length < 2) return arr[0] || [];
  return [].reduce.call(arr, (col, set) => {
    let res = [];
    col.forEach((c) => {
      set.forEach((s) => {
        let t = [].concat(Array.isArray(c) ? c : [c]);
        t.push(s);
        res.push(t);
      });
    });
    return res;
  });
}
// 套餐类型切换
function typeChange() {
  // ruleForm.typeEnum = 'normal'
  if (ruleForm.groupType == 0) {
    ruleForm.proGroupVo = [];
    ruleForm.proGroupVo[0] = {
      title: "",
      count: "",
      number: 1,
      goods: [],
    };
  } else {
    ruleForm.proGroupVo = [];
  }
  // this.changeTypeEnum()
}
// 获取规格列表
async function tbProductSpecGet() {
  datas.specificationsconfig = (await UserAPI4.getPage(null)) as [];
}
// 选择规格
function selectSpecHandle(e: any) {
  const selectSpec = JSON.parse(
    JSON.stringify(datas.specificationsconfig.find((item) => item.id == e).children)
  );
  for (let item in selectSpec) {
    selectSpec[item].selectSpecResult = [];
  }
  datas.selectSpeclist = selectSpec;
}
const specificationAttributeRef = ref(null);
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      // 第一张图片作为封面图
      ruleForm.coverImg = ruleForm.images[0];
      // 规格id修改
      // ruleForm.specId = specIdFunction(ruleForm.type)
      let selectTitle = false;
      ruleForm.proGroupVo.forEach((item: any) => { });
      if (selectTitle) {
        ElMessage.error("请填写组名和几选几");
        return;
      }
      // 拿到sku数据
      ruleForm.skuList = (specificationAttributeRef.value as any)?.getdata();
      // 多规格 selectSpecInfo 添加
      if (ruleForm.type == "sku") {
        let obj: any = {};
        datas.selectSpeclist.forEach((item: any) => {
          obj[item.name] = item.selectSpecResult;
        });
        ruleForm.selectSpecInfo = obj;
      } else if (ruleForm.type == "package") {
        // console.log(ruleForm, '套餐')
      }

      // 标题和几选几是否填写
      if (ruleForm.type == "package") {
        if (ruleForm.groupType == 1) {
          let selectTitle = false;
          ruleForm.proGroupVo.forEach((item: any) => {
            if (item.number == "" || item.title == "") {
              selectTitle = true;
            }
          });
          if (selectTitle) {
            ElMessage.error("请填写组名和几选几");
            return;
          }
        }
      }
      ruleForm.days = ruleForm.days.join(',')
      setTimeout(() => {
        ruleForm.days = ruleForm.days.split(",");
      }, 200);

      if (ruleForm.type == "weight") {
        ruleForm.specId = "";
      }
      if (ruleForm.id) {
        let res = await UserAPI3.update(ruleForm);
        if (res.code == 200) {
          ElMessage.success("修改成功");
        }
      } else {
        let res = await UserAPI3.addunit(ruleForm);
        if (res.code == 200) {
          ElMessage.success("添加成功");
        }
      }
      setTimeout(() => {
        closeSelectedTag({
          name: "addgoods",
          title: "新增商品",
          path: "/product/addgoods",
          fullPath: "/product/addgoods",
        });
      }, 500);
      setTimeout(() => {
        router.push({ path: "/product/index" });
      }, 1000);
    } else {
      ElMessage.error("请填写完整信息");
      console.log("error submit!", fields);
    }
  });
};

// 关闭当前窗口
function closeSelectedTag(view: TagView) {
  tagsViewStore.delView(view).then((res: any) => {
    if (tagsViewStore.isActive(view)) {
      tagsViewStore.toLastView(res.visitedViews, view);
    }
  });
}
// 规格id过滤
const specIdFunction = (type: string) => {
  if (type === "single") {
    return "";
  } else if (type === "2") {
    return 2;
  } else if (type === "3") {
    return 3;
  } else if (type === "4") {
    return 4;
  } else if (type === "5") {
    return 5;
  }
};
const resetForm = (formEl: FormInstance | undefined) => {
  closeSelectedTag({
    name: "addgoods",
    title: "新增商品",
    path: "/product/addgoods",
    fullPath: "/product/addgoods",
    affix: false,
    keepAlive: true,
    query: {},
  });
  if (!formEl) return;
  formEl.resetFields();
};
</script>
<style scoped lang="scss">
.addgoods {
  padding: 20px;
  background-color: #fff;
}

.pro_sku {
  .item {
    .row {
      display: flex;
      align-items: center;

      &:not(:first-child) {
        margin-top: 20px;
      }

      .title {
        width: 80px;
      }

      .tag {
        background-color: #f7f7fa;
        padding: 6px 12px;
        margin-right: 10px;
        border-radius: 4px;

        &.no {
          background: none;
          padding: 6px 0;
        }

        &.active {
          background-color: #46a6ff;
          color: #fff;
        }
      }
    }
  }
}

.group_wrap {
  padding: 20px;
  background-color: #f7f7fa;
  margin-bottom: 20px;
}

.showStyle:hover>.buttonstyle {
  display: block;
}

.upImgStyle {
  cursor: pointer;
  width: 148px;
  height: 148px;
  line-height: 148px;
  text-align: center;
  border: 1px dashed #ccc;
  border-radius: 1%;
  font-size: 30px;
  color: #ccc;
}

.buttonstyle {
  border-radius: 50%;
  color: #db1616;
  background-color: #fff;
  font-size: 20px;
  display: none;
  position: absolute;
  right: 0px;
  top: -10px;
  z-index: 10;
}
</style>
