<template>
  <div class="addgoods">
    <div class="form_wrap">
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="150px" class="demo-ruleForm" status-icon>
        <el-steps :active="stepsActiveName" finish-status="success" simple>
          <el-step title="基础信息" />
          <el-step title="耗材设置/关联推荐商品" />
        </el-steps>
        <div style="padding-top: 20px;">
          <!-- 基础信息 -->
          <div v-show="stepsActiveName == 0">
            <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 prop="unitId">
              <el-select v-model="ruleForm.unitId" placeholder="请选择单位" :disabled="isSyncStatus()" style="width: 330px;">
                <el-option :label="item.name" :value="item.id" v-for="item in datas.Company" :key="item.id" />
              </el-select>
              <el-button type="primary" icon="Plus" style="margin-left: 14px;"
                @click="addUnitRef.open()">添加单位</el-button>
            </el-form-item>
            <el-form-item label="商品分类" required prop="categoryId">
              <el-select v-model="ruleForm.categoryId" placeholder="请选择商品分类" :disabled="isSyncStatus()"
                style="width: 330px;">
                <el-option :label="item.name" :value="item.id" v-for="item in datas.classification" :key="item.id" />
              </el-select>
              <el-button type="primary" icon="Plus" style="margin-left: 14px;"
                @click="addCategoryRef.open()">添加分类</el-button>
            </el-form-item>
            <el-form-item label="商品分组">
              <el-select v-model="ruleForm.proGroupIds" multiple placeholder="请选择商品分组" style="width: 330px;">
                <el-option :label="item.name" :value="item.id" v-for="item in goodsGroupList" :key="item.id" />
              </el-select>
              <el-button type="primary" icon="Plus" style="margin-left: 14px;"
                @click="addGoodsGroupRef.open()">添加分组</el-button>
            </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'">
              <div class="center">
                <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-button type="primary" icon="Plus" style="margin-left: 14px;"
                  @click="addSkuModalRef?.open()">添加规格</el-button>
              </div>
            </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="重量" v-if="ruleForm.type == 'weight'">
              <el-col :span="12">
                <div style="display: block">
                  <el-input v-model="ruleForm.weight" placeholder="纯文本描述"></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-text type="info">-</el-text> <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">
              <div class="center">
                <el-switch v-model="ruleForm.isHot" :active-value="1" :inactive-value="0" />
                <el-text>推荐后，商品会展示在用户小程序端热销模块内</el-text>
              </div>
            </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>
          </div>
          <!-- 耗材设置 -->
          <div v-show="stepsActiveName == 1">
            <el-tabs v-model="tabsActiveName">
              <el-tab-pane label="耗材设置" :name="1">
                <el-form-item label="耗材列表">
                  <el-table :data="ruleForm.consList" border>
                    <el-table-column label="序号" type="index" width="60"></el-table-column>
                    <el-table-column label="耗材名称" prop="consInfoId">
                      <template v-slot="scope">
                        <el-select filterable v-model="scope.row.consInfoId" reserve-keyword placeholder="请输入关键词"
                          @change="selectionChange($event, scope.row)">
                          <el-option v-for="item in consOptions" :key="item.id" :label="item.conName"
                            :value="item.id"></el-option>
                        </el-select>
                        <!-- <div class="tips" v-if="scope.row.stockNumber">库存：{{ scope.row.stockNumber }}</div> -->
                      </template>
                    </el-table-column>
                    <el-table-column label="单位" prop="conUnit">
                      <template v-slot="scope">
                        <el-input v-model="scope.row.conUnit" readonly disabled placeholder="请选择耗材"></el-input>
                        <!-- <el-select v-model="scope.row.conUnit" reserve-keyword placeholder="请输入关键词">
                  <el-option
                    v-for="item in returnConUnits(scope.row.consInfoId)"
                    :key="item"
                    :label="item"
                    :value="item"
                  ></el-option>
                </el-select> -->
                      </template>
                    </el-table-column>
                    <el-table-column label="使用数量" prop="surplusStock" min-width="150px">
                      <template v-slot="scope">
                        <el-input-number v-model="scope.row.surplusStock" :min="0" />
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" width="100">
                      <template #header>
                        <el-button type="primary" size="small" @click="createItem">添加</el-button>
                      </template>
                      <template v-slot="scope">
                        <div class="table_btn_wrap">
                          <div class="btn sub" @click="ruleForm.consList.splice(scope.$index, 1)">
                            <el-icon>
                              <RemoveFilled />
                            </el-icon>
                          </div>
                          <!-- <div class="btn add" v-if="scope.$index == ruleForm.consList.length - 1"
                    @click="createItem(scope.row)">
                    <el-icon>
                      <CirclePlusFilled />
                    </el-icon>
                  </div> -->
                        </div>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-form-item>
                <el-form-item label="自动售罄">
                  <div class="center">
                    <el-switch v-model="ruleForm.isAutoSoldStock" :active-value="1" :inactive-value="0"></el-switch>
                    <el-text type="info">当绑定的任何一种耗材库存不足时，商品自动售罄</el-text>
                  </div>
                </el-form-item>
                <el-form-item label="退菜是否退库存">
                  <div class="column">
                    <div>
                      <el-radio-group v-model="ruleForm.refundMode">
                        <el-radio label="退菜退库存" :value="1"></el-radio>
                        <el-radio label="仅退菜不退库存" :value="2"></el-radio>
                        <el-radio label="每次询问-退菜后弹窗提示，可手动选择" :value="3"></el-radio>
                      </el-radio-group>
                    </div>
                    <div>
                      <el-text type="danger">当前店铺退菜退库存规则：{{ shopInfoTypeFilter(shopInfo.refundMode) }}</el-text>
                    </div>
                  </div>
                </el-form-item>
              </el-tab-pane>
              <el-tab-pane label="关联商品设置" :name="2">
                <el-form-item label="关联商品设置">
                  <div class="column">
                    <div class="row">
                      <div class="center">
                        <el-button type="primary" @click="selecProductDialogRef?.show()"
                          :disabled="ruleForm.relatedRecommendJson.length >= goodsListMax">添加商品</el-button>
                        <div class="tips">设置商品后，用户可以在商品详情页中看到推荐商品可拖动调整顺序，最多设置{{ goodsListMax }}个商品</div>
                      </div>
                    </div>
                    <div class="row">
                      <div id="goods_table_drag">
                        <el-table :data="ruleForm.relatedRecommendJson" border stripe row-key="id">
                          <!-- 拖拽列 -->
                          <el-table-column label="排序" width="60">
                            <template v-slot="scope">
                              <div class="drag-handle">☰</div>
                            </template>
                          </el-table-column>
                          <el-table-column label="商品图片" prop="coverImg" width="90">
                            <template v-slot="scope">
                              <el-image :src="scope.row.coverImg" style="width: 50px;height: 50px;border-radius: 4px;"
                                fit="cover"></el-image>
                            </template>
                          </el-table-column>
                          <el-table-column label="商品名称" prop="name"></el-table-column>
                          <el-table-column label="操作" width="100">
                            <template v-slot="scope">
                              <el-button link type="danger"
                                @click="ruleForm.relatedRecommendJson.splice(scope.$index, 1)">删除</el-button>
                            </template>
                          </el-table-column>
                        </el-table>
                      </div>
                    </div>
                  </div>
                </el-form-item>
              </el-tab-pane>
            </el-tabs>
          </div>
        </div>
        <el-form-item>
          <el-button type="primary" @click="nextStep" v-if="stepsActiveName == 0">下一步</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)" v-if="stepsActiveName == 1">保存</el-button>
          <el-button @click="resetForm(ruleFormRef)" v-if="stepsActiveName == 0">取消</el-button>
          <el-button @click="stepsActiveName = 0" v-if="stepsActiveName != 0">上一步</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 选择商品 -->
    <!-- <shopList ref="shopListRef" @success="selectShopRes" /> -->
    <GoodsSelect 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>
    <!-- 选择商品弹窗 -->
    <selecProductDialog ref="selecProductDialogRef" @success="selecProductSuccess" />
    <!-- 添加单位 -->
    <addUnit ref="addUnitRef" @success="getList" />
    <!-- 添加商品分类 -->
    <addCategory ref="addCategoryRef" @success="getList" />
    <!-- 添加商品分组 -->
    <addGoodsGroup ref="addGoodsGroupRef" @success="getGoodsGroupList" />
    <!-- 添加规格 -->
    <addSkuModal ref="addSkuModalRef" @success="tbProductSpecGet" />
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted, nextTick } 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 GoodsGroupAPI from "@/api/onlineShop/goodsGroupconfig";
import shopList from "@/components/mycomponents/shopList.vue";
import AddImg from "@/components/mycomponents/addImg.vue";
import { useRouter } from "vue-router";
import Sortable from "sortablejs";
import { useTagsViewStore } from "@/store";
import selecProductDialog from "@/views/marketing_center/group_booking/components/selecProductDialog.vue";
import addUnit from "../components/addUnit.vue";
import addCategory from "../components/addCategory.vue";
import addGoodsGroup from "@/views/online-shop/components/addGoodsGroup.vue";
import GoodsSelect from '@/components/GoodsSelect/index.vue'
import addSkuModal from "../components/addSkuModal.vue";

