<template>
  <info-con title="销售信息：" class="sale-info-con">
    <div class="item">
      <label class="label">销售模式：</label>
      <RadioGroup v-model="data.salesType" @on-change="changeSalesType">
        <Radio :label="1" style="width: 200px" :disabled="isDetail || isEdit|| isAgain"
          >普通</Radio
        >
        <Radio
          :label="2"
          style="width: 200px"
          :disabled="isDetail|| isEdit|| isAgain  || packType"
          >预售</Radio
        >
        <Radio
          :label="3"
          style="width: 200px"
          :disabled="isDetail || isEdit|| isAgain || packType"
          >拍卖</Radio
        >
        <Radio :label="4" style="width: 200px" :disabled="isDetail || isEdit|| isAgain || shopStatus==4 || shopStatus==1"
          >盲盒</Radio
        >
        <Radio :label="5" style="width: 200px" :disabled="isDetail || isEdit|| isAgain"
          >免费领取</Radio
        >
      </RadioGroup>
    </div>
    <div class="item" v-if="shopStatus != 4">
      <label class="label">限购数量：</label>
       <InputNumber :min="0" style="width: 400px" :disabled="isDetail" placeholder="请输入限购数量"  v-model.number="data.purchaseLimit"></InputNumber>
    </div>
    <div class="item" v-if="data.salesType == 2 && shopStatus != 3">
      <label class="label">预售时间：</label>
      <Row class="time">
        <Col>
          <DatePicker
            type="date"
            :options="startOption"
            :readonly="isDetail "
            v-model="data.saleStartTime"
            placeholder="请选择开始时间"
            style="width: 200px"
          ></DatePicker>
        </Col>
        <span>至</span>
        <Col>
          <DatePicker
            type="date"
            :options="endOption"
            :readonly="isDetail "
            v-model="data.saleEndTime"
            placeholder="请选择结束时间"
            style="width: 200px"
          ></DatePicker>
        </Col>
      </Row>
    </div>
    <div class="item" v-if="data.salesType == 2 && shopStatus != 3">
      <label class="label">预计提货时间：</label>
      <Row class="time">
        <Col>
          <DatePicker
            type="date"
            :options="drawStartOption"
            :readonly="isDetail "
            v-model="data.drawStartTime"
            placeholder="请选择开始时间"
            style="width: 200px"
          ></DatePicker>
        </Col>
        <span>至</span>
        <Col>
          <DatePicker
            type="date"
            :options="drawEndOption"
            :readonly="isDetail "
            v-model="data.drawEndTime"
            placeholder="请选择结束时间"
            style="width: 200px"
          ></DatePicker>
        </Col>
      </Row>
    </div>
    <div class="item" v-if="data.salesType == 2 && shopStatus != 3">
      <label class="label">首付比例：</label>
      <RadioGroup v-model="data.depositType">
        <Radio
          label="1"
          :disabled="isDetail "
          class="ivu-radio"
          style="width: 260px"
        >
          <span>固定比例</span>
          <Input
            v-model="data.fixedProportion"
            :disabled="isDetail "
            style="width: 100px"
          />
          <span>%</span>
        </Radio>
        <Radio
          label="2"
          :disabled="isDetail "
          class="ivu-radio"
          style="width: 260px"
        >
          <span>固定金额</span>
          <Input
            v-model="data.fixedAmount"
            :disabled="isDetail "
            style="width: 100px"
          />
          <span>元</span>
        </Radio>
      </RadioGroup>
    </div>
    <div class="item" v-if="shopStatus == 3">
      <label class="label">打包价格：</label>
      <Input
        v-model="data.price"
        :disabled="isDetail "
        placeholder="请输入打包价格"
        style="width: 400px"
      />
    </div>
    <div class="series-info" v-if="shopStatus == 3">
      <label class="label">商品库存：</label>
      <Input
        v-model="data.stock"
        :disabled="isDetail "
        placeholder="请输入库存"
        style="width: 400px"
        :maxlength="9"
        @on-blur="stockBlur(data.stock)"
      />
    </div>
    <div class="item" v-if="shopStatus == 3">
      <label class="label">打包资源：</label>
      <div class="pack-con">
        <div
          class="pack-item"
          v-for="(item, index) of data.resource"
          :key="'prop-item-' + index"
        >
          <AutoComplete
            v-model="item.name"
            @on-search="handleSearch($event, index)"
            placeholder="请输入资源编号或名称"
            :disabled="isDetail "
            style="width: 215px"
          >
            <Option
              v-for="(item, index) in item.integralMerchantNameList"
              :value="item.name"
              :key="'state-option-' + index"
              >{{ item.name }}</Option
            >
          </AutoComplete>
          <Select
            placeholder="请选择资源规格"
            class="search-input"
            v-model="item.skuId"
            :disabled="isDetail "
            style="width: 215px; margin: 0 20px"
          >
            <Option
              v-for="(itemb, idx) of item.specificationsList"
              :value="itemb.skuId"
              :key="itemb.skuId"
              @click.native="handleSpecifications(idx, index)"
              >{{ itemb.name }}</Option
            >
          </Select>
          <Input
            class="prop-val"
            placeholder="请设置资源数量"
            v-model="item.number"
            :disabled="isDetail "
            @on-blur="packOnBlur(index, item)"
            :maxlength="30"
            style="width: 215px"
          />
          <span v-if="item.actualNumber && item.actualNumber != 0"
            >资源总数：{{ item.actualNumber }}</span
          >
          <Icon
            class="del-con"
            type="md-close-circle"
            color="#ed4014"
            v-if="!isDetail "
            :size="20"
            @click="delAge(index)"
          />
        </div>
        <div class="add-btn">
          <Button type="info" @click="addAge" v-if="!isDetail && !isEdit&&!isDraft"
            >+ 添加</Button
          >
        </div>
      </div>
    </div>
    <div class="item" v-if="data.salesType == 3 && shopStatus != 3">
      <label class="label">起拍价：</label>
      <Input
        v-model="data.startPrice"
        :readonly="isDetail "
        type="number"
        style="width: 400px"
      >
      </Input>
    </div>
    <div class="item" v-if="data.salesType == 3 && shopStatus != 3">
      <label class="label">拍卖保证金：</label>
      <Input
        v-model="data.buyerDeposit"
        :readonly="isDetail "
        type="number"
        style="width: 400px"
      >
      </Input>
    </div>
    <div class="item" v-if="data.salesType == 3 && shopStatus != 3">
      <label class="label">出价最小增幅：</label>
      <Input
        v-model="data.priceIncrease"
        :readonly="isDetail "
        type="number"
        style="width: 400px"
      >
      </Input>
    </div>
    <div class="item" v-if="data.salesType == 3 && shopStatus != 3">
      <label class="label">竞拍结束时间：</label>
      <DatePicker
        type="date"
        :options="buyEndOption"
        :readonly="isDetail "
        v-model="data.endTime"
        placeholder="请选择结束时间"
        style="width: 400px"
      ></DatePicker>
    </div>
    <div class="item" v-if="data.salesType == 3 && shopStatus != 3">
      <label class="label">付款结束时间：</label>
      可以延后
      <Input
        v-model="data.delayPayTime"
        :readonly="isDetail "
        type="number"
        style="width: 150px"
      >
      </Input>
      天付款
    </div>
    <div
      class="item"
      v-if="(data.salesType == 3 && shopStatus != 3) || shopStatus == 4"
    >
      <label class="label">规格名称：</label>
      <Input
        v-model="data.name"
        :readonly="isDetail "
        style="width: 400px"
      >
      </Input>
    </div>
    <div class="item" v-if="data.salesType == 4">
      <label class="label">商品价格：</label>
      <Input
        v-model="data.price"
        :readonly="isDetail"
        placeholder="请输入商品价格"
        style="width: 400px"
      />
    </div>
    <div
      class="item"
      v-if="shopStatus == 4 && (data.salesType == 1 || data.salesType == 5)"
    >
      <label class="label">商品价格：</label>
      <Input
        v-model="data.shopPrice"
        type="number"
        :readonly="isDetail "
        style="width: 400px"
      >
      </Input>
    </div>
    <div class="item" v-if="shopStatus == 4 && data.salesType == 2">
      <label class="label">预售价格：</label>
      <Input
        v-model="data.preSalePrice"
        :readonly="isDetail "
        style="width: 400px"
      >
      </Input>
    </div>
    <div
      class="item"
      v-if="
        (data.salesType == 1 || data.salesType == 2 || data.salesType == 5) &&
        shopStatus != 3 &&
        shopStatus != 4
      "
      v-for="(pItem, pIndex) of propList"
      :key="'prop-item-' + pIndex"
    >
      <label class="label">规格参数：</label>
      <Input
        style="width: 140px; margin-right: 10px"
        placeholder="请输入规格名称"
        @on-change="delAllSku(pItem, pIndex)"
        v-model="pItem.name"
        :readonly="isDetail "
        :maxlength="30"
      />
      <div class="property-con">
        <div
          class="property-item"
          v-for="(vItem, vIndex) of pItem.valList"
          :key="'val-item-' + vIndex"
        >
          <Input
            class="prop-val"
            placeholder="请输入规格值"
            @on-change="delSkuVal(pItem, vIndex)"
            v-model="vItem.val"
            :readonly="isDetail "
            :maxlength="30"
          />
          <Icon
            class="del-con"
            type="md-close-circle"
            color="#ed4014"
            :size="20"
            @click="delVal(pItem, vIndex)"
            v-if="!isDetail && !isEdit&&!isDraft && data.salesType != 2"
          />
        </div>
        <div class="add-btn">
          <Button
            type="info"
            shape="circle"
            size="small"
            @click="addVal(pItem)"
            v-if="
              !isDetail &&
              !isEdit &&
              pItem.valList.length < 10 &&
              data.salesType != 2
            "
            >+ 添加属性值</Button
          >
        </div>
      </div>
      <Icon
        class="del-con"
        type="md-backspace"
        color="#ed4014"
        :size="30"
        @click="delProp(pIndex)"
        v-if="!isDetail && !isEdit&&!isDraft"
      />
    </div>
    <div
      class="item"
      v-if="
        (data.salesType == 1 || data.salesType == 2 || data.salesType == 5) &&
        shopStatus != 3 &&
        shopStatus != 4
      "
    >
      <div class="empty" />
      <div class="opt-btn" v-if="!isDetail && !isEdit&&!isDraft">
        <Button type="info" @click="addProp" v-show="propList.length < 3"
          >+ 添加属性</Button
        >
      </div>
    </div>
    <!--  v-if="shopStatus == 4 || (shopStatus != 3 && shopStatus != 4)" -->
    <div
      class="item"
      v-if="data.salesType == 4 || (shopStatus != 3 && shopStatus != 4)"
    >
      <label class="label">商品通证：</label>
      <RadioGroup v-model="data.commodityPass">
        <!-- <Radio :label="0" style="width:200px" :disabled="isDetail ">否</Radio> -->
        <Radio :label="1" style="width: 200px" :disabled="isDetail || isEdit|| isAgain"
          >内部生成</Radio
        >
        <Radio :label="2" style="width: 200px" :disabled="isDetail || isEdit|| isAgain"
          >外部绑定</Radio
        >
      </RadioGroup>
    </div>
    <div
      class="item"
      v-if="data.salesType == 3 && shopStatus != 3 && data.commodityPass == 2"
    >
      <label class="label"></label>
      <Select
        :transfer="true"
        placeholder="请选择外部导入的token"
        class="search-input"
        v-model="data.id"
        @on-change="getMoreOutParams(data.id)"
        :disabled="isDetail || isEdit|| isAgain"
        style="width: 400px"
      >
        <Option
          v-for="(item, index) of newseriesList"
          :value="item.commodityPassId"
          :key="'series-option-' + index"
          :disabled="item.disabled"
          >{{ item.labelName }}</Option
        >
      </Select>
    </div>
    <div class="item" v-if="shopStatus == 4 || data.salesType == 3">
      <label class="label">溯源哈希：</label>
      <Input
        v-model="data.hash"
        :readonly="isDetail"
        style="width: 400px"
      />
    </div>
    <div
      class="item"
      style="text-align: center"
      v-if="
        (data.salesType == 1 || data.salesType == 2 || data.salesType == 5) &&
        shopStatus != 3 &&
        shopStatus != 4
      "
    >
      <Button
        type="primary"
        style="margin: auto"
        @click="genSkuTable"
        v-if="!isDetail && !isEdit&&!isDraft"
        >生成价目表</Button
      >
    </div>
    <div
      class="tip"
      v-if="
        !isDetail &&
        !isEdit &&
        (data.salesType == 1 || data.salesType == 2 || data.salesType == 5) &&
        shopStatus != 3 &&
        shopStatus != 4
      "
    >
      提示：如修改上述基本属性后，需重新生成价目表！缩略图建议尺寸100 *
      100，大小不得超过6MB
    </div>
    <template v-if="data.salesType !== 4">
      <Table
        v-if="
          showTable &&
          (data.salesType == 1 || data.salesType == 2 || data.salesType == 5) &&
          shopStatus != 3 &&
          shopStatus != 4
        "
        border
        :columns="columns"
        :data="data.sku"
      >
        <template slot-scope="{ row, index }" slot="originalPrice">
          <span v-if="isDetail">{{ row.originalPrice }}</span>
          <Input
            v-else
            placeholder="单位（RMB）"
            :value="row.originalPrice"
            @on-change="handleInputChange(index, 'originalPrice')"
            type="number"
            :readonly="isDetail"
          />
        </template>
        <template slot-scope="{ row, index }" slot="stock">
          <span v-if="isDetail">{{ row.stock }}</span>
          <Input
            v-else
            placeholder="整数值"
            :value="row.stock"
            @on-change="handleInputChange(index, 'stock')"
            @on-blur="onBlur(index, row)"
            type="number"
            :readonly="isDetail || data.commodityPass == 2"
            :maxlength="9"
          />
        </template>
        <template slot-scope="{ row, index }" slot="coinName">
          <template v-if="isDetail || isEdit|| isAgain">
            <label class="coinName-label">{{ row.coinName || "--" }}</label>
          </template>
          <template v-else>
            <div v-if="data.commodityPass == 0">
              <label>--</label>
            </div>
            <div v-if="data.commodityPass == 1">
              <span>系统生成</span>
            </div>
            <div v-if="data.commodityPass == 2">
              <Select
                :transfer="true"
                v-model="data.sku[index].commodityPassId"
                @on-change="
                  getMoreParams(data.sku[index].commodityPassId, index)
                "
                style="width: 140px"
              >
                <Option
                  v-for="(item, index) of newseriesList"
                  :value="item.commodityPassId"
                  :disabled="item.disabled"
                  :key="'series-option-' + index"
                  >{{ item.labelName }}</Option
                >
              </Select>
            </div>
          </template>
        </template>
        <template slot-scope="{ row, index }" slot="hash">
          <span v-if="isDetail">{{ row.hash }}</span>
          <Input
            v-else
            :value="row.hash"
            @on-change="handleInputChange(index, 'hash')"
            :readonly="isDetail"
          />
        </template>
        <template slot-scope="{ row, index }" slot="weight">
          <span v-if="isDetail">{{ row.weight }}</span>
          <Input
            v-else
            placeholder="单位（KG）"
            :value="row.weight"
            @on-change="handleInputChange(index, 'weight')"
            type="number"
            :readonly="isDetail || shopStatus == 2"
          />
        </template>
        <template slot-scope="{ row, index }" slot="image">
          <file-upload
            :ref="'fileUpload' + index"
            :width="46"
            style="margin-top: 5px"
            v-model="data.sku[index].upload.imageList"
            @input="handleUploadInput($event, index)"
            :maxNum="1"
            :defaultList="data.sku[index].upload.defaultImgList"
            :readonly="isDetail"
            showWatch
            :iconSize="16"
          />
        </template>

        <template slot-scope="{ index }" slot="opt">
          <Button type="error" size="small" @click="delSku(index)">删除</Button>
        </template>
      </Table>
    </template>

    <template v-if="data.salesType === 4">
      <div class="item" style="text-align: center">
        <label class="label">规格列表:</label>
        <Table border :columns="columns" :data="data.sku">
          <template slot-scope="{ row, index }" slot="name">
            <span v-if="isDetail">{{ row.name }}</span>
            <Input
              v-else
              placeholder="规格名称"
              :value="row.name"
              @on-change="handleInputChange(index, 'name')"
              :readonly="isDetail"
            />
          </template>
          <template slot-scope="{ row, index }" slot="image">
            <file-upload
              :ref="'fileUpload' + index"
              :width="46"
              style="margin-top: 5px"
              v-model="data.sku[index].upload.imageList"
              @input="handleUploadInput($event, index)"
              :maxNum="1"
              :defaultList="data.sku[index].upload.defaultImgList"
              :readonly="isDetail"
              showWatch
              :iconSize="16"
            />
          </template>
          <template slot-scope="{ row, index }" slot="weight">
            <span v-if="isDetail">{{ row.weight }}</span>
            <Input
              v-else
              placeholder="单位（KG）"
              v-model="row.weight"
              @on-change="handleInputChange(index, 'weight')"
              type="number"
              :readonly="isDetail"
            />
          </template>
          <template slot-scope="{ row, index }" slot="stock">
            <span v-if="isDetail">{{ row.stock }}</span>
            <InputNumber  placeholder="整数值"  v-else :max="20000" :min="1" v-model="row.stock"  @on-change="handleInputChange(index, 'stock')" @on-blur="onBlur(index, row)" :readonly="isDetail"></InputNumber>
          </template>
          <template slot-scope="{ row, index }" slot="coinName">
            <template v-if="isDetail || isEdit|| isAgain || data.sku[index].status == 1">
              <label class="coinName-label">{{ row.coinName || "--" }}</label>
            </template>
            <template v-else>
              <div v-if="data.commodityPass == 1">
                <label>内部生成</label>
              </div>
              <div v-if="data.commodityPass == 0">
                <label class="coinName-label">{{ row.coinName || "--" }}</label>
                <!-- <label class="coinName-label" style="color: #ed4014"
            >&nbsp;&nbsp;+&nbsp;&nbsp;</label
          > -->
                <Input
                  placeholder="2-10位大写字母或数字"
                  :value="row.coinName"
                  @on-change="handleInputChange(index, 'coinName')"
                  @on-blur="handleInputBlur(index, 'coinName')"
                  style="width: 140px"
                  :readonly="isDetail || isEdit|| isAgain || isAgain "
                  :disabled="isDetail || data.sku[index].status == 1"
                  :maxlength="10"
                />
              </div>
              <div v-if="data.commodityPass == 2">
                <label class="coinName-label">{{ coinNamePrefix }}</label>
                <Select
                  :transfer="true"
                  v-model="data.sku[index].commodityPassId"
                  @on-change="getMoreParams(data.sku[index].commodityPassId, index)"
                  style="width: 140px"
                >
                  <Option
                    v-for="(item, index) of newseriesList"
                    :value="item.commodityPassId"
                    :disabled="item.disabled"
                    :key="'series-option-' + index"
                    >{{ item.labelName }}</Option
                  >
                </Select>
              </div>
            </template>
          </template>
          <template slot-scope="{ row, index }" slot="hash">
          <span v-if="isDetail">{{ row.hash }}</span>
          <Input
            v-else
            :value="row.hash"
            @on-change="handleInputChange(index, 'hash')"
            :readonly="isDetail"
          />
        </template>
          <template slot-scope="{ row, index }" slot="isHide">
            <span v-if="isDetail|| isEdit|| isAgain">{{ row.isHide ? "是" : "否" }}</span>
            <Checkbox
              v-else
              v-model="row.isHide"
              @on-change="changIsHidden($event, index)"
            ></Checkbox>
          </template>

          <template slot-scope="{ index }" slot="opt">
            <Button type="error" size="small" @click="delSku(index)"
              >删除</Button
            >
          </template>
        </Table>
      </div>
      <div class="item" style="justify-content: flex-end" v-if="!isDetail && !isEdit&&!isDraft">
        <Button type="primary" style="margin: auto" @click="genSkuTableBlindBox"
          >添加商品</Button
        >
      </div>
      <div class="item" style="margin-top: 40px">
        <label class="label">难度系数：</label>
        <Slider
          v-model="data.difficulty"
          :tip-format="format"
          :min="1"
          :max="10"
          style="width: 500px"
        ></Slider>
      </div>
      <div class="item">
        <label class="label">盲盒规则：</label>
        <div class="editor-con">
          <Spin fix v-if="editorLoading">
            <Icon
              type="ios-loading"
              size="30"
              color="#2d8cf0"
              class="spin-icon-load"
            ></Icon>
            <div>上传中( {{ editorUploadPercent }}% )...</div>
          </Spin>
          <quill-editor
            v-model="data.blindBoxRule"
            ref="myQuillEditor"
            :options="editorOption"
            class="detail-editor"
            v-show="!isDetail"
          ></quill-editor>
          <div
            v-show="isDetail"
            v-html="data.blindBoxRule"
            class="describt-detail"
          ></div>
        </div>
      </div>
      <Upload
        :action="uploadImgUrl"
        ref="uploadImg"
        v-show="false"
        :headers="{
          token: $store.state.admin.token,
          adminId: $store.state.admin.uid,
        }"
        :before-upload="imgBoforeUpload"
        :on-progress="uploadOnProgress"
        :on-success="imgUploadSuccess"
        :on-error="imgUploadErr"
        accept=".jpg, .jpeg, .png, .gif"
      />
      <Upload
        :action="uploadVideoUrl"
        ref="uploadVideo"
        v-show="false"
        :headers="{
          token: $store.state.admin.token,
          adminId: $store.state.admin.uid,
        }"
        :before-upload="videoBoforeUpload"
        :on-progress="uploadOnProgress"
        :on-success="videoUploadSuccess"
        :on-error="videoUploadErr"
        accept=".mp4, .mkv"
      />
    </template>
  </info-con>
</template>

<script>
import InfoCon from "./info-con";
import FileUpload from "_c/file-upload";
import config from "@/config";
import { deepCopy } from "@/utils/common";
import { uploadImgUrl, uploadVideoUrl } from "@/api/apiConfig";
import axios from "axios";
import { getPosterFromVideoUrl } from "@/libs/tools";
const baseUrl =
  process.env.NODE_ENV === "development"
    ? config.baseUrl.dev
    : config.baseUrl.pro;
export default {
  props: {
    data: {
      // type: Object,
      default: { sku: [] },
      commodityPass: "",
      saleStartTime: "",
      saleEndTime: "",
      drawStartTime: "",
      drawEndTime: "",
      fixedProportion: "",
      fixedAmount: "",
      depositType: "",
      price: "",
      startPrice: "",
      buyerDeposit: "",
      priceIncrease: "",
      delayPayTime: "",
      endTime: "",
      resource: [
        {
          integralMerchantNameList: [],
          goodsId: "",
          skuId: "",
          number: "",
          specificationsList: [],
          actualNumber: "",
        },
      ], // 打包资源
      outToken: "",
      stock: "",
      salesType: "",
      name: "",
      id: "",
      outStock: "",
      shopPrice: "",
      preSalePrice: "",
      hash: "",
      difficulty: 1,
      purchaseLimit:0
    },
    isDetail: {
      type: Boolean,
      default: false,
    },
    isEdit: {
      type: Boolean,
      default: false,
    },
    // isSelf: {
    //   type: Boolean,
    //   default: false
    // },
    isDraft: {
      type: Boolean,
      default: false,
    },
    isAgain: {
      type: Boolean,
      default: false,
    },
    shopStatus: "",
  },
  watch: {
    salesType(val) {
      // console.log('111', val)
      if (val == 2) {
        this.propList = [{ outToken: "", valList: [{ val: "" }] }];
      }
    },
    shopStatus(val, oldVal) {
      if (val == 3 || val == 2) {
        this.data.salesType = 1;
      }
      if (val != oldVal) {
        this.columns[0].title = "";
        this.propList = [{ outToken: "", valList: [{ val: "" }] }];
      }
    },
  },
  components: {
    InfoCon,
    FileUpload,
  },
  data() {
    return {
      propList: [{ outToken: "", valList: [{ val: "" }] }],
      showTable: false,
      columns: [],
      coinNamePrefix: '',
      seriesList: [],
      name: "",
      tokenNumber: "",
      numberStock: "",
      outTokenName: "",
      id: "",
      drawStartOption: {
        // 指定开始限制时间
        disabledDate: (date) => {
          return date && date.valueOf() < Date.now() - 86400000;
        },
      },
      drawEndOption: {
        // 指定终止日期
        disabledDate: (date) => {
          return date && date.valueOf() < Date.now() - 86400000;
        },
      },
      startOption: {
        // 指定开始限制时间
        disabledDate: (date) => {
          return date && date.valueOf() < Date.now() - 86400000;
        },
      },
      endOption: {
        // 指定终止日期
        disabledDate: (date) => {
          return date && date.valueOf() < Date.now() - 86400000;
        },
      },
      buyEndOption: {
        // 指定终止日期
        disabledDate: (date) => {
          return date && date.valueOf() < Date.now() - 86400000;
        },
      },
      uploadImgUrl,
      uploadVideoUrl,
      editorOption: {
        placeholder: "请输入内容...",
        modules: {
          toolbar: [
            [
              "bold",
              "italic",
              { header: 2 },
              "blockquote",
              { list: "ordered" },
              { list: "bullet" },
              { align: [] },
            ],
            ["image", "video"],
          ],
        },
      },
      editorLoading: false,
      editorUploadPercent: 0,
      // rateList: [3, 4, 5, 6, 9, 10, 11, 13]
    };
  },
  computed: {
    platform() {
      return (
        this.$store.state.admin.type == 1 || this.$store.state.admin.type == 4
      );
    },
    packType() {
      return this.shopStatus == 3;
    },
    newseriesList() {
      let arr = deepCopy(this.seriesList);
      arr.forEach((item) => {
        // console.log(this.data.sku.find(x => { return x.commodityPassId === item.commodityPassId }))
        if (
          this.data.sku.find((x) => {
            return x.commodityPassId === item.commodityPassId;
          })
        ) {
          // console.log(item)
          item.disabled = true;
        }
        // item.stringData = JSON.stringify(item)
      });
      // console.log(arr)
      return arr;
    },
  },
  async mounted() {
    this.genPropList(this.data.sku);
    
    if(this.data.salesType===4){
        this.genColumnBlindBox();
    }else{
        this.genColumn();
    }
    
    // if (!this.platform) {
    //   this.getMerchantPrefixInfo()
    // }
    if (!this.platform) {
      this.seriesList = await this.getunbindToken();
    }
    this.data.sku.forEach((item) => {
      // console.log('item', item)
      this.numberStock = item.stock;
      if (this.isAgain) {
        item.republish = false;
      }
      if (item.outToken) {
        let obj = JSON.parse(item.outToken);
        obj.disabled = true;
        if (
          !this.seriesList.some((x) => {
            return x.commodityPassId === obj.commodityPassId;
          })
        ) {
          this.seriesList.push(obj);
        }
        // if (this.seriesList.find(x => { return x.commodityPassId !== obj.commodityPassId })) {
        //   console.log(11111)
        //   this.seriesList.push(obj)
        // }
      }
      // console.log('1', this.data.commodityPass)
      // if (this.$store.state.admin.type == 2 && this.data.commodityPass != 2) {
      //   item.coinNamePrefix = item.coinName.substring(0, 6)
      //   item.coinName = item.coinName.substring(6)
      // } else if (this.$store.state.admin.type == 3 && this.data.commodityPass != 2) {
      //   item.coinNamePrefix = item.coinName.substring(0, 2)
      //   item.coinName = item.coinName.substring(2)
      // } else {
      //   item.coinNamePrefix = ''
      // }

      // console.log('coinName', item.coinName)
    });
    // console.log('154', this.data.outToken)
    this.showTable = true;
    setTimeout(() => {});
  },
  methods: {
    format(val) {
      return "难度系数: " + val + "";
    },
    changeSalesType(val) {
      if (val === 4) {
        this.data.sku = [];
        this.columns = [];
        this.genSkuTableBlindBox();
        if(!this.data.commodityPass){
          this.data.commodityPass=1
        }
      } else if (val === 1) {
        this.data.sku = [];
        this.columns = [];
        this.genColumn();
      } else {
        this.data.salesType = val;
      }
    },
    addAge() {
      // console.log('111111111111')
      this.data.resource.push({
        integralMerchantNameList: [],
        goodsId: "",
        skuId: "",
        number: "",
        specificationsList: [],
        actualNumber: "",
      });
    },
    delAge(index) {
      this.data.resource.splice(index, 1);
    },
    handleSearch(goodsInfo, index) {
      if (!goodsInfo) {
        return this.$Message.warning("请先输入资源编号以便查询！");
      }
      this.api({
        apiName: "spugetbyvague",
        postdata: goodsInfo,
        success: (res) => {
          this.data.resource[index].integralMerchantNameList = res.data;
          if (this.data.resource[index].integralMerchantNameList.length === 1) {
            let goodsId =
              this.data.resource[index].integralMerchantNameList[0].goodsId;
            this.api({
              apiName: "skugetbygoodsId",
              postdata: goodsId,
              success: (res) => {
                let arr = [];
                let list = this.data.resource[index].specificationsList;
                if (list && list.length > 0) {
                  for (let item of res.data) {
                    if (
                      list.find((x) => {
                        return x.skuId === item.skuId;
                      })
                    ) {
                      item.stock = list.find((x) => {
                        return x.skuId === item.skuId;
                      }).stock;
                    }
                    arr.push(item);
                  }
                } else {
                  arr = res.data;
                }
                this.data.resource[index].specificationsList = arr;
              },
            });
          }
        },
      });
    },
    handleSpecifications(idx, index) {
      this.idx = idx;
      this.data.resource[index].number = "";
      for (var i = 0; i < this.data.resource.length - 1; i++) {
        for (var j = i + 1; j < this.data.resource.length; j++) {
          if (this.data.resource[i].skuId === this.data.resource[j].skuId) {
            let title = "规格信息不能重复！";
            this.data.resource[index].skuId = "";
            return this.$Notice.error({ title });
          }
        }
      }
    },
    getMoreParams(val, index) {
      let item = this.seriesList.find((x) => {
        return x.commodityPassId === val;
      });
      this.tokenNumber = item.availableNumber;
      this.data.sku[index].stock = Number(item.availableNumber).toFixed();
      console.log("item", item);
      this.data.sku[index].hash = item.hash;
      console.log("item", item.hash);
    },
    getMoreOutParams(val) {
      let item = this.seriesList.find((x) => {
        return x.commodityPassId === val;
      });
      this.data.id = val;
      this.data.outStock = Number(item.availableNumber).toFixed();
    },
    stockBlur(val) {
      let skuNumber = this.data.resource;
      skuNumber.forEach((item, index) => {
        let number = item.number * val;
        let n = NaN;
        for (let i = 0, len = item.specificationsList.length; i < len; i++) {
          if (item.specificationsList[i].skuId === item.skuId) {
            n = i;
            break;
          }
        }
        if (number > item.specificationsList[n].stock) {
          this.data.resource[index].number = "";
          return this.$Notice.warning({
            title: `库存 * 填写的资源量不能超过总资源数量`,
          });
        }
      });
    },
    changIsHidden (val, index) {
      this.data.sku[index].isHide = val
    },
    onBlur(index, val) {
      //  console.log('4444', this.data.commodityPass)
      // if (!this.isEdit && JSON.parse(val.stock) > this.tokenNumber && this.data.commodityPass == 2) {
      //   this.data.sku[index].stock = parseInt(this.tokenNumber)
      //   return this.$Notice.warning({ title: `填写库存过多 (实际数量：${parseInt(this.tokenNumber)})` })
      // }
      // if (this.isEdit && this.data.commodityPass == 2) {
      //   let number = JSON.parse(val.stock) - this.numberStock
      //   //  + this.data.sku[index].balanceNum
      //   if (number > this.data.sku[index].balanceNum) {
      //     this.data.sku[index].stock = parseInt(this.numberStock + this.data.sku[index].balanceNum)
      //     return this.$Notice.warning({ title: `填写库存过多 (实际数量：${parseInt(this.numberStock + this.data.sku[index].balanceNum)})` })
      //   }
      // }
    },
    packOnBlur(index, val) {
      for (let i = 0, len = val.specificationsList.length; i < len; i++) {
        if (val.specificationsList[i].skuId === val.skuId) {
          this.idx = i;
          break;
        }
      }
      let idx = this.idx;

      this.data.resource[index].actualNumber =
        this.data.resource[index].specificationsList[idx].stock;
      this.$set(this.data.resource, index, this.data.resource[index]);
      let stockNumber = JSON.parse(val.number) * this.data.stock;
      if (stockNumber > this.data.resource[index].actualNumber) {
        this.data.resource[index].number = "";
        return this.$Notice.warning({
          title: `库存*填写的资源量不能超过总资源数量`,
        });
      }
    },
    getunbindToken() {
      return new Promise((resolve, reject) => {
        this.api({
          apiName: "unbindToken",
          success: (res) => {
            // this.seriesList = res.data
            resolve(res.data);
          },
        });
      });
    },
    handleInputChange(index, key) {
      this.data.sku[index][key] = event.target.value;
    },
    handleInputBlur(index, key) {
      if (this.isAgain) {
        if (key == "coinName") {
          this.data.sku[index].republish = true;
        }
      }
    },
    handleUploadInput(e, index) {
      console.log(index, this.data.sku);
      // this.data.sku[index].upload.imageList = e;
      // this.data.sku[index].upload.defaultImgList = e.slice(0)
    },

    addProp() {
      this.propList.push({ name: "", valList: [{ val: "" }] });
    },
    delAllSku(item, index) {
      this.data.sku = [];

      this.propList[index].valList = [{ val: "" }];
      this.data.commodityPass = "";
      this.columns[0].title = "";
    },
    delSkuVal(item, index) {
      this.data.sku = [];
      this.data.commodityPass = "";
      this.columns[0].title = "";
    },
    delProp(index) {
      this.propList.splice(index, 1);
    },
    addVal(item) {
      item.valList.push({ val: "" });
    },
    delVal(item, index) {
      item.valList.splice(index, 1);
    },
    delSku(index) {
      this.data.sku.splice(index, 1);
    },
    genPropList(sku) {
      if (sku && sku.length !== 0) {
        let propHashTable = {};
        sku.forEach((sItem) => {
          if (!sItem.propertyList || sItem.propertyList.length === 0) {
            return;
          }
          sItem.propertyList.forEach((pItem) => {
            if (propHashTable[pItem.propKey]) {
              propHashTable[pItem.propKey][pItem.propVal] = "x";
            } else {
              propHashTable[pItem.propKey] = {
                [pItem.propVal]: "x",
              };
            }
          });
        });
        this.propList = [];
        for (let key in propHashTable) {
          let valList = [];
          for (let vkey in propHashTable[key]) {
            valList.push({ val: vkey });
          }
          this.propList.push({ name: key, valList });
        }
      }
    },

    genSkuTable() {
      let check = true;
      let title = "";
      if (!this.propList || this.propList.length === 0) {
        check = false;
        title = "请添加属性！";
      }
      let propNameHashTable = {};
      this.propList.find((pItem) => {
        let propName = pItem.name;
        if (!propName) {
          title = "属性名称不能为空！";
          check = false;
          return true;
        }
        if (propNameHashTable[propName]) {
          title = "属性名称不能重复！";
          check = false;
          return true;
        }
        if (
          [
            "originalPrice",
            "stock",
            "coinName",
            "image",
            "imageList",
            "defaultImgList",
            "propertyList",
          ].includes(propName)
        ) {
          title = "属性名称不符合规范！";
          check = false;
          return true;
        }
        propNameHashTable[propName] = true;
        if (!pItem.valList || pItem.valList.length === 0) {
          title = "属性值不能为空！";
          check = false;
          return true;
        }
        pItem.valList.find((vItem) => {
          if (!vItem.val) {
            title = "属性值不能为空！";
            check = false;
            return true;
          }
        });
        for (var i = 0; i < pItem.valList.length - 1; i++) {
          for (var j = i + 1; j < pItem.valList.length; j++) {
            if (pItem.valList[i].val === pItem.valList[j].val) {
              title = "属性值不能重复！";
              check = false;
              return true;
            }
          }
        }
      });

      if (!check) {
        this.$Notice.warning({ title });
      } else {
        if (this.data.commodityPass == 0) {
          return this.$Notice.warning({ title: "请先选择商品通证" });
        }
        this.genColumn();
        this.genSku();
        this.showTable = true;
      }
    },
    genColumn() {
      let columns = [];
      this.propList.forEach((pItem) => {
        columns.push({
          title: pItem.name,
          minWidth: 120,
          key: pItem.name,
          align: "center",
        });
      });
      columns.push({
        title: "缩略图",
        slot: "image",
        width: 240,
        align: "center",
      });
      columns.push({
        title: "价格（￥）",
        slot: "originalPrice",
        width: 160,
        align: "center",
      });
      columns.push({
        title: "商品Token",
        slot: "coinName",
        width: 230,
        align: "center",
      });
      columns.push({
        title: "溯源哈希",
        slot: "hash",
        width: 180,
        align: "center",
      });
      columns.push({
        title: "重量（KG）",
        slot: "weight",
        width: 130,
        align: "center",
      });
      columns.push({
        title: "库存",
        slot: "stock",
        width: 160,
        align: "center",
      });
      if (!this.isDetail && !this.isEdit && !this.isAgain) {
        columns.push({
          title: "操作",
          slot: "opt",
          width: 80,
          align: "center",
        });
      }
      this.columns = columns;
    },
    genSku() {
      let resArr = [];
      this.propList.forEach((item) => {
        resArr = this.genSkuData(item, resArr);
      });

      this.data.sku = resArr;
    },
    genSkuData(prop, resArr) {
      let newArr = [];
      let { name, valList } = prop;
      if (resArr.length === 0) {
        valList.forEach((item) => {
          let propertyList = [{ propKey: name, propVal: item.val }];
          newArr.push({
            [name]: item.val,
            originalPrice: 0,
            stock: "",
            coinName: "",
            // coinNamePrefix: this.coinNamePrefix,
            outToken: "",
            republish: false,
            // availableNumber: '',
            image: "",
            propertyList,
            // rate: 0,
            // typeCode: '',
            hash: "",
            weight: 0,
            upload: {
              imageList: [],
              defaultImgList: [],
            },
          });
        });
        // console.log('newArr1', newArr)
      } else {
        resArr.forEach((rItem) => {
          valList.forEach((vItem) => {
            let newItem = { ...rItem, [name]: vItem.val };
            newItem.propertyList = JSON.parse(
              JSON.stringify(newItem.propertyList)
            );
            newItem.propertyList.push({
              propKey: name,
              propVal: vItem.val,
            });
            newItem.upload = {
              imageList: [],
              defaultImgList: [],
            };
            // console.log('newItem', newItem)
            newArr.push(newItem);
          });
        });
      }
      // console.log('newArr', newArr)
      return newArr;
    },
    genSkuTableBlindBox() {
      if(this.columns.length===0){
        this.genColumnBlindBox();
      }
      this.genSkuBlindBox();
    },
    genColumnBlindBox() {
      let columns = [];
      this.propList.forEach((pItem) => {
        columns.push({
          title: "规格名称",
          minWidth: 120,
          slot: "name",
          align: "center",
        });
      });
      columns.push({
        title: "缩略图",
        slot: "image",
        width: 240,
        align: "center",
      });

      columns.push({
        title: "重量（KG）",
        slot: "weight",
        width: 130,
        align: "center",
      });
      columns.push({
        title: "库存",
        slot: "stock",
        width: 160,
        align: "center",
      });
      columns.push({
        title: "商品Token",
        slot: "coinName",
        width: 230,
        align: "center",
      });
      columns.push({
        title: "溯源哈希",
        slot: "hash",
        width: 180,
        align: "center",
      });
      columns.push({
        title: "是否是隐藏款",
        slot: "isHide",
        width: 110,
        align: "center",
      });
      // columns.push({
      //   title: '类型编码',
      //   slot: 'typeCode',
      //   width: 200,
      //   align: 'center'
      // })
      // if (this.isDetail) {
      //   columns.push({
      //     title: '发行量',
      //     key: 'issueNum',
      //     width: 160,
      //     align: 'center'
      //   })
      // }
      if (!this.isDetail && !this.isEdit && !this.isAgain) {
        columns.push({
          title: "操作",
          slot: "opt",
          width: 80,
          align: "center",
        });
      }
      console.log(columns);
      this.columns = columns;
    },
    genSkuBlindBox() {
      let resArr = [];
      this.propList.forEach((item) => {
        resArr = this.genSkuDataBlindBox(item, resArr);
      });
      if (this.data.sku.length === 0) {
        this.data.sku = resArr;
      } else {
        this.data.sku = [...this.data.sku, ...resArr];
      }
       console.log(this.data.sku)
    },
    genSkuDataBlindBox(prop, resArr) {
      let newArr = [];
      let { name, valList } = prop;
      if (resArr.length === 0) {
        valList.forEach((item) => {
          let propertyList = [{ propKey: name, propVal: item.val }];
          newArr.push({
            [name]: item.val,
            originalPrice: "",
            stock: "",
            coinName: "",
            coinNamePrefix: this.coinNamePrefix,
            name: "",
            republish: false,
            // availableNumber: '',
            image: "",
            propertyList,
            weight: "",
            upload: {
              imageList: [],
              defaultImgList: [],
            },
            isHide: false,
          });
        });
        // console.log('newArr1', newArr)
      } else {
        resArr.forEach((rItem) => {
          valList.forEach((vItem) => {
            let newItem = { ...rItem, [name]: vItem.val };
            newItem.propertyList = JSON.parse(
              JSON.stringify(newItem.propertyList)
            );
            newItem.propertyList.push({
              propKey: name,
              propVal: vItem.val,
            });
            newItem.upload = {
              imageList: [],
              defaultImgList: [],
            };
            // console.log('newItem', newItem)
            newArr.push(newItem);
          });
        });
      }
      // console.log('newArr', newArr)
      return newArr;
    },
    imgHandler(image) {
      if (image) {
        this.$refs.uploadImg.$el.querySelector("[type=file]").click();
      }
    },
    videoHandler(video) {
      if (video) {
        this.$refs.uploadVideo.$el.querySelector("[type=file]").click();
      }
    },

    uploadOnProgress(event, file, fileList) {
      this.editorUploadPercent = parseFloat(event.percent).toFixed(1);
    },
    imgBoforeUpload(file) {
      if (file.size >= 50 * 1024 * 1024) {
        this.$Notice.warning({ title: "上传图片不得超过50MB！" });
        return false;
      }
      this.editorUploadPercent = 0;
      this.editorLoading = true;
    },
    imgUploadSuccess(res, file, fileList) {
      this.editorLoading = false;
      apiVerify({
        res: { data: res },
        success: () => {
          let url = res.data;
          let addImageRange = this.editor.getSelection();
          let newRange = 0 + (addImageRange !== null ? addImageRange.index : 0);
          this.editor.insertEmbed(newRange, "simpleImg", {
            url,
            width: "100%",
          });
          this.editor.setSelection(1 + newRange);
        },
      });
    },
    imgUploadErr() {
      this.editorLoading = false;
      this.$Notice.error({ title: "上传失败，请稍后再试！" });
    },

    videoBoforeUpload(file) {
      if (file.size >= 50 * 1024 * 1024) {
        this.$Notice.warning({ title: "上传视频不得超过50MB！" });
        return false;
      }
      this.editorUploadPercent = 0;
      this.editorLoading = true;
    },
    videoUploadSuccess(res, file, fileList) {
      this.editorLoading = false;
      apiVerify({
        res: { data: res },
        success: () => {
          let url = res.data;
          let addVideoRange = this.editor.getSelection();
          let newRange = 0 + (addVideoRange !== null ? addVideoRange.index : 0);
          this.editor.insertEmbed(newRange, "simpleVideo", {
            url,
            controls: "controls",
            width: "100%",
            poster: getPosterFromVideoUrl(url),
          });
          this.editor.setSelection(1 + newRange);
        },
      });
    },
    videoUploadErr() {
      this.editorLoading = false;
      this.$Notice.error({ title: "上传失败，请稍后再试！" });
    },
  },
};
</script>

<style lang="less">
.sale-info-con {
  .item {
    display: flex;
    align-items: center;
    margin-bottom: 30px;
  }
  .item .label {
    width: 140px;
    margin-right: 10px;
    text-align: right;
    flex-shrink: 0;
  }
  .item .property-con {
    flex: 1;
    padding: 20px;
    border: 1px solid #dcdee2;
    border-radius: 5px;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
  }
  .item .property-con .add-btn {
    width: 100%;
  }
  .del-con {
    margin-left: 5px;
    cursor: pointer;
  }
  .item .property-item {
    width: 240px;
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    padding-right: 30px;
    .prop-val {
      flex: 1;
    }
  }
  .item .pack-con {
    width: 800px;
    // flex: 1;
    padding: 20px;
    border: 1px solid #dcdee2;
    border-radius: 5px;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
  }
  .item .pack-con .add-btn {
    width: 100%;
  }
  .item .pack-item {
    // width: 240px;
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    padding-right: 30px;
    .prop-val {
      flex: 1;
    }
  }

  .item .empty {
    width: 150px;
  }
  .item .opt-btn {
    flex: 1;
    display: flex;
    justify-content: space-between;
  }
  .tip {
    color: #ed4014;
    font-size: 12px;
    margin: 20px 0 5px 0;
  }
  .token-label {
    font-size: 14px;
  }

  .item .time {
    display: flex;
    justify-content: space-around;
  }
  .item .editor-con {
    position: relative;
    width: 600px;
    .spin-icon-load {
      animation: ani-demo-spin 1s linear infinite;
    }
    .ivu-spin {
      border: 1px solid #dcdee2;
      border-radius: 5px;
    }
    .describt-detail {
      width: 100%;
      height: 800px;
      overflow-y: auto;
      padding: 10px;
      border: 1px solid #dcdee2;
      border-radius: 5px;
    }
  }
  .detail-editor {
    > .ql-toolbar {
      border-top-left-radius: 5px;
      border-top-right-radius: 5px;
    }
    > .ql-container {
      height: 800px;
      border-bottom-left-radius: 5px;
      border-bottom-right-radius: 5px;
    }
  }
}
</style>
