<template>
  <div class="app-container">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="140px" label-position="left">
      <!-- <el-form-item label="商品类型" prop="typeEnum">
        <div class="shop_type_box" :class="{}">
          <div class="item" v-for="(item, index) in shopTypes" :key="index"
            :class="{ active: shopTypesActive == index }" @click="changeTypeEnum(index)">
            <div class="s_title">{{ item.label }}</div>
            <div class="intro">（{{ item.intro }}）</div>
            <div class="active_dot">
              <i class="el-icon-check"></i>
            </div>
          </div>
        </div>
      </el-form-item> -->
      <el-form-item label="商品名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入商品名称" style="width: 500px"></el-input>
      </el-form-item>
      <el-form-item label="商品介绍" prop="shortTitle">
        <el-input v-model="form.shortTitle" type="textarea" placeholder="请输入商品介绍" style="width: 500px"></el-input>
      </el-form-item>
      <el-form-item label="单位" prop="unitId">
        <el-select v-model="form.unitId" placeholder="请选择单位" style="width: 500px" @change="selectUnitt">
          <el-option :label="item.name" :value="item.id" v-for="item in units" :key="item.id"></el-option>
        </el-select>
        <el-button type="primary" plain icon="el-icon-plus" @click="$refs.addUnitRef.show()">添加单位</el-button>
        <addUnit ref="addUnitRef" @success="tbShopUnit" />
      </el-form-item>
      <el-form-item label="团购券分类" prop="groupCategoryId" v-if="form.typeEnum == 'group'">
        <el-table :data="form.groupCategoryId" border style="width: 500px" v-if="form.groupCategoryId.length">
          <el-table-column label="名称" prop="name"></el-table-column>
          <el-table-column label="操作" width="160">
            <template v-slot="scope">
              <el-button type="text" @click="form.groupCategoryId.splice(scope.$index, 1)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="text" @click="$refs.groupTypeList.show(form.groupCategoryId)">添加团购券分类</el-button>
      </el-form-item>
      <el-form-item label="商品分类" prop="categoryId" v-else>
        <el-select v-model="form.categoryId" placeholder="请选择商品分类" style="width: 500px">
          <el-option :label="item.name" :value="item.id" v-for="item in categorys" :key="item.id"></el-option>
        </el-select>
        <el-button type="primary" plain icon="el-icon-plus" @click="$refs.addClassifyRef.show()">添加分类</el-button>
        <addClassify ref="addClassifyRef" @success="tbShopCategoryGet" />
      </el-form-item>
      <el-form-item label="商品图片" prop="coverImg">
        <div style="display: flex; flex-wrap: wrap">
          <div v-for="(item, index) in imgList" :key="index" style="position: relative" class="showStyle">
            <i class="el-icon-error buttonstyle" @click="deleteEvent(item)"></i>
            <img style="width: 148px; height: 148px; margin-right: 6px" class="imgStyle" :key="item.id" :src="item.url"
              alt="" />
          </div>
          <div class="upImgStyle" @click="$refs.addImg.show()">+</div>
        </div>
        <!-- <uploadImg ref="uploadImg" :limit="9" @success="uploadSuccess" @remove="uploadRemove" /> -->
        <div class="tips">注：第一张图为商品封面图，图片尺寸为750×750</div>
        <!-- <el-button type="primary" plain icon="el-icon-plus" @click="$refs.addImg.show()">选择图片</el-button> -->
      </el-form-item>
      <el-form-item label="显示/隐藏" prop="showType">
        <el-checkbox-group v-model="form.showType">
          <el-checkbox label="table">堂食</el-checkbox>
          <el-checkbox label="dine">自取</el-checkbox>
          <el-checkbox label="delivery">配送</el-checkbox>
          <el-checkbox label="express">快递</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="商品类型">
        <el-radio-group v-model="form.type" @change="typeChange">
          <el-radio label="normal">普通商品</el-radio>
          <el-radio label="package">套餐类型</el-radio>
          <el-radio label="weigh">称重</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="规格类型" v-if="form.type == 'normal'">
        <el-radio-group v-model="form.typeEnum" @change="changeTypeEnum">
          <el-radio label="normal">单规格</el-radio>
          <el-radio label="sku">多规格</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="套餐商品" v-if="form.type == 'package'">
        <div class="head-container">
          <el-radio-group v-model="form.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="form.groupType == 0">
          <el-table border :data="item.goods" v-for="(item, index) in form.proGroupVo" :key="index">
            <el-table-column label="名称" prop="proName"></el-table-column>
            <el-table-column label="规格" prop="skuName">
              <!-- <template slot-scope="scope">
                <template v-if="scope.row.typeEnum == '多规格'">
                  <template v-if="scope.row.skuName">
                    {{ scope.row.skuName }}
                  </template>
                  <span class="tips" v-else>请设置规格</span>
                </template>
                <template v-else>
                  单规格
                </template>
              </template> -->
            </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 slot="header" slot-scope="scope">
                <el-button type="primary"
                  @click="$refs.shopListRef.show([...form.proGroupVo[index].goods])">添加商品</el-button>
              </template>
              <template slot-scope="scope">
                <el-button type="text" :disabled="scope.row.typeEnum != '多规格'"
                  @click="showSelectSkuHandle(scope.row, scope.$index, index)">设置规格</el-button>
                <el-button type="text" @click="form.proGroupVo[index].goods.splice(scope.$index, 1)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div v-if="form.groupType == 1">
          <div class="group_wrap" v-for="(item, index) in form.proGroupVo" :key="index">
            <el-form inline :model="item">
              <el-form-item label="规格组名">
                <el-input v-model="item.title" />
              </el-form-item>
              <el-form-item :label="`本组菜品${item.goods.length}选`">
                <el-input v-model="item.number" />
              </el-form-item>
              <el-form-item>
                <el-button @click="form.proGroupVo.splice(index, 1)">删除</el-button>
              </el-form-item>
            </el-form>
            <div>
              <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" />
                  </template>
                </el-table-column>
                <el-table-column width="150">
                  <template slot="header" slot-scope="scope">
                    <el-button type="primary"
                      @click="$refs.shopListRef.show([...form.proGroupVo[index].goods]); addGroupIndex = index">添加商品</el-button>
                  </template>
                  <template slot-scope="scope">
                    <el-button type="text" :disabled="scope.row.typeEnum != '多规格'"
                      @click="showSelectSkuHandle(scope.row, scope.$index, index)">设置规格</el-button>
                    <el-button type="text" @click="form.proGroupVo[index].goods.splice(scope.$index, 1)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
          <el-button type="primary" @click="$refs.shopListRef.show(); addGroupIndex = false">添加套餐组</el-button>
        </div>
      </el-form-item>
      <el-form-item label="规格属性" v-if="form.typeEnum != 'sku'">
        <el-table :data="form.skuList" border>
          <el-table-column label="售价" prop="salePrice">
            <template v-slot="scope">
              <el-input-number size="mini" @change="priceFormat(scope.row, 'salePrice')"
                @blur="priceFormat(scope.row, 'salePrice')" v-model="scope.row.salePrice"
                controls-position="right"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="会员价" prop="memberPrice">
            <template v-slot="scope">
              <el-input-number @change="priceFormat(scope.row, 'memberPrice')"
                @blur="priceFormat(scope.row, 'memberPrice')" v-model="scope.row.memberPrice"
                controls-position="right"></el-input-number>
            </template>
          </el-table-column>
          <!-- <el-table-column label="成本价" prop="costPrice">
            <template v-slot="scope">
              <el-input-number
                @change="priceFormat(scope.row, 'costPrice')"
                @blur="priceFormat(scope.row, 'costPrice')"
                v-model="scope.row.costPrice"
                controls-position="right"
              ></el-input-number>
            </template>
          </el-table-column> 
          <el-table-column label="原价" prop="originPrice">
            <template v-slot="scope">
              <el-input-number
                @change="priceFormat(scope.row, 'originPrice')"
                @blur="priceFormat(scope.row, 'originPrice')"
                v-model="scope.row.originPrice"
                controls-position="right"
              ></el-input-number>
            </template>
          </el-table-column>-->
          <el-table-column label="起售数量" prop="suit">
            <template slot-scope="scope">
              <el-input-number @change="priceFormat(scope.row, 'suit')" @blur="priceFormat(scope.row, 'suit')" :min="1"
                v-model="scope.row.suit" controls-position="right"></el-input-number>
            </template>
          </el-table-column>
          <!-- <el-table-column label="库存数量" prop="stockNumber">
            <template v-slot="scope">
              <el-input-number
                @change="priceFormat(scope.row, 'stockNumber')"
                @blur="priceFormat(scope.row, 'stockNumber')"
                v-model="scope.row.stockNumber"
                :disabled="!!form.id"
                controls-position="right"
              ></el-input-number>
            </template>
          </el-table-column> -->
          <el-table-column label="分销金额" prop="firstShared">
            <template v-slot="scope">
              <el-input-number @change="priceFormat(scope.row, 'firstShared')"
                @blur="priceFormat(scope.row, 'firstShared')" v-model="scope.row.firstShared"
                controls-position="right"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="商品条码">
            <template v-slot="scope">
              <el-input v-model="scope.row.barCode" disabled></el-input>
            </template>
          </el-table-column>
        </el-table>
        <!-- <div class="tips" v-if="form.isShowMall">
          注：小程序商城必须设置库存数量大于0
        </div> -->
      </el-form-item>
      <template v-if="form.typeEnum == 'group'">
        <el-form-item label="使用日期说明" prop="notices.dateUsed">
          <el-input type="textarea" v-model="form.notices.dateUsed" :autosize="{ minRows: 3, maxRows: 10 }"
            style="width: 500px" placeholder="请输入使用日期说明"></el-input>
        </el-form-item>
        <el-form-item label="可用时间说明" prop="notices.availableTime">
          <el-input type="textarea" v-model="form.notices.availableTime" :autosize="{ minRows: 3, maxRows: 10 }"
            style="width: 500px" placeholder="请输入可用时间说明
"></el-input>
        </el-form-item>
        <el-form-item label="预约方式" prop="notices.bookingType">
          <el-input type="textarea" v-model="form.notices.bookingType" :autosize="{ minRows: 3, maxRows: 10 }"
            style="width: 500px" placeholder="请输入预约方式
"></el-input>
        </el-form-item>
        <el-form-item label="退款说明" prop="notices.refundPolicy">
          <el-input type="textarea" v-model="form.notices.refundPolicy" :autosize="{ minRows: 3, maxRows: 10 }"
            style="width: 500px" placeholder="请输入退款说明
"></el-input>
        </el-form-item>
        <el-form-item label="团购价说明">
          <el-input type="textarea" v-model="form.notices.groupPurInfo" :autosize="{ minRows: 3, maxRows: 10 }"
            style="width: 500px" placeholder="请输入团购价说明"></el-input>
        </el-form-item>
        <el-form-item label="门市价/划线价说明">
          <el-input type="textarea" v-model="form.notices.marketPriceInfo" :autosize="{ minRows: 3, maxRows: 10 }"
            style="width: 500px" placeholder="请输入门市价/划线价说明"></el-input>
        </el-form-item>
        <el-form-item label="折扣说明">
          <el-input type="textarea" v-model="form.notices.discountInfo" :autosize="{ minRows: 3, maxRows: 10 }"
            style="width: 500px" placeholder="请输入折扣说明"></el-input>
        </el-form-item>
        <el-form-item label="发票说明">
          <el-input type="textarea" v-model="form.notices.invoiceInfo" :autosize="{ minRows: 3, maxRows: 10 }"
            style="width: 500px" placeholder="请输入发票说明"></el-input>
        </el-form-item>
        <el-form-item label="使用规则">
          <Editor :minHeight="200" :value="form.notices.usageRules" v-model="form.notices.usageRules" />
        </el-form-item>
      </template>
      <el-form-item label="选择规格" v-if="form.type == 'normal' && form.typeEnum == 'sku'">
        <el-select v-model="form.specId" placeholder="请选择规格" style="width: 500px" @change="selectSpecHandle">
          <el-option :label="item.name" :value="item.id" v-for="item in specList" :key="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="item.name" v-if="selectSpec.length" v-for="item in selectSpec" :key="item.name">
        <el-checkbox-group v-model="item.selectSpecResult" @change="selectSpecResultChange">
          <el-checkbox :label="item" v-for="(item, index) in item.value" :key="index"></el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item v-if="selectSpecResult && form.typeEnum == 'sku'">
        <el-table :data="form.skuList" border>
          <el-table-column :label="item.label" :prop="item.value" v-for="(item, index) in specTableHeaders"
            :key="index">
          </el-table-column>
          <el-table-column label="图片" prop="coverImg" width="80">
            <template v-slot="scope">
              <uploadImg v-if="!scope.row.coverImg" type="text" :limit="1"
                @success="uploadImgSucess($event, scope.row)" />
              <el-image style="width: 30px; height: 30px" :src="scope.row.coverImg" v-else />
              <i class="el-icon-error" v-if="scope.row.coverImg" @click="scope.row.coverImg = ''" />
            </template>
          </el-table-column>
          <el-table-column label="售价" prop="salePrice">
            <template slot="header" slot-scope="scope">
              <span>售价</span>
              <i class="icon el-icon-edit" @click="batchNumber('salePrice')"></i>
            </template>
            <template slot-scope="scope">
              <el-input-number @change="priceFormat(scope.row, 'salePrice')" @blur="priceFormat(scope.row, 'salePrice')"
                v-model="scope.row.salePrice" controls-position="right"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="会员价" prop="memberPrice">
            <template slot="header" slot-scope="scope">
              <span>会员价</span>
              <i class="icon el-icon-edit" @click="batchNumber('memberPrice')"></i>
            </template>
            <template slot-scope="scope">
              <el-input-number @change="priceFormat(scope.row, 'memberPrice')"
                @blur="priceFormat(scope.row, 'memberPrice')" v-model="scope.row.memberPrice"
                controls-position="right"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="成本价" prop="costPrice">
            <template slot="header" slot-scope="scope">
              <span>成本价</span>
              <i class="icon el-icon-edit" @click="batchNumber('costPrice')"></i>
            </template>
            <template slot-scope="scope">
              <el-input-number @change="priceFormat(scope.row, 'costPrice')" @blur="priceFormat(scope.row, 'costPrice')"
                v-model="scope.row.costPrice" controls-position="right"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="原价" prop="originPrice">
            <template slot="header" slot-scope="scope">
              <span>原价</span>
              <i class="icon el-icon-edit" @click="batchNumber('originPrice')"></i>
            </template>
            <template slot-scope="scope">
              <el-input-number @change="priceFormat(scope.row, 'originPrice')"
                @blur="priceFormat(scope.row, 'originPrice')" v-model="scope.row.originPrice"
                controls-position="right"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="起售数量" prop="suit">
            <template slot="header" slot-scope="scope">
              <span>起售数量</span>
              <i class="icon el-icon-edit" @click="batchNumber('suit')"></i>
            </template>
            <template slot-scope="scope">
              <el-input-number @change="priceFormat(scope.row, 'originsuitrice')" @blur="priceFormat(scope.row, 'suit')"
                v-model="scope.row.suit" controls-position="right" :min="1"></el-input-number>
            </template>
          </el-table-column>
          <!-- <el-table-column label="库存数量" prop="stockNumber">
            <template slot="header" slot-scope="scope">
              <span>库存数量</span>
              <i
                class="icon el-icon-edit"
                @click="batchNumber('stockNumber')"
                v-if="!form.id"
              ></i>
            </template>
            <template slot-scope="scope">
              <el-input-number
                @change="priceFormat(scope.row, 'stockNumber')"
                @blur="priceFormat(scope.row, 'stockNumber')"
                v-model="scope.row.stockNumber"
                :disabled="!!scope.row.id"
                controls-position="right"
              ></el-input-number>
            </template>
          </el-table-column> -->
          <el-table-column label="分销金额" prop="firstShared">
            <template slot="header" slot-scope="scope">
              <span>分销金额</span>
              <i class="icon el-icon-edit" @click="batchNumber('firstShared')"></i>
            </template>
            <template slot-scope="scope">
              <el-input-number @change="priceFormat(scope.row, 'firstShared')"
                @blur="priceFormat(scope.row, 'firstShared')" v-model="scope.row.firstShared"
                controls-position="right"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="商品条码">
            <template v-slot="scope">
              <el-input v-model="scope.row.barCode" disabled></el-input>
            </template>
          </el-table-column>
          <!-- <el-table-column label="操作" width="80">
            <template v-slot="scope">
              <el-button
                type="text"
                @click="form.skuList.splice(scope.$index, 1)"
                >删除</el-button
              >
            </template>
          </el-table-column> -->
        </el-table>
        <!-- <div class="tips" v-if="form.isShowMall">
          注：小程序商城必须设置库存数量大于0
        </div> -->
      </el-form-item>
      <el-form-item label="重量">
        <el-input v-model="form.weight" style="width: 250px;">
          <template slot="append">千克</template>
        </el-input>
        <div class="tips">用于快递或配送运费计重</div>
      </el-form-item>
      <el-form-item label="是否允许临时改价">
        <el-radio-group v-model="form.isTempPrice">
          <el-radio label="1">允许</el-radio>
          <el-radio label="0">不允许</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="每日销量上限">
        <el-input-number v-model="form.dayLimit" :min="0" />
      </el-form-item>
      <el-form-item label="每单限购">
        <el-input-number v-model="form.singleOrderLimit" :min="0" />
      </el-form-item>
      <el-form-item label="每人限购">
        <el-input-number v-model="form.singlePeopleLimit" :min="0" />
      </el-form-item>
      <el-form-item label="定时上下架" style="width: 100%;">
        <el-checkbox-group v-model="form.days">
          <el-checkbox v-for="(item, index) in couponEnum.cycle" :key="item.value" :label="item.value">
            {{ item.label }}
          </el-checkbox>
        </el-checkbox-group>
        <el-time-picker v-model="useTime" is-range range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
          :default-time="['00:00:00', '23:59:59']" value-format="HH:mm" format="HH:mm" @change="useTimeChange" />
      </el-form-item>
      <template v-if="form.typeEnum != 'group'">
        <!-- <el-form-item label="上架区域">
          <div class="shop_type_box">
            <div class="item" :class="{ active: form.isShowCash }" @click="areaChange('isShowCash')">
              <div class="s_title">收银台</div>
              <div class="active_dot">
                <i class="el-icon-check"></i>
              </div>
            </div>
            <div class="item" :class="{ active: form.isShowMall }" @click="areaChange('isShowMall')">
              <div class="s_title">小程序商城</div>
              <div class="active_dot">
                <i class="el-icon-check"></i>
              </div>
            </div>
          </div>
        </el-form-item> -->
        <el-form-item label="上架">
          <el-switch v-model="form.isGrounding" :active-value="1" :inactive-value="0"></el-switch>
        </el-form-item>
        <el-form-item label="库存开关">
          <el-switch v-model="form.isStock" :active-value="1" :inactive-value="0"></el-switch>
          <div class="tips">注：关闭则不计算出入库数据</div>
        </el-form-item>
        <el-form-item label="设为推荐">
          <el-switch v-model="form.isHot" :active-value="1" :inactive-value="0"></el-switch>
        </el-form-item>
        <el-form-item label="库存数量" v-if="form.isStock">
          <el-input-number @change="priceFormat(form, 'stockNumber')" @blur="priceFormat(form, 'stockNumber')"
            v-model="form.stockNumber" controls-position="right"></el-input-number>
        </el-form-item>
        <!-- <el-form-item label="标签打印">
          <el-switch v-model="form.enableLabel" :active-value="1" :inactive-value="0"></el-switch>
          <div class="tips">开启后: 收银完成后会自动打印对应数量的标签数</div>
        </el-form-item>-->
        <el-form-item label="打包费">
          <el-input-number @change="priceFormat(form, 'packFee')" @blur="priceFormat(form, 'packFee')"
            v-model="form.packFee" controls-position="right"></el-input-number>
          <div class="tips">
            单份商品打包费。注：店铺开启外卖模式下该数据才生效
          </div>
        </el-form-item>
        <!-- <el-form-item label="虚拟销量">
          <el-input-number @change="priceFormat(form, 'baseSalesNumber')" @blur="priceFormat(form, 'baseSalesNumber')"
            v-model="form.baseSalesNumber" controls-position="right"></el-input-number>
        </el-form-item> -->
      </template>
      <el-form-item label="排序" v-if="form.id">
        <el-input-number v-model="form.sort" controls-position="right" :min="0"></el-input-number>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" v-loading="loading" @click="submitHandle">确定</el-button>
        <el-button @click="$router.back()">取消</el-button>
      </el-form-item>
    </el-form>
    <el-dialog title="批量修改" width="400px" :visible.sync="showBatchModal">
      <el-form :model="batchNumberForm">
        <el-form-item>
          <el-input-number @change="priceFormat(batchNumberForm, 'batchNumber')"
            @blur="priceFormat(batchNumberForm, 'batchNumber')" v-model="batchNumberForm.batchNumber"
            controls-position="right" style="width: 100%"></el-input-number>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showBatchModal = false">取 消</el-button>
        <el-button type="primary" @click="batchNumberFormConfirm">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 选择团购券分类 -->
    <!-- <groupTypeList ref="groupTypeList" @success="(res) => (form.groupCategoryId = res)" /> -->
    <!-- 选择图片 -->
    <addImg ref="addImg" @successEvent="successEvent"></addImg>
    <!-- 选择商品 -->
    <shopList ref="shopListRef" @success="selectShopRes" />
    <el-dialog :title="selectSkuItem.proName" :visible.sync="showSelectSku">
      <div class="pro_sku">
        <div class="item">
          <!-- <div class="row">
            <div class="title">规格</div>
            <div class="tag no">温度</div>
          </div> -->
          <div class="row">
            <div class="title">选项值</div>
            <div class="tag" :class="{ active: item.active }" v-for="(item, index) in selectSkuItem.skuList"
              :key="item.id" @click="selectSkuHandle(item, index)">
              {{ item.specSnap }}
            </div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showSelectSku = false">取 消</el-button>
        <el-button type="primary" :disabled="selectSkuConfirmDisabled" @click="showSelectSkuConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Editor from "@/components/Editor";