const route = useRoute();
const selecProductDialogRef = ref(null)
const goodsListMax = ref(9)
const addUnitRef = ref(null)
const consOptions = ref([])
const addCategoryRef = ref(null)
const addGoodsGroupRef = ref(null)
const addSkuModalRef = ref(null)

// let haocaiData = ref({
//   consList: [
//     {
//       productId: '',
//       consInfoId: "",
//       surplusStock: "0",
//     }
//   ]
// });

const stepsActiveName = ref(0);
const tabsActiveName = ref(1);
const stepRules = [
  'name',
  'unitId',
  'categoryId',
  'images',
]

const goodsGroupList = ref([])
async function getGoodsGroupList() {
  try {
    goodsGroupList.value = await GoodsGroupAPI.getList()
  } catch (error) {
    console.log(error);
  }
}

onMounted(() => {
  getGoodsGroupList()
})

// 校验基础信息的表单是否通过
async function nextStep() {
  try {
    await ruleFormRef.value.validateField(stepRules)
    stepsActiveName.value++
  } catch (error) {
    console.log(error);
  }
}

// 生成新商品绑定耗材关系项
function createItem(val) {
  let item = {
    productId: '',
    consInfoId: "",
    surplusStock: "",
  };
  ruleForm.consList.push(item);
}

// 商品选择耗材
function selectionChange(e, row) {
  let item = consOptions.value.find((item) => item.id == e);
  row.name = item.conName;
  row.conUnit = item.conUnit;
}

// 获取耗材列表
async function gethaocaiList() {
  try {
    let res = await UserAPI3.productconsList({ id: route.query.id });
    console.log('获取耗材列表', res);
    consOptions.value = res || [];
  } catch (error) {
    console.log(error);
  }
}

const shopInfo = ref('')

function shopInfoTypeFilter(t) {
  if (t == 1) return '跟随商品分类'
  if (t == 2) return '跟随单商品'
}

onMounted(() => {
  shopInfo.value = JSON.parse(localStorage.getItem('userInfo'))
  gethaocaiList()
  // Sortable 需要在 el-table 渲染 tbody 后初始化，尝试多次以确保 DOM 可用
  const initSortable = async () => {
    await nextTick();
    let attempts = 0;
    const maxAttempts = 8;
    const tryInit = () => {
      const el = document.querySelector("#goods_table_drag .el-table__body-wrapper tbody");
      if (!el) {
        attempts++;
        if (attempts < maxAttempts) {
          setTimeout(tryInit, 80);
        }
        return;
      }

      // 已找到表体，初始化 Sortable
      new Sortable(el as HTMLElement, {
        animation: 150,
        handle: ".drag-handle",
        ghostClass: "sortable-ghost",
        chosenClass: "sortable-chosen",
        onEnd: (e) => {
          if (e.oldIndex == null || e.newIndex == null) return;
          if (e.oldIndex === e.newIndex) return;
          const from = e.oldIndex;
          const to = e.newIndex;
          const item = ruleForm.relatedRecommendJson.splice(from, 1)[0];
          ruleForm.relatedRecommendJson.splice(to, 0, item);
          // 触发响应式更新
          ruleForm.relatedRecommendJson = ruleForm.relatedRecommendJson.slice();
          console.log("排序后的数据", ruleForm.relatedRecommendJson);
        },
      });
    };
    tryInit();
  };

  initSortable();
});

// 已选择的商品
function selecProductSuccess(res: any) {
  if (res.id == ruleForm.id) {
    ElMessage.error("不能选择当前商品");
    return;
  }

  let obj = ruleForm.relatedRecommendJson.find((item) => item.id == res.id);
  if (obj && obj.id) {
    ElMessage.error("该商品已选择");
    return;
  }
  ruleForm.relatedRecommendJson.push({ ...res });
}

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 {
  id: number | string;
  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;
  relatedRecommendJson: any[];
}
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  id: '',
  //商品名称
  name: "",
  //商品介绍
  shortTitle: "",
  // 单位id
  unitId: "",
  // 分类id
  categoryId: "",
  proGroupIds: [], // 商品分组集合
  // 封面图url
  coverImg: "",
  // 详情图urls
  images: [],
  // 商品类型
  type: "single",
  // 规格id
  specId: "",
  // 套餐类型
  groupType: 0,
  // 套餐入参
  proGroupVo: [
    {
      title: "",
      count: "",
      number: "",
      goods: [],
    },
  ],
  // sku集合
  skuList: [],
  // 重量
  weight: '',
  // 是否允许改价
  isAllowTempModifyPrice: 1,
  // 定时上下架周期
  days: ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
  useTime: ["00:00:00", "23:59:59"],
  // 开始时间
  startTime: "00:00:00",
  // 结束时间
  endTime: "23:59:59",
  // 是否上架
  isSale: "1",
  // 是否开启库存
  isStock: "1",
  // 设为推荐
  isHot: "1",
  // 库存数量
  stockNumber: 0,
  // 打包费
  packFee: 0,
  // 排序值
  sort: 1,
  selectSpecInfo: {},
  relatedRecommendJson: [], // 关联推荐商品
  consList: [], // 耗材列表
  refundMode: 1, // 退菜是否退库存 1退菜退库存 2仅退菜不退库存 3每次询问-退菜后弹窗提示
  isAutoSoldStock: 0, // 是否自动售罄
});
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;
  }

  // if (res.consList.length == 0) {
  //   ruleForm.consList.push({
  //     productId: '',
  //     consInfoId: "",
  //     surplusStock: "0",
  //   })
  // }
}
// 选择套餐商品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;
  if (ruleForm.groupType == 0) {
    (shopListRef.value as any)?.show(ruleForm.proGroupVo[0].goods || []);
  } else {
    (shopListRef.value as any)?.show(ruleForm.proGroupVo[index].goods || []);
  }
}

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)?.show();
}
// 生成多规格表体
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: 14px;

  .form_wrap {
    background-color: #fff;
    border-radius: 14px;
    padding: 14px;
  }
}

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

.drag-handle {
  cursor: move;
  display: inline-block;
  padding: 4px 8px;
  border-radius: 4px;
  background: #f0f0f0;
}

/* SortableJS classes */
.sortable-ghost {
  opacity: 0.6;
}

.sortable-chosen {
  background: #f5f7ff !important;
}

.el-table__body-wrapper tbody tr {
  transition: transform 150ms ease, background-color 150ms ease;
}

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

.column {
  flex: 1;
  display: flex;
  flex-direction: column;

  .row {
    flex: 1;
    margin-bottom: 10px;
  }
}

.center {
  display: flex;
  align-items: center;
  gap: 10px;

  .tips {
    color: #999;
    font-size: 14px;
  }
}

.header-wrap {
  padding-bottom: 20px;
}
</style>