<template>
  <div class="app-container">
    <div class="step-container">
      <el-steps :active="step" simple style="margin-top: 20px">
        <el-step title="1.编辑基础信息"></el-step>
        <el-step title="2.编辑价格库存"></el-step>
        <el-step title="3.编辑商品详情"></el-step>
      </el-steps>
    </div>

    <!-- 第一步 -->
    <div class="form-container" v-show="step == 0">
      <el-form ref="step1Form" :model="step1Form" :rules="step1FormRules" label-width="120px">
        <div class="title">以旧换新设置</div>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="商品以旧换新：" prop="isTrade">
              <el-radio-group v-model="step1Form.isTrade">
                <el-radio :label="'YES'">支持</el-radio>
                <el-radio :label="'NO'">不支持</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item label="以旧换新描述：" prop="tradeRemark">
              <el-input v-model="step1Form.tradeRemark" placeholder="请输入以旧换新描述"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <div class="title">基础信息</div>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="品牌：" prop="brand">
              <el-select v-model="step1Form.brand" value-key="id" placeholder="请选择">
                <el-option v-for="item in brandList" :key="item.id" :label="item.brandName" :value="item"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="工单类型：" prop="orderSmallType">
              <el-select v-model="step1Form.orderSmallType" placeholder="请选择">
                <el-option
                  v-for="item in orderTypeList"
                  :key="item.id"
                  :label="item.orderSmallTypeText"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否虚拟商品：" prop="isVr">
              <el-radio-group v-model="step1Form.isVr">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="商品分类：" prop="classify">
              <el-cascader
                placeholder="请选择商品分类"
                :options="classifyList"
                :props="{ value: 'categoryId', label: 'name' }"
                v-model="step1Form.classify"
                filterable
                clearable
              >
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="商品属性：" prop="attrs">
              <el-select v-model="step1Form.attrs" multiple placeholder="请选择商品属性" clearable style="width: 100%">
                <el-option v-for="item in attrList" :key="item" :label="item" :value="item"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="商品标签：" prop="tags">
              <el-select v-model="step1Form.tags" multiple placeholder="请选择商品标签" clearable style="width: 100%">
                <el-option v-for="item in tagList" :key="item" :label="item" :value="item"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="商品名称：" prop="goodsName">
              <div style="display: flex">
                <el-input
                  v-model="step1Form.goodsName"
                  placeholder="请输入商品名称"
                  maxlength="200"
                  show-word-limit
                ></el-input>
                <el-button v-if="type == 'add'" size="mini" @click="isSelectShop = true" type="primary"
                  >从商品库选择</el-button
                >
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="商品描述：" prop="goodsDes">
              <el-input
                v-model="step1Form.goodsDes"
                type="textarea"
                placeholder="请输入商品描述"
                :autosize="{ minRows: 3, maxRows: 6 }"
                maxlength="100"
                show-word-limit
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品主图：" prop="imgUrl">
              <el-upload
                class="avatar-uploader goodsImageUpload"
                style="height: 0"
                :action="baseURL + 'common/upload'"
                :headers="myHeaders"
                :show-file-list="false"
                :on-success="uploadSuccess"
                :before-upload="beforeUpload"
              >
              </el-upload>
              <div class="images">
                <div class="item" style="margin: 0" v-if="step1Form.imgUrl">
                  <div class="img">
                    <el-image
                      ref="goodsImg"
                      :src="$showImgUrl(step1Form.imgUrl)"
                      style="width: 120px; height: 120px"
                      fit="cover"
                      :preview-src-list="[$showImgUrl(step1Form.imgUrl)]"
                    ></el-image>
                    <div class="mask" v-if="step1Form.imgUrl">
                      <div class="row">
                        <div class="it" @click="previewGoodsImage()"><i class="el-icon-search"></i></div>
                        <div class="it" @click="uploadGoodsImage()"><i class="el-icon-upload2"></i></div>
                      </div>
                    </div>
                  </div>
                </div>
                <div class="item" style="margin: 0" v-else>
                  <div class="add" @click="uploadGoodsImage()">
                    <i class="el-icon-plus avatar-uploader-icon"></i>
                  </div>
                </div>
              </div>
              <div class="tips">
                <span>建议尺寸：800*800</span>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品视频：" prop="videoUrl">
              <el-upload
                class="avatar-uploader"
                style="height: 122px"
                :action="baseURL + 'common/upload'"
                :headers="myHeaders"
                :show-file-list="false"
                :on-success="uploadSuccess3"
                :before-upload="beforeUpload3"
              >
                <!-- <img v-if="step1Form.videoUrl" :src="step1Form.videoUrl" class="avatar"> -->
                <video v-if="step1Form.videoUrl" :src="step1Form.videoUrl" height="120" style="display: block"></video>
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
              <div class="tips">
                <span>建议视频宽高比：16:9，建议时长9-30秒</span>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="轮播图：" prop="images">
              <el-upload
                v-if="showImageListUpload2"
                multiple
                :limit="6"
                ref="imageListUpload2"
                class="avatar-uploader2 imageListUpload2"
                style="height: 0"
                :action="baseURL + 'common/upload'"
                :headers="myHeaders"
                name="file"
                :show-file-list="false"
                :on-success="uploadSuccess2"
                :on-exceed="uploadExceed2"
                :before-upload="beforeUpload2"
              >
              </el-upload>
              <div class="images">
                <div class="item" v-for="(item, index) in step1Form.images" :key="index">
                  <div class="img">
                    <el-image
                      :ref="`img${index}`"
                      :src="$showImgUrl(item.url)"
                      style="width: 120px; height: 120px"
                      fit="cover"
                      :preview-src-list="[$showImgUrl(item.url)]"
                    ></el-image>
                    <div class="mask">
                      <div class="row">
                        <div class="it" @click="previewImage(index)"><i class="el-icon-search"></i></div>
                        <div class="it" @click="uploadImage(item.id)"><i class="el-icon-upload2"></i></div>
                        <div class="it" @click="deleteImage(index)"><i class="el-icon-delete"></i></div>
                      </div>
                      <div class="row">
                        <div class="it" @click="moveForward(index)"><i class="el-icon-back"></i><span>前移</span></div>
                        <div class="it" @click="moveBack(index)"><span>后移</span><i class="el-icon-right"></i></div>
                      </div>
                    </div>
                  </div>
                </div>
                <div class="item">
                  <div class="add" @click="uploadImage(0)">
                    <i class="el-icon-plus avatar-uploader-icon"></i>
                  </div>
                </div>
              </div>
              <div class="tips" style="margin-top: 0">
                <span>建议尺寸：800*800，最多上传6张</span>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 第二步 -->
    <div class="form-container" v-show="step == 1">
      <div class="title">价格库存</div>

      <el-form ref="step2Form" :model="step2Form" :rules="step2FormRules" label-width="110px">
        <el-form-item label="规格类型：" label-width="90px">
          <div class="addBtn">
            <el-button type="primary" size="small" @click="addSpec">添加规格</el-button>
            <el-button size="small" @click="toMaterial">去商品物料</el-button>
            <span>注：仓库管理方式为【不管理】，无需填写规格型号，不控制库存</span>
          </div>
        </el-form-item>

        <el-form-item label-width="0">
          <el-upload
            class="editSpecimage-uploader"
            style="height: 0"
            :action="baseURL + 'common/upload'"
            :headers="myHeaders"
            :show-file-list="false"
            :on-success="uploadSuccess6"
            :before-upload="beforeUpload5"
          >
          </el-upload>
          <el-table
            class="specTable"
            :data="specList"
            element-loading-text="Loading"
            border
            highlight-current-row
            stripe
            style="margin-bottom: 20px"
          >
            <el-table-column align="center" label="*大类" prop="mainId" min-width="120">
              <template slot-scope="scope">
                <el-select
                  size="small"
                  v-model="scope.row.mainId"
                  filterable
                  placeholder="请选择"
                  :disabled="scope.row.goodsCode != ''"
                  @change="scope.row.mainName = mainList.find(o => o.categoryId == scope.row.mainId).name"
                >
                  <el-option
                    v-for="item in mainList"
                    :key="item.categoryId"
                    :label="item.name"
                    :value="item.categoryId"
                  >
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column align="center" label="*小类" prop="smallId" min-width="120">
              <template slot-scope="scope">
                <el-select
                  size="small"
                  v-model="scope.row.smallId"
                  filterable
                  placeholder="请选择"
                  :disabled="scope.row.goodsCode != ''"
                  @change="
                    scope.row.smallName = mainList
                      .find(o => o.categoryId == scope.row.mainId)
                      .children.find(o => o.categoryId == scope.row.smallId).name
                  "
                >
                  <el-option
                    v-for="item in scope.row.mainId
                      ? mainList.find(o => o.categoryId == scope.row.mainId).children
                      : []"
                    :key="item.categoryId"
                    :label="item.name"
                    :value="item.categoryId"
                  >
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column align="center" label="*规格名称" prop="specValue" min-width="180">
              <template slot-scope="scope">
                <el-input size="small" v-model="scope.row.specValue" :disabled="scope.row.goodsCode != ''"></el-input>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              :label="`${joinCode == 'NO' ? '' : '*'}规格型号`"
              prop="goodsCode"
              min-width="180"
            >
              <template slot-scope="scope">
                <el-select
                  :disabled="joinCode == 'NO'"
                  size="small"
                  v-model="scope.row.goodsCode"
                  filterable
                  clearable
                  placeholder="请选择"
                  @change="changeSpec(scope.$index, scope.row)"
                >
                  <el-option v-for="item in goodsSpecList" :key="item.id" :label="item.specsName" :value="item.id">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column align="center" label="单位" prop="unit" min-width="120">
              <template slot-scope="scope">
                {{ scope.row.unit | unitFilter }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="*销售价格" prop="price" min-width="120">
              <template slot-scope="scope">
                <el-input size="small" v-model="scope.row.price"></el-input>
              </template>
            </el-table-column>
            <el-table-column align="center" label="*划线价格" prop="orgPrice" min-width="120">
              <template slot-scope="scope">
                <el-input size="small" v-model="scope.row.orgPrice"></el-input>
              </template>
            </el-table-column>
            <el-table-column align="center" label="参考成本价" prop="costAmount" min-width="120">
              <template slot-scope="scope">
                {{ scope.row.costAmount }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="*佣金" prop="shareAmount" min-width="120">
              <template slot-scope="scope">
                <el-input size="small" v-model="scope.row.shareAmount"></el-input>
              </template>
            </el-table-column>
            <el-table-column align="center" label="*内部佣金" prop="innerShareAmount" min-width="120">
              <template slot-scope="scope">
                <el-input size="small" v-model="scope.row.innerShareAmount"></el-input>
              </template>
            </el-table-column>
            <el-table-column align="center" label="*上架库存" prop="stockNum" min-width="120">
              <template slot-scope="scope">
                <el-input size="small" v-model="scope.row.stockNum"></el-input>
              </template>
            </el-table-column>
            <el-table-column align="center" label="总库存数量" prop="stockQty" min-width="120">
              <template slot-scope="scope">
                {{ scope.row.stockQty || 0 }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="*规格图片" prop="imgUrl" min-width="120">
              <template slot-scope="scope">
                <el-image
                  v-if="scope.row.imgUrl"
                  style="width: 40px; height: 40px; cursor: pointer; display: inline-block; margin-top: 6px"
                  :src="$showImgUrl(scope.row.imgUrl)"
                  fit="cover"
                  @click="editSpecImage(scope.$index)"
                >
                </el-image>
                <i
                  v-else
                  class="el-icon-plus avatar-uploader-icon"
                  style="width: 40px; height: 40px; line-height: 40px; cursor: pointer; margin: 6px 0; color: #409eff"
                  @click="editSpecImage(scope.$index)"
                >
                </i>
              </template>
            </el-table-column>

            <el-table-column align="center" label="操作" min-width="120">
              <template slot-scope="scope">
                <!-- <el-button type="text" @click="edit('theory', scope.$index)">编辑</el-button> -->
                <el-popconfirm title="确定删除吗？" @confirm="deleteSpec(scope.$index)" style="margin-left: 10px">
                  <el-button slot="reference" type="text">删除</el-button>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="详情显示库存：" prop="showStock">
              <el-radio-group v-model="step2Form.showStock">
                <el-radio :label="true">显示</el-radio>
                <el-radio :label="false">隐藏</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="详情显示销量：" prop="showSales">
              <el-radio-group v-model="step2Form.showSales">
                <el-radio :label="true">显示</el-radio>
                <el-radio :label="false">隐藏</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="已售件数：" prop="sales">
              <el-input
                v-model="step2Form.sales"
                placeholder="请输入已售件数"
                class="small"
                style="width: 100%"
              ></el-input>
              <div class="tips2">已售件数不计入后台数据统计</div>
            </el-form-item>
          </el-col>
        </el-row>

        <div class="title">其他设置</div>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="运费模版：" prop="freight" label-width="100px">
              <el-select v-model="step2Form.freight" filterable placeholder="请选择运费模版">
                <el-option
                  v-for="item in freightList"
                  :key="item.freightTemplateId"
                  :label="item.name"
                  :value="item.freightTemplateId"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品状态：" prop="status" label-width="90px">
              <el-radio-group v-model="step2Form.status">
                <el-radio :label="true">上架</el-radio>
                <el-radio :label="false">下架</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 第三步 -->
    <div class="form-container" v-show="step == 2">
      <el-form ref="step3Form" :model="step3Form" :rules="step3FormRules" label-width="80px" label-position="top">
        <el-form-item label="说明模块" prop="moduleId">
          <el-select v-model="step3Form.moduleId" filterable placeholder="请选择说明模块" style="width: 300px">
            <el-option
              v-for="item in moduleList"
              :key="item.commonTemplateId"
              :label="item.name"
              :value="item.commonTemplateId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="详情内容" prop="detailContent">
          <el-upload
            ref="imageListUpload"
            class="avatar-uploader2 imageListUpload"
            :action="baseURL + 'common/upload'"
            :headers="myHeaders"
            multiple
            name="file"
            :show-file-list="false"
            :on-success="uploadSuccess4"
            :on-error="uploadError4"
            :before-upload="beforeUpload4"
          >
          </el-upload>
          <!--富文本编辑器组件-->
          <el-row v-loading="quillImgLoading">
            <quill-editor v-model="step3Form.detailContent" ref="myQuillEditor" :options="editorOption"> </quill-editor>
          </el-row>
        </el-form-item>
      </el-form>
    </div>

    <div class="page-footer">
      <div class="footer">
        <el-button @click="changeStep(0)" v-show="step > 0">上一步</el-button>
        <el-button @click="changeStep(1)" v-show="step < 2">下一步</el-button>
        <el-button type="primary" @click="clickSubmitForm" :loading="formLoading">{{
          formLoading ? '提交中 ...' : '提 交'
        }}</el-button>
        <el-popconfirm title="确定关闭吗？" @confirm="goBack" style="margin-left: 10px">
          <el-button slot="reference">关 闭</el-button>
        </el-popconfirm>
      </div>
    </div>
    <!-- 选择商品 -->
    <el-dialog
      title="选择商品"
      :visible.sync="isSelectShop"
      width="90%"
      style="max-height: 95vh; overflow-y: auto"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
    >
      <selectShopDetail @selectShop="selectShop" :isSelectShop="isSelectShop"></selectShopDetail>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import {
  getClassifyList,
  getFreightList,
  addGoods,
  editGoods,
  getGoodsDetail,
  getModuleList,
  getTagList,
  getBrand,
  getGoodsSpecList,
  getMainList
} from '@/api/goods'
import { getTypeList } from '@/api/workOrder/settlementStandardInstall'
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { EventBus } from '@/utils/eventBus'
import selectShopDetail from '../goodsWarehouse/detail'
import { getDetail } from '@/api/goodsWarehouse'
// 工具栏配置
const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'],
  ['blockquote', 'code-block'],
  [{ header: 1 }, { header: 2 }],
  [{ list: 'ordered' }, { list: 'bullet' }],
  [{ script: 'sub' }, { script: 'super' }],
  [{ indent: '-1' }, { indent: '+1' }],
  [{ direction: 'rtl' }],
  [{ size: ['small', false, 'large', 'huge'] }],
  [{ header: [1, 2, 3, 4, 5, 6, false] }],
  [{ color: [] }, { background: [] }],
  [{ font: [] }],
  [{ align: [] }],
  ['link', 'image', 'video']
  // ['clean']
]

export default {
  components: {
    quillEditor,
    selectShopDetail
  },
  filters: {
    unitFilter(val) {
      const MAP = {
        C: '整套',
        I: '单个'
      }
      return MAP[val]
    }
  },
  data() {
    return {
      baseURL: process.env.VUE_APP_BASE_API,
      myHeaders: { 'x-token': getToken() },
      isEdit: false,
      editId: '',

      step: 0,
      step1Form: {
        isTrade: 'NO', // 是否以旧换新
        tradeRemark: '', // 以旧换新描述
        brand: {}, // 品牌
        orderSmallType: '', // 工单类型
        isVr: false, // 是否虚拟商品
        classify: '', // 商品分类
        attrs: [], // 商品属性
        tags: [], // 商品标签
        goodsName: '', // 商品名称
        goodsDes: '', // 商品描述
        imgUrl: '', // 商品主图
        videoUrl: '', // 商品视频
        images: [] // 轮播图
      },
      step1FormRules: {
        brand: [{ required: true, message: '请选择品牌', trigger: 'change' }],
        orderSmallType: [{ required: true, message: '请选择工单类型', trigger: 'change' }],
        isVr: [{ required: true, message: '请选择是否虚拟商品', trigger: 'change' }],
        classify: [{ required: true, message: '请选择商品分类', trigger: 'change' }],
        goodsName: [
          { required: true, message: '请填写商品名称', trigger: 'blur' },
          { required: true, message: '请填写商品名称', trigger: 'change' }
        ],
        imgUrl: [{ required: true, message: '请上传商品主图', trigger: 'change' }],
        images: [{ required: true, message: '请上传轮播图', trigger: 'change' }]
      },
      imagesList: [], // 图片墙展示列表

      brandList: [], // 品牌列表
      classifyList: [], // 商品分类列表
      freightList: [], // 运费模版列表
      moduleList: [], // 说明模块列表
      orderTypeList: [], // 工单类型列表
      goodsSpecList: [], // 规格型号列表

      step2Form: {
        showStock: true, // 详情显示库存
        showSales: true, // 详情显示销量
        sales: '', // 已售件数
        freight: '', // 运费模版
        status: true // 商品状态
      },
      step2FormRules: {
        freight: [{ required: true, message: '请选择运费模版', trigger: 'change' }]
      },

      specList: [],

      step3Form: {
        moduleId: '', // 说明模块
        detailContent: '' // 详情内容
      },
      step3FormRules: {
        detailContent: [{ required: true, message: '请输入详情内容', trigger: 'blur' }]
      },

      quillImgLoading: false, // 富文本上传图片loading
      editorOption: {
        // 富文本配置
        placeholder: '请输入详情内容',
        theme: 'snow',
        modules: {
          toolbar: {
            container: toolbarOptions,
            handlers: {
              image: function (value) {
                if (value) {
                  document.querySelector('.imageListUpload input').click()
                } else {
                  this.quill.format('image', false)
                }
              }
            }
          }
        }
      },

      editorImages: [],

      formLoading: false,

      uploadImageId: null,

      editSpecImageIdx: null,

      mainList: [], // 大类列表
      attrList: [], // 属性列表
      tagList: [], // 标签列表

      showImageListUpload2: false,
      type: 'add',
      isSelectShop: false, //选择商品库

      joinCode: JSON.parse(localStorage.getItem('greemall_user')).joinCode
    }
  },

  computed: {},

  watch: {},

  async created() {
    const { id, type } = this.$route.query
    this.type = type
    this.isEdit = id ? true : false
    this.editId = id

    await this.getClassifyList()
    this.getTagList()
    this.getFreightList()
    this.getModuleList()
    this.getTypeList()
    this.getBrand()
    this.getGoodsSpecList()
    this.getMainList()

    if (this.isEdit) {
      this.getGoodsDetail(id)
    }
  },
  methods: {
    //选择商品库商品
    selectShop(goodsLibraryId) {
      this.isSelectShop = false
      if (goodsLibraryId) {
        getDetail({
          goodsLibraryId
        }).then(res => {
          let imgs = []
          let goodsLibrarySpecList = []
          res.data.imgs.split(',').forEach(item => {
            imgs.push({
              url: item
            })
          })
          res.data.goodsLibrarySpecList.forEach(item => {
            goodsLibrarySpecList.push({
              goodsCode: '', // 物料编号
              mainId: '', // 大类id
              mainName: '', // 大类名称
              smallId: '', // 小类id
              smallName: '', // 小类名称
              specValue: item.specValue, // 商品名称
              specsName: '', // 规格名称
              unit: '', // 单位
              price: item.price, // 销售价格
              orgPrice: item.orgPrice, // 划线价格
              costAmount: item.costPrice, // 成本价格
              shareAmount: item.shareAmount, // 分销金额
              innerShareAmount: item.innerShareAmount, // 内部分销金额
              stockNum: '', // 上架库存
              stockQty: '', // 当前库存
              imgUrl: item.imgUrl // 图片
            })
          })
          this.step1Form = {
            ...this.step1Form,
            goodsName: res.data.goodsName, // 商品名称
            goodsDes: res.data.describeText, // 商品描述
            imgUrl: res.data.imgUrl, // 商品主图
            videoUrl: res.data.vedio, // 商品视频
            images: res.data.imgs ? imgs : [] // 轮播图
          }
          this.specList = [...this.specList, ...goodsLibrarySpecList]
          this.step3Form.detailContent = res.data.content
          this.$refs.step1Form.validateField('goodsName')
        })
      }
    },

    // 获取商品分类列表
    async getClassifyList() {
      return new Promise((resolve, reject) => {
        let params = {
          name: '',
          categoryLevel: 1,
          status: true
        }
        getClassifyList(params)
          .then(res => {
            this.classifyList = res.data
          })
          .finally(res => {
            resolve()
          })
      })
    },

    // 获取工单类型列表
    getTypeList() {
      getTypeList({
        pageNum: 1,
        pageSize: -1,
        params: [{ param: 'a.status', compare: '=', value: true }]
      }).then(res => {
        this.orderTypeList = res.data.records
      })
    },

    // 获取品牌列表
    getBrand() {
      getBrand().then(res => {
        this.brandList = res.data
      })
    },

    // 获取商品属性列表
    getTagList() {
      getTagList({
        dictType: 'GOODS_ATTR'
      }).then(res => {
        let list = []
        res.data.forEach(item => {
          list.push(item.dictValue)
        })
        this.attrList = list
      })

      // 获取商品标签列表
      getTagList({
        dictType: 'GOODS_TAG'
      }).then(res => {
        let list = []
        res.data.forEach(item => {
          list.push(item.dictValue)
        })
        this.tagList = list
      })
    },

    // 获取运费模版
    getFreightList() {
      getFreightList({
        pageNum: 1,
        pageSize: -1,
        status: true
      }).then(res => {
        this.freightList = res.data.records
        console.log(this.freightList)
      })
    },

    // 获取说明模块列表
    getModuleList() {
      getModuleList({
        pageNum: 1,
        pageSize: -1
      }).then(res => {
        this.moduleList = res.data.records
      })
    },

    // 获取规格列表
    getGoodsSpecList() {
      getGoodsSpecList({
        pageNum: 1,
        pageSize: -1,
        specsName: ''
      }).then(res => {
        this.goodsSpecList = res.data.records
      })
    },

    // 获取大类列表
    getMainList() {
      getMainList({
        type: 2,
        status: true
      }).then(res => {
        this.mainList = res.data
      })
    },

    // 获取详情
    getGoodsDetail(goodsId) {
      getGoodsDetail({ goodsId }).then(res => {
        let data = res.data

        // 第一步
        this.step1Form = {
          isTrade: data.isTrade,
          tradeRemark: data.tradeRemark,
          brand: { id: data.brandId, brandName: data.brandName },
          orderSmallType: data.orderSmallType,
          isVr: data.isVr,
          classify: data.categoryId,
          attrs: data.tags,
          tags: data.tagsLabel,
          goodsName: data.goodsName,
          goodsDes: data.describeText,
          imgUrl: data.imgUrl,
          videoUrl: data.vedio
        }
        this.$set(this.step1Form, 'images', data.images)

        // 第二步
        this.step2Form = {
          showStock: data.showDetailStock,
          showSales: data.showDetailSold,
          sales: data.soldNum,
          freight: data.freightTemplateId,
          status: data.status
        }
        data.goodsSpecs.forEach(item => {
          item.stockQty = item.goodsMaterialStock
        })
        this.specList = data.goodsSpecs

        // 第三步
        this.step3Form = {
          moduleId: data.templateId,
          detailContent: data.content
        }
      })
    },

    // 切换步骤
    changeStep(type) {
      if (type == 1) {
        this.step++
      } else {
        this.step--
      }
    },

    // 将数组加上索引
    listAddIndex(arr) {
      arr.forEach((item, index) => {
        item.index = index
      })
      return arr
    },

    // 添加规格
    addSpec() {
      let obj = {
        goodsCode: '', // 物料编号
        mainId: '', // 大类id
        mainName: '', // 大类名称
        smallId: '', // 小类id
        smallName: '', // 小类名称
        specValue: '', // 商品名称
        specsName: '', // 规格名称
        unit: '', // 单位
        price: '', // 销售价格
        orgPrice: '', // 划线价格
        costAmount: '', // 成本价格
        shareAmount: '', // 分销金额
        innerShareAmount: '', // 内部分销金额
        stockNum: '', // 上架库存
        stockQty: '', // 当前库存
        imgUrl: '' // 图片
      }
      let item = JSON.parse(JSON.stringify(obj))
      this.specList.push(item)
      console.log(this.specList)
    },

    // 删除规格
    deleteSpec(index) {
      this.specList.splice(index, 1)
    },

    // 选择规格型号
    changeSpec(index, row) {
      let item = this.goodsSpecList.find(o => o.id == row.goodsCode) || {}
      this.specList[index].goodsCode = item.id || ''
      this.specList[index].mainId = item.mainId || ''
      this.specList[index].mainName = item.mainName || ''
      this.specList[index].smallId = item.smallId || ''
      this.specList[index].smallName = item.smallName || ''
      this.specList[index].specValue = item.specsName || ''
      this.specList[index].specsName = item.specsName || ''
      this.specList[index].unit = item.unit || ''
      this.specList[index].costAmount = item.costAmount || ''
      this.specList[index].stockQty = item.stockQty || ''
    },

    // 点击 提交表单
    clickSubmitForm() {
      // 验证第一步
      this.$refs.step1Form.validate(valid => {
        if (valid) {
          // 验证第二步
          this.$refs.step2Form.validate(valid => {
            if (valid) {
              if (this.specList.length < 1) return this.$errorMsg('请添加规格类型')

              for (let i = 0; i < this.specList.length; i++) {
                if (!this.specList[i].mainId) return this.$errorMsg('请选择大类')
                if (!this.specList[i].smallId) return this.$errorMsg('请选择小类')
                if (!this.specList[i].specValue) return this.$errorMsg('请填写规格名称')
                if (!this.specList[i].goodsCode && this.joinCode != 'NO') return this.$errorMsg('请选择规格型号')
                if (!this.specList[i].price) return this.$errorMsg('请填写销售价格')
                if (!this.specList[i].orgPrice) return this.$errorMsg('请填写划线价格')
                if (!this.specList[i].shareAmount) return this.$errorMsg('请填写佣金')
                if (!this.specList[i].innerShareAmount) return this.$errorMsg('请填写内部佣金')
                if (!this.specList[i].stockNum) return this.$errorMsg('请填写商品库存')
                if (!this.specList[i].imgUrl) return this.$errorMsg('请上传规格图片')
              }

              // 验证第三步
              this.$refs.step3Form.validate(valid => {
                if (valid) {
                  this.submitForm()
                } else {
                  this.step = 2
                }
              })
            } else {
              this.step = 1
            }
          })
        } else {
          this.step = 0
        }
      })
    },

    // 提交表单
    submitForm() {
      this.formLoading = true

      let images = []
      for (let i = 0; i < this.step1Form.images.length; i++) {
        let obj = {}
        obj.id = this.step1Form.images[i].id
        images.push(obj)
      }

      let categoryId = ''
      if (typeof this.step1Form.classify == 'string') {
        categoryId = this.step1Form.classify
      } else {
        categoryId = this.step1Form.classify[1]
      }

      let params = {
        // 第一步
        isTrade: this.step1Form.isTrade,
        tradeRemark: this.step1Form.tradeRemark,
        brandId: this.step1Form.brand.id,
        brandName: this.step1Form.brand.brandName,
        orderSmallType: this.step1Form.orderSmallType,
        isVr: this.step1Form.isVr,
        categoryId: categoryId,
        tags: this.step1Form.attrs,
        tagsLabel: this.step1Form.tags,
        goodsName: this.step1Form.goodsName,
        describeText: this.step1Form.goodsDes,
        imgUrl: this.step1Form.imgUrl,
        vedio: this.step1Form.videoUrl,
        images: images,

        // 第二步
        goodsSpecs: this.specList,
        showDetailStock: this.step2Form.showStock,
        showDetailSold: this.step2Form.showSales,
        soldNum: this.step2Form.sales,
        freightTemplateId: this.step2Form.freight,
        status: this.step2Form.status,

        // 第三步
        templateId: this.step3Form.moduleId,
        content: this.step3Form.detailContent
      }
      console.log(params)

      if (this.isEdit) {
        params.goodsId = this.editId
        editGoods(params)
          .then(res => {
            this.formLoading = false
            // this.$refs.mainForm.resetFields();
            this.$successMsg('编辑成功')
            setTimeout(() => {
              this.goBack()
            }, 1000)
          })
          .catch(err => {
            this.formLoading = false
          })
      } else {
        addGoods(params)
          .then(res => {
            this.formLoading = false
            // this.$refs.mainForm.resetFields();
            this.$successMsg('新增成功')
            setTimeout(() => {
              this.goBack()
            }, 1000)
          })
          .catch(err => {
            this.formLoading = false
          })
      }
    },

    goBack() {
      this.$router.go(-1)
      EventBus.$emit('updateGoodsListPage')
      // this.$store.dispatch("tagsView/delView", this.$route);
    },

    // 商品主图 - 上传成功
    uploadSuccess(res, file) {
      this.step1Form.imgUrl = res.data.url
    },

    // 商品主图 - 上传前
    beforeUpload(file) {
      const fileSuffix = file.name.substring(file.name.lastIndexOf('.') + 1)
      const whiteList = ['jpg', 'jpeg', 'png']
      if (whiteList.indexOf(fileSuffix) === -1) {
        this.$('请添加规格类型')('只支持上传jpg/png文件!')
        return false
      }
    },

    uploadGoodsImage() {
      document.querySelector('.goodsImageUpload input').click()
    },

    previewGoodsImage() {
      this.$refs.goodsImg.clickHandler()
    },

    // 商品视频 - 上传成功
    uploadSuccess3(res, file) {
      this.step1Form.videoUrl = res.data.url
    },

    // 商品视频 - 上传前
    beforeUpload3(file) {
      const fileSuffix = file.name.substring(file.name.lastIndexOf('.') + 1)
      const whiteList = ['AVI', 'mov', 'rmvb', 'rm', 'FLV', 'mp4']
      if (whiteList.indexOf(fileSuffix) === -1) {
        this.$('请添加规格类型')('只支持上传视频文件!')
        return false
      }
    },

    // 水印logo - 上传成功
    uploadSuccess7(res, file) {
      this.step1Form.logoUrl = res.data.url
    },

    // 水印logo - 上传前
    beforeUpload7(file) {
      const fileSuffix = file.name.substring(file.name.lastIndexOf('.') + 1)
      const whiteList = ['jpg', 'jpeg', 'png']
      if (whiteList.indexOf(fileSuffix) === -1) {
        this.$('请添加规格类型')('只支持上传jpg/png文件!')
        return false
      }
    },

    // 规格图片 - 上传成功
    uploadSuccess5(res, file) {
      this.specForm.imgUrl = res.data.url
    },

    // 规格图片 - 上传前
    beforeUpload5(file) {
      const fileSuffix = file.name.substring(file.name.lastIndexOf('.') + 1)
      const whiteList = ['jpg', 'jpeg', 'png']
      if (whiteList.indexOf(fileSuffix) === -1) {
        this.$('请添加规格类型')('只支持上传jpg/png文件!')
        return false
      }
    },

    // 富文本图片 - 上传前
    beforeUpload4() {
      this.quillImgLoading = true
    },

    // 富文本图片 - 上传成功
    uploadSuccess4(res, file, fileList) {
      console.log(fileList)
      fileList.forEach(item => {
        if (this.editorImages.indexOf(item.response.data.url) < 0) {
          this.editorImages.push(item.response.data.url)
        }
      })
      this.showImage()
      this.quillImgLoading = false
    },

    // 富文本图片 - 显示图片
    showImage() {
      console.log(this.editorImages)
      let quill = this.$refs.myQuillEditor.quill
      this.editorImages.forEach(item => {
        // 获取光标所在位置
        let length = quill.getSelection().index
        // 插入图片  res.info为服务器返回的图片地址
        console.log(item)
        quill.insertEmbed(length, 'image', item)
        // this.$refs.imageListUpload.clearFiles()
        // 调整光标到最后
        quill.setSelection(length + 1)
      })
      this.editorImages = []
      this.$refs.imageListUpload.clearFiles()
    },

    // 富文本图片 - 上传失败
    uploadError4() {
      this.quillImgLoading = false
      this.$('请添加规格类型')('图片插入失败')
    },

    // 轮播图 - 点击上传图片
    uploadImage(id) {
      if (this.step1Form.images.length >= 6) {
        this.$('请添加规格类型')('最多上传6张轮播图')
        return
      }

      this.showImageListUpload2 = false
      this.$nextTick(() => {
        this.showImageListUpload2 = true
        this.$nextTick(() => {
          this.uploadImageId = id
          document.querySelector('.imageListUpload2 input').click()
        })
      })
    },

    // 轮播图 - 上传成功
    uploadSuccess2(res, file) {
      if (this.uploadImageId) {
        let index = this.$findElem(this.step1Form.images, 'id', this.uploadImageId)
        this.$set(this.step1Form.images, index, res.data)
      } else {
        if (this.step1Form.images.length >= 6) {
          return this.$('请添加规格类型')('最多上传6张轮播图')
        }
        this.step1Form.images.push(res.data)
      }
    },

    // 轮播图 - 超出限制数量
    uploadExceed2(files, fileList) {
      return this.$('请添加规格类型')('最多上传6张轮播图')
    },

    // 轮播图 - 上传前
    beforeUpload2(file) {
      const fileSuffix = file.name.substring(file.name.lastIndexOf('.') + 1)
      const whiteList = ['jpg', 'jpeg', 'png']
      if (whiteList.indexOf(fileSuffix) === -1) {
        this.$('请添加规格类型')('只支持上传jpg/jpeg/png文件!')
        return false
      }
    },

    // 轮播图 - 预览
    previewImage(index) {
      this.$refs[`img${index}`][0].clickHandler()
    },

    // 轮播图 - 删除图片
    deleteImage(index) {
      this.step1Form.images.splice(index, 1)
    },

    // 轮播图 - 向前移动
    moveForward(index) {
      if (index != 0) {
        let arr = this.step1Form.images
        let thisItem = arr[index]
        let targetItem = arr[index - 1]
        this.$set(this.step1Form.images, index, targetItem)
        this.$set(this.step1Form.images, index - 1, thisItem)
      } else {
        this.$('请添加规格类型')('已经最前，无法前移')
      }
    },

    // 轮播图 - 向后移动
    moveBack(index) {
      if (index + 1 < this.step1Form.images.length) {
        let arr = this.step1Form.images
        let thisItem = arr[index]
        let targetItem = arr[index + 1]
        this.$set(this.step1Form.images, index, targetItem)
        this.$set(this.step1Form.images, index + 1, thisItem)
      } else {
        this.$('请添加规格类型')('已经最后，无法后移')
      }
    },

    // 编辑规格图 - 点击图片
    editSpecImage(index) {
      this.editSpecImageIdx = index
      document.querySelector('.editSpecimage-uploader input').click()
    },

    // 编辑规格图 - 上传成功
    uploadSuccess6(res, file) {
      this.specList[this.editSpecImageIdx].imgUrl = res.data.url
    },

    toMaterial() {
      this.$router.push({
        name: 'commercialMaterial',
        query: {}
      })
    }
  }
}
</script>

<style scoped lang="scss">
.step-container {
  padding: 0 10%;
}

.form-container {
  margin-top: 40px;
  padding: 0 10%;

  .title {
    font-size: 16px;
    margin-bottom: 30px;
    padding-left: 10px;
    font-weight: bold;
  }

  .tips {
    margin-top: 10px;

    span {
      display: inline-block;
      width: 300px;
      text-align: center;
      line-height: 32px;
      background: #ffefef;
      font-size: 14px;
      color: #f66460;
    }
  }

  .tips2 {
    font-size: 12px;
    color: #999999;
    line-height: 30px;
  }

  .container {
    padding: 10px 20px 0;
    background: #f5f5f5;
    border-radius: 10px;
  }

  .addBtn {
    padding: 10px 0;
    margin-top: -10px;
    span {
      margin-left: 10px;
      color: #f66460;
    }
  }
}

@media only screen and (max-width: 1200px) {
  .form-container {
    padding: 0 10%;
  }
}

@media only screen and (max-width: 768px) {
  .step-container {
    padding: 0;
  }

  .form-container {
    padding: 0 5%;
  }
}
</style>

<style lang="scss">
.specTable .el-table__cell {
  padding: 0 !important;
}

// 图片墙
.el-upload-list--picture-card .el-upload-list__item {
  width: 100px;
  height: 100px;
}

.el-upload--picture-card {
  width: 100px;
  height: 100px;
  line-height: 100px;

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
}

.avatar-uploader2 {
  height: 0;
}

.container {
  .el-form-item__label {
    padding-bottom: 0;
  }

  .el-form-item {
    margin-bottom: 5px;
  }
}

.ql-editor {
  min-height: 300px;
}
</style>

<style scoped lang="scss">
.images {
  display: flex;
  flex-wrap: wrap;

  .item {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    width: 120px;
    margin-right: 20px;
    margin-bottom: 20px;

    .img {
      border: 1px dashed #eaeaea;
      border-radius: 5px;
      overflow: hidden;
      position: relative;

      .el-image {
        display: block;
      }

      .mask {
        position: absolute;
        left: 0;
        top: 0;
        width: 120px;
        height: 120px;
        background: rgba($color: #000000, $alpha: 0.5);
        display: flex;
        align-items: center;
        justify-content: center;
        flex-direction: column;
        opacity: 0;

        &:hover {
          opacity: 1;
        }

        .row {
          display: flex;
          align-items: center;
          justify-content: center;

          .it {
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            margin: 5px;

            i {
              font-size: 20px;
              color: #ffffff;
            }

            span {
              font-size: 14px;
              color: #ffffff;
            }
          }
        }
      }
    }

    .add {
      border: 1px dashed #eaeaea;
      border-radius: 5px;
      cursor: pointer;

      .avatar-uploader-icon {
        width: 120px;
        height: 120px;
        line-height: 120px;
      }

      &:hover {
        border: 1px dashed #66b1ff;
      }
    }
  }
}
</style>