import {
  tbShopUnit,
  tbShopCategoryGet,
  tbProductPost,
  tbProductSpecGet,
  tbProductGetDetail,
  tbProductPut,
} from "@/api/shop";
import addUnit from "./components/addUnit";
import addImg from "./components/addImages.vue";
import addClassify from "./components/addClassify";
import shopList from "@/components/shopList";
import groupTypeList from "@/components/groupTypeList";
import uploadImg from "@/components/uploadImg";
import settings from "@/settings";
import dayjs from "dayjs";
import { RandomNumBoth } from "@/utils";
import { formatPrice } from "@/utils/format";
import couponEnum from '@/views/coupon_manage/couponEnum.js'

export default {
  components: {
    addUnit,
    addClassify,
    uploadImg,
    shopList,
    groupTypeList,
    Editor,
    addImg,
  },
  name: 'add_shop',
  data() {
    const validatordateUsed = (rule, value, callback) => {
      if (!this.form.notices.dateUsed) {
        console.log("this.form.notices.dateUsed", this.form.notices.dateUsed);
        callback(new Error("请输入可用时间说明"));
      } else {
        callback();
      }
    };
    const validateCoverImg = (rule, value, callback) => {
      if (!this.form.images.length) {
        callback(new Error("请上传商品图片"));
      } else {
        callback()
      }
    }
    return {
      couponEnum,
      shopTypesActive: 0,
      shopTypes: settings.typeEnum,
      specTableHeaders: [],
      specTableBodys: [],
      specId: "",
      specList: [],
      selectSpec: [],
      selectSpecResult: false,
      defaultSku: {
        salePrice: undefined,
        memberPrice: undefined,
        costPrice: undefined,
        originPrice: undefined,
        // stockNumber: undefined,
        firstShared: 0,
        barCode: `${localStorage.getItem("shopId")}${dayjs().valueOf()}`,
        isGrounding: 1,
        productId: this.$route.query.goods_id ? this.$route.query.goods_id : "",
        shopId: localStorage.getItem("shopId"),
        suit: 0,
      },
      tableAddShopIndex: null,
      isEditor: false,
      loading: false,
      originSkuList: [],
      showSelectSku: false,
      selectSkuItem: {
        skuList: []
      },
      selectSkuTableIndex: 0,
      selectSkuConfirmIndex: 0,
      selectSkuConfirmDisabled: true,
      addGroupIndex: false,
      form: {
        id: "",
        type: 'normal',
        typeEnum: "normal",
        groupType: '0',
        name: "",
        shortTitle: "", //商品介绍
        unitId: "",
        unitName: "",
        categoryId: "", // 商品分类id
        coverImg: "",
        images: [],
        shopId: localStorage.getItem("shopId"),
        showType: ['table'],
        lowPrice: "",
        skuList: [],
        isShowMall: 1,
        isShowCash: 1,
        isStock: 0,
        packFee: 0,
        specId: "",
        baseSalesNumber: 0,
        sort: 0,
        proGroupVo: [
          {
            title: '',
            count: '',
            number: '',
            goods: []
          }
        ],
        groupSnap: [],
        specInfo: [],
        selectSpec: [],
        specTableHeaders: [],
        skuSnap: "",
        groupCategoryId: [],
        notices: {
          availableTime: "",
          bookingType: "",
          dateUsed: "",
          discountInfo: "",
          groupPurInfo: "",
          invoiceInfo: "",
          marketPriceInfo: "",
          platformTips: "",
          refundPolicy: "",
          usageRules: "",
        },
        stockNumber: 0,
        isHot: 1,
        isGrounding: 1,
        isTempPrice: '1',
        dayLimit: 0,
        singleOrderLimit: 0,
        singlePeopleLimit: 0,
        weight: '',
        days: [],
        startTime: '',
        endTime: ''
      },
      useTime: ['', ''],
      imgList: [],
      rules: {
        typeEnum: [
          {
            required: true,
          },
        ],
        showType: [
          {
            required: true,
            trigger: "change",
            message: "至少选择一项",
          }
        ],
        name: [
          {
            required: true,
            trigger: "blur",
            message: "请输入商品名称",
          },
        ],
        coverImg: [
          {
            required: true,
            trigger: "change",
            validator: validateCoverImg,
            message: "请上传商品图片",
          }
        ],
        unitId: [
          {
            required: true,
            trigger: "change",
            message: "请选择单位",
          },
        ],
        categoryId: [
          {
            required: true,
            trigger: "change",
            message: "请选择商品分类",
          },
        ],
        groupCategoryId: [
          {
            required: true,
            trigger: "change",
            message: "请选择团购券分类",
          },
        ],
        "notices.dateUsed": [
          {
            required: true,
            trigger: "blur",
            message: "请输入使用日期说明",
          },
        ],
        "notices.availableTime": [
          {
            required: true,
            trigger: "blur",
            message: "请输入可用时间说明",
          },
        ],
        "notices.bookingType": [
          {
            required: true,
            trigger: "blur",
            message: "请输入预约方式",
          },
        ],
        "notices.refundPolicy": [
          {
            required: true,
            trigger: "blur",
            message: "请输入退款说明",
          },
        ],
      },
      units: [],
      categorys: [],
      // 批量修改规格
      showBatchModal: false,
      batchNumberKey: "",
      batchNumberForm: {
        batchNumber: 0,
      },
      routequery: ''
    };
  },
  mounted() {
    this.tbShopUnit();
    this.tbShopCategoryGet();
    this.changeTypeEnum(0);
    if (this.$route.query.goods_id) {
      this.tbProductGetDetail();
    }
  },
  watch: {
    // 监听路由对象中的参数变化
    $route(to, from) {
      console.log(to.query.goods_id)
      if (to.query.goods_id) {
        if (this.routequery == to.query.goods_id) {
          return false;
        } else {
          this.tbProductGetDetail();
        }
        this.routequery = to.query.goods_id
      }
    }
  },
  methods: {
    useTimeChange(e) {
      this.form.startTime = e[0]
      this.form.endTime = e[1]
    },
    // 套餐类型切换
    typeChange() {
      this.form.typeEnum = 'normal'
      if (this.form.groupType == 0) {
        this.$set(this.form.proGroupVo, 0, {
          title: '',
          count: '',
          number: 1,
          goods: []
        })
      } else {
        this.form.proGroupVo = []
      }
      this.changeTypeEnum()
    },
    // 确认套餐商品设置规格
    showSelectSkuConfirm() {
      let item = this.selectSkuItem.skuList.filter(item => item.active)

      this.$set(this.form.proGroupVo[this.selectSkuTableIndex].goods, this.selectSkuConfirmIndex, { ...this.form.proGroupVo[this.selectSkuTableIndex].goods[this.selectSkuConfirmIndex], skuId: item[0].id })
      this.$set(this.form.proGroupVo[this.selectSkuTableIndex].goods, this.selectSkuConfirmIndex, { ...this.form.proGroupVo[this.selectSkuTableIndex].goods[this.selectSkuConfirmIndex], skuName: item[0].specSnap })

      this.showSelectSku = false
      // console.log(this.form.proGroupVo.goods[this.selectSkuConfirmIndex]
    },
    // 选择套餐商品sku
    selectSkuHandle(item, index) {
      // 把所有的设置为false
      this.selectSkuItem.skuList.map((item, index) => {
        let nitem = { ...item }
        nitem.active = false
        this.$set(this.selectSkuItem.skuList, index, nitem)
      })

      if (item.active) {
        item.active = false
        this.$set(this.selectSkuItem.skuList, index, { ...item })
      } else {
        item.active = true
        this.$set(this.selectSkuItem.skuList, index, { ...item })
      }

      let arr = this.selectSkuItem.skuList.filter(item => item.active)

      if (arr.length) {
        this.selectSkuConfirmDisabled = false
      } else {
        this.selectSkuConfirmDisabled = true
      }
    },
    // 显示套餐商品设置规格
    showSelectSkuHandle(row, index, tabIndex) {
      this.selectSkuTableIndex = tabIndex
      this.selectSkuConfirmIndex = index
      this.showSelectSku = true

      let obj = { ...row }

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

      this.selectSkuItem = obj
    },
    uploadImgSucess(res, item) {
      console.log(res);
      console.log(item);
      item.coverImg = res[0];
    },
    successEvent(d) {
      this.form.images.push(d[0].url);
      this.imgList.push(d[0]);
      // if (this.$refs.uploadImg.fileList.length < 9) {
      //   d.forEach(item => {
      //     item.uid = item.id
      //     item.url = item.url
      //     this.form.images.push(item.url);
      //   })
      //   this.$refs.uploadImg.fileList.push(...d)
      //   console.log(this.$refs.uploadImg.fileList, '调试1')
      // } else {
      //   this.$notify.error({
      //     title: '错误',
      //     message: '最多选择9张图片'
      //   });
      // }
    },
    priceFormat(item, key) {
      const messageheight = 48;
      const offset = window.innerHeight / 2 - messageheight / 2 - 100;
      this.$nextTick(() => {
        const min = 0;
        const max = 100000000;
        const newval = formatPrice(item[key], min, max, true);
        console.log(newval);
        if (typeof newval !== "number") {
          item[key] = newval.value;
          this.$message({
            offset,
            message: `请输入${min}到${max}范围内的数字`,
            type: "error",
          });
        } else {
          item[key] = newval;
        }
      });
    },

    deleteEvent(d) {
      let index = this.imgList.findIndex((ele) => ele.url == d.url);
      this.imgList.splice(index, 1);
    },
    // 删除分组商品
    delGoods(goods, index, $index) {
      goods.splice(index, 1);
      if (!goods.length) {
        this.form.groupSnap.splice($index, 1);
      }
    },
    // 修改商家区域
    areaChange(key) {
      if (this.form[key] == 1) {
        this.form[key] = 0;
      } else {
        this.form[key] = 1;
      }
    },
    selectUnitt(e) {
      this.form.unitName = this.units.find((item) => item.id == e).name;
    },
    // 批量修改规格
    batchNumber(key) {
      this.batchNumberKey = key;
      this.showBatchModal = true;
    },
    // 确认批量修改规格
    batchNumberFormConfirm() {
      console.log(this.form.skuList);
      this.form.skuList.map((item, index) => {
        //解决vue2列表数据更新视图未变化问题
        let newitem = { ...item };
        newitem[this.batchNumberKey] = this.batchNumberForm.batchNumber;

        this.$set(this.form.skuList, index, { ...newitem });
        // item[this.batchNumberKey] = this.batchNumberForm.batchNumber;
      });
      this.showBatchModal = false;
      this.batchNumberForm.batchNumber = 0;
    },
    // 商品详情
    async tbProductGetDetail() {
      try {
        const res = await tbProductGetDetail(this.$route.query.goods_id);

        // 赋值商品类型
        this.changeTypeEnum(
          this.shopTypes.findIndex((item) => item.typeEnum == res.typeEnum)
        );
        this.specTableHeaders = JSON.parse(res.specTableHeaders);
        this.selectSpec = JSON.parse(res.selectSpec);
        // 初始化上传图片
        // this.$refs.uploadImg.fileList = res.images.map(item => {
        //   return {
        //     url: item
        //   };
        // });
        this.imgList = res.images.map((item) => {
          return {
            url: item,
          };
        });

        res.days = res.days.split(',')
        res.showType = res.showType.split(',')
        res.isTempPrice = JSON.stringify(res.isTempPrice)

        this.form = res;

        this.useTime = [res.startTime, res.endTime]

        if (res.typeEnum == "sku") {
          let skuList = [...res.skuList];
          let specInfo = JSON.parse(res.specInfo);
          this.isEditor = true;
          this.form.skuList = skuList.map((item, index) => {
            specInfo[index].id = item.id;
            specInfo[index].productId = item.productId;
            specInfo[index].realSalesNumber = item.realSalesNumber;
            specInfo[index].shopId = item.shopId;
            specInfo[index].warnLine = item.warnLine;
            specInfo[index].suit = item.suit;
            specInfo[index].stockNumber = item.stockNumber;
            specInfo[index].isGrounding = item.isGrounding;
            specInfo[index].salePrice = item.salePrice;
            specInfo[index].memberPrice = item.memberPrice;
            specInfo[index].costPrice = item.costPrice;
            specInfo[index].originPrice = item.originPrice;
            specInfo[index].firstShared = item.firstShared;
            return specInfo[index];
          });
          console.log(this.form.skuList);
          this.originSkuList = [...this.form.skuList];
          this.selectSpecResult = true;
        }
      } catch (error) {
        console.log(error);
      }
    },

    // 提交
    submitHandle() {
      console.log(this.form);
      // return
      if (this.form.type == 'normal') {
        // 如果找到undefined，立即停止搜索并返回true
        const hasUndefined = this.form.skuList.some(obj => {
          for (const key in obj) {
            if (this.form.typeEnum == 'normal') {//单规格判断
              if (obj['salePrice'] == undefined || obj['memberPrice'] == undefined) {
                return true;
              }
            } else {//多规格判断  
              if (obj['salePrice'] == undefined || obj['memberPrice'] == undefined || obj['costPrice'] == undefined || obj['originPrice'] == undefined) {
                return true;
              }
            }
          }
          return false;
        });
        if (hasUndefined) {
          this.$message({
            message: "请完善规格属性的参数！",
            type: "warning",
          });
          return false;
        }
      }

      let arr = [];
      this.imgList.forEach((ele) => {
        arr.push(ele.url);
      });
      this.$refs.formRef.validate(async (faild) => {
        try {
          if (faild) {
            this.loading = true;
            this.form.images = arr;
            this.form.lowPrice =
              this.form.skuList.length && this.form.skuList[0].salePrice;
            this.form.coverImg = this.form.images[0];
            this.form.selectSpec = JSON.stringify(this.selectSpec);
            this.form.specTableHeaders = JSON.stringify(this.specTableHeaders);
            this.form.specInfo = JSON.stringify(this.form.skuList);
            // this.form.skuList[0].costPrice = 0
            this.form.skuList[0].originPrice = this.form.skuList[0].salePrice

            this.form.showType = this.form.showType.join(',')
            this.form.days = this.form.days.join(',')

            if (this.form.id) {
              await tbProductPut(this.form);
            } else {
              await tbProductPost(this.form);
            }
            this.$notify({
              title: "成功",
              message: `${this.form.id ? "编辑" : "添加"}成功`,
              type: "success",
            });
            this.$router.back();
            this.loading = false;
          }
        } catch (error) {
          this.loading = false;
          console.log(error);
        }
      });
    },
    // 给分组添加商品
    tableAddShop(index, goods) {
      this.tableAddShopIndex = index;
      this.$refs.shopListRef.show([...goods]);
    },
    // 分组选择商品
    selectShopRes(res) {
      let newres = res.map(item => {
        item.proId = item.id
        item.proName = item.name
        item.price = item.lowPrice
        item.skuId = ''
        item.skuName = ''
        item.number = 1
        return item
      })
      if (this.form.groupType == 0) {
        let obj = {
          title: '',
          count: newres.length,
          number: '',
          goods: newres
        }
        this.form.proGroupVo = [{ ...obj }]
      } else {
        if (this.addGroupIndex !== false) {
          this.form.proGroupVo[this.addGroupIndex].goods = newres
        } else {
          let arr = [...this.form.proGroupVo]
          arr.push({
            title: '',
            count: newres.length,
            number: '',
            goods: newres
          })
          this.form.proGroupVo = [...arr]
        }
      }
    },
    // 切换类型
    changeTypeEnum(index) {
      // if (this.form.id) return;
      // this.shopTypesActive = index;
      // const typeEnum = this.shopTypes[index].typeEnum;
      // this.form.typeEnum = typeEnum;
      if (this.form.typeEnum == "sku") {
        this.form.skuList = [];
        this.tbProductSpecGet();
      } else {
        this.specId = "";
        this.form.specId = "";
        this.selectSpec = [];
        this.selectSpecResult = "";
        this.form.skuList = [JSON.parse(JSON.stringify(this.defaultSku))];
      }
    },
    // 上传图片
    uploadSuccess(res) {
      this.form.images.push(res[0]);
    },
    // 删除突破按
    uploadRemove(arr) {
      this.form.images = arr;
    },
    // 选择规格属性
    selectSpecResultChange() {
      this.createSkuHeader();
      this.createSkuBody();
    },
    // 生成多规格表体
    createSkuBody() {
      let bodys = [];
      let skuSnap = [];
      for (let item of this.selectSpec) {
        if (item.selectSpecResult.length) {
          let arr = [];
          for (let val of item.selectSpecResult) {
            arr.push({
              [item.name]: val,
            });
          }
          skuSnap.push({
            name: item.name,
            value: item.selectSpecResult.join(","),
          });
          bodys.push(arr);
        }
      }
      this.form.skuSnap = JSON.stringify(skuSnap);

      let arr = this.cartesian(bodys);
      // console.log(arr)
      let newarr = [];

      const m = {
        coverImg: "",
        ...this.defaultSku,
      };

      for (let item of arr) {
        if (Array.isArray(item)) {
          let obj = {};
          let specSnap = [];
          for (let v of item) {
            for (let key in v) {
              obj[`${key}`] = v[key];
              specSnap.push(v[key]);
            }
          }
          newarr.push({
            specSnap: specSnap.join(","),
            ...m,
            ...obj,
            barCode: `${dayjs().valueOf()}${RandomNumBoth(1, 9999)}`,
          });
        } else {
          let specSnap = [];
          for (let key in item) {
            specSnap.push(item[key]);
          }
          newarr.push({
            specSnap: specSnap.join(","),
            ...m,
            ...item,
            barCode: `${dayjs().valueOf()}${RandomNumBoth(1, 9999)}`,
          });
        }
      }

      if (this.originSkuList.length) {
        this.form.skuList = newarr.map((item) => {
          this.originSkuList.map((val) => {
            if (item.specSnap == val.specSnap) {
              for (let key in val) {
                item[key] = val[key];
              }
              item.id = val.id;
            } else {
              item.productId = this.$route.query.goods_id;
              item.realSalesNumber = "";
              item.shopId = localStorage.getItem("shopId");
              item.warnLine = "";
            }
          });

          return item;
        });
      } else {
        this.form.skuList = [];
        this.form.skuList = newarr;
      }

      console.log("newarr===", this.form.skuList);
    },
    // 笛卡尔积算法
    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;
      });
    },
    // 生成多规格表头
    createSkuHeader() {
      let i = 0;
      const headers = [];
      for (let item of this.selectSpec) {
        if (item.selectSpecResult.length) {
          i++;
          headers.push({
            label: item.name,
            value: item.name,
          });
        }
      }
      this.selectSpecResult = i;
      this.specTableHeaders = headers;
    },
    // 选择规格
    selectSpecHandle(e) {
      this.isEditor = false;
      const selectSpec = JSON.parse(
        JSON.stringify(this.specList.find((item) => item.id == e).specList)
      );
      for (let item in selectSpec) {
        selectSpec[item].selectSpecResult = [];
      }
      this.selectSpec = selectSpec;
      this.form.skuList = [];
    },
    // 获取规格列表
    async tbProductSpecGet() {
      try {
        const res = await tbProductSpecGet({
          shopId: localStorage.getItem("shopId"),
          sort: "id",
          page: 0,
          size: 100,
        });
        this.specList = res.content;
      } catch (error) { }
    },
    // 获取单位
    async tbShopUnit() {
      try {
        const res = await tbShopUnit({
          shopId: localStorage.getItem("shopId"),
          sort: "id",
          page: 0,
          size: 100,
        });
        this.units = res.content;
      } catch (error) { }
    },
    // 商品分类列表
    async tbShopCategoryGet() {
      try {
        const res = await tbShopCategoryGet({
          shopId: localStorage.getItem("shopId"),
          sort: "id",
          page: 0,
          size: 100,
        });
        let categorys = [];
        for (let item of res.content) {
          categorys.push({
            name: `|----${item.name}`,
            id: item.id,
          });
          if (item.childrenList.length) {
            for (let val of item.childrenList) {
              categorys.push({
                name: `|----|----${val.name}`,
                id: val.id,
              });
            }
          }
        }
        this.categorys = categorys;
      } catch (error) {
        console.log("商品分类列表", error);
      }
    },
  },
};
</script>

<style scoped lang="scss">
.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;
}

.shop_list {
  .item {
    display: flex;
    align-items: center;

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

    .dot {
      $size: 6px;
      width: $size;
      height: $size;
      border-radius: 50%;
      background-color: #1890ff;
    }

    .name {
      flex: 1;
      display: flex;
      margin-left: 10px;
      align-items: center;

      .t {
        color: #333;
        font-size: 14px;
        width: 100px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        margin-right: 10px;
      }
    }

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

      &:hover {
        cursor: pointer;
        color: #555;
      }
    }
  }
}

.icon {
  font-size: 14px;
  color: #1890ff;
  margin-left: 10px;

  &:hover {
    cursor: pointer;
  }
}

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

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

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