<template>
  <div class="execution">

    <basic-container v-loading="loading">

      <el-form :model="form" :rules="rules" ref="refForm" label-width="110px" label-position="left">

        <div class="zm_info_body">

          <div class="zm_info_row">
            <el-form-item label="商品名称" prop="goodsName" >
              <el-input v-model="form.goodsName"
                        placeholder="输入商品名称"
                        maxlength="100"
                        show-word-limit
                        style="width: 230px;"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goodsClassId" style="margin-left: 32px;">
              <el-select v-model="form.goodsClassId" placeholder="请选择商品分类" style="width: 240px;" @change="onClassChange">
                <el-option v-for="item in classOptions" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </div>

          <div class="zm_info_row">
            <el-form-item label="商品规格" prop="skus">
              <div class="layout_v">
                <el-button type="primary" @click="showSpecList = true" :disabled="!canSelectType" style="width: 100px;">
                  添加规格</el-button>
                <el-table :data="form.skus" size="mini">

                  <el-table-column v-for="(spec, index) in specs" :key="index" :label="spec.specName" width="120">

                    <template slot-scope="scope">
                      <span>{{titleValue(spec, scope.row)}}</span>
                    </template>

                  </el-table-column>

                  <el-table-column label="价格" width="160">
                    <template slot-scope="scope">
                      <el-input-number v-model="scope.row.merchantPrice" :precision="2" :step="1" :min="0">
                      </el-input-number>
                    </template>
                  </el-table-column>

                  <el-table-column label="图片" width="120">
                    <template slot-scope="scope">
                      <uploader :size="{width: '60px', height: '60px'}" :urls="scope.row.goodsImage" @change="(list) => { scope.row.goodsImage = list.join(',') }" />
                    </template>
                  </el-table-column>

                  <el-table-column label="商品库存" width="160">
                    <template slot-scope="scope">
                      <el-input-number v-model="scope.row.stock" :step="1" :min="0"></el-input-number>
                    </template>
                  </el-table-column>

                  <el-table-column label="操作" width="120">
                    <template slot-scope="scope">
                      <el-button type="text" @click="onDelete(scope.$index)">删除</el-button>
                    </template>
                  </el-table-column>

                </el-table>
              </div>
            </el-form-item>
          </div>

          <div class="zm_info_row">
            <el-form-item label="商品列表图" prop="listImage">
              <div class="upload">
                <uploader :lazyList="form.listImage" @change="(list) => { form.listImage = list.join(',') }" />
                <span class="sug">上传图片，建议尺寸495*372</span>
              </div>
            </el-form-item>
            <el-form-item label="商品视频">
              <div class="upload">
                <uploader :lazyList="form.videoUrl" :video="true" :image="false" @change="(list) => { form.videoUrl = list.join(',') }" />
                <span class="sug">上传视频，建议视频长度1分钟，仅支持MP4格式</span>
              </div>
            </el-form-item>
          </div>

          <div class="zm_info_row">
            <el-form-item label="商品详情图" prop="detailImage">
              <div class="upload">
                <uploader :lazyList="form.detailImage" :max="9" @change="(list) => { form.detailImage = list.join(',') }" />
                <span class="sug">上传图片，建议尺寸1125*1125</span>
              </div>
            </el-form-item>
          </div>

          <div class="zm_info_row">
            <el-form-item label="商品详情" prop="details" required>
              <editor :content="form.details" height="400px" @changed="onEditorChanged" />
            </el-form-item>
          </div>

          <div class="zm_info_row">
            <el-form-item label="虚拟销售量" prop="fakeNumber">
              <div class="layout_h_v_c">
                <el-input-number v-model="form.fakeNumber" :step="1" :min="0"></el-input-number>
                <div style="margin-left: 10px;">展示销量=虚拟销量+实际销量</div>
              </div>
            </el-form-item>
          </div>

          <div class="zm_info_row">
            <el-form-item label="实名认证" prop="needReal">
              <el-radio-group v-model="form.needReal">
                <el-radio-button :label="true">是，实名认证通过才能购买此商品</el-radio-button>
                <el-radio-button :label="false">否</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </div>

          <div class="zm_info_row">
            <el-form-item label="A币支付" prop="payWithA">
              <el-radio-group v-model="form.payWithA">
                <el-radio-button :label="true">是，可以用A币支付</el-radio-button>
                <el-radio-button :label="false">否</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </div>

          <div class="zm_info_row">
            <el-form-item label="上传视频" prop="needVideo">
              <el-radio-group v-model="form.needVideo">
                <el-radio-button :label="true">是，上传购买视频才能购买此商品</el-radio-button>
                <el-radio-button :label="false">否</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </div>

          <div class="zm_info_row">
            <el-form-item label="电子合同" prop="needContract">
              <el-radio-group v-model="form.needContract">
                <el-radio-button :label="true">是，需要签署电子合同</el-radio-button>
                <el-radio-button :label="false">否</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </div>

          <div class="zm_info_row">
            <el-form-item label="是否发货" prop="needDelivery">
              <el-radio-group v-model="form.needDelivery">
                <el-radio-button :label="true">是</el-radio-button>
                <el-radio-button :label="false">否</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </div>

          <div class="zm_info_row">
            <el-form-item label="推广员佣金" prop="hireRate">
              <div class="layout_h_v_c">
                <el-input-number v-model="form.hireRate" :step="1" :min="0"></el-input-number>
                <div style="margin-left: 10px;">%</div>
              </div>
            </el-form-item>
          </div>

        </div>

      </el-form>

    </basic-container>

    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" :loading="loading" @click="onSubmit">确 认</el-button>
    </span>
    <!-- 规格显示控件 -->
    <type-select v-if="this.form.goodsClassId != undefined" :show="showSpecList" :classId="this.form.goodsClassId"
      @chosen="onChosen" @close="showSpecList = false" />
  </div>
</template>

<script>
  let DBG = false

  import {
    ZmMixin
  } from '@/mixins/ZmMixin.js'

  import {
    mock
  } from './mock_data.js'

  import {
    getClassifyDropDown,
    getGoodsDetails,
    getMerchantByAccount,
  } from './goods_api.js'
  export default {
    mixins: [ZmMixin],
    components: {
      "type-select": () => import('./type_select.vue'),
      "uploader": () => import('@/components/uploader.vue'),
      'editor': () => import('@/components/ckeditor/index.vue')
    },
    data() {
      return {
        //如果是编辑则需要加载数据
        loading: false,
        //是否显示商品规格选择
        showSpecList: false,
        //选择的规格
        specs: [],
        //表单数据
        form: {
          goodsName: "",
          goodsClassId: "",
          listImage: "",
          detailImage: "",
          videoUrl: "",
          authUrl: "",
          details: "",
          fakeNumber: 0,
          needReal: true,
          payWithA: true,
          needVideo: true,
          needContract: true,
          needDelivery: true,
          hireRate: 0,
          skus: [],
        },
        //分类数据
        classOptions: [],
        //校验规则
        rules: {
          goodsName: [{
            required: true,
            trigger: "blur",
            message: "请输入商品名称"
          }],
          goodsClassId: [{
            required: true,
            trigger: "blur",
            message: "请选择商品分类"
          }],
          fakeNumber: [{
            required: true,
            trigger: "blur",
            message: "虚拟销量不能为空"
          }],
          needReal: [{
            required: true,
            trigger: "blur",
            message: "需选择是否实名认证"
          }],
          payWithA: [{
            required: true,
            trigger: "blur",
            message: "需选择是否A币支付"
          }],
          needVideo: [{
            required: true,
            trigger: "blur",
            message: "需选择是否上传视频"
          }],
          needContract: [{
            required: true,
            trigger: "blur",
            message: "需选择是否需要签署电子合同"
          }],
          needDelivery: [{
            required: true,
            trigger: "blur",
            message: "选择是否发货"
          }],
          hireRate: [{
            required: true,
            trigger: "blur",
            message: "请填写推广员佣金比例"
          }],
          listImage: [{
            required: true,
            trigger: "blur",
            validator: (rule, value, callback) => {
              let img = this.form.listImage
              if(img == undefined || img.length == 0) {
                callback(new Error("列表图不能为空"))
              } else {
                callback()
              }
            }
          }],
          detailImage: [{
            required: true,
            trigger: "blur",
            validator: (rule, value, callback) => {
              let detailsList = this.form.detailImage
              if(detailsList == undefined || detailsList.length == 0) {
                callback(new Error("详情图不能为空"))
              } else {
                callback()
              }
            }
          }],
          authUrl: [{
            required: true,
            trigger: "blur",
            validator: (rule, value, callback) => {
              let authUrl = this.form.authUrl
              if(authUrl == undefined || authUrl.length == 0) {
                callback(new Error("请上传认证视频"))
              } else {
                callback()
              }
            }
          }],
          details: [{
            required: true,
            trigger: "blur",
            validator: (rule, value, callback) => {
              let content = this.form.details
              if(content == undefined || content.length == 0) {
                callback(new Error("请填写商品详情"))
              } else {
                callback()
              }
            }
          }],
          skus: [{
            required: true,
            trigger: 'blur',
            validator: (rule, value, callback) => {
              if(this.form.skus.length == 0) {
                callback(new Error("请选择规格"))
                return
              }
              for(let i = 0; i < this.form.skus.length; i++) {
                let sku = this.form.skus[i]
                let merchantPrice = parseFloat(sku.merchantPrice)
                if(isNaN(merchantPrice)) {
                  callback(new Error("第" + (i + 1) + "个规格商品商家价格不正确"))
                  return
                }

                let goodsImage = sku.goodsImage
                if(goodsImage == undefined || goodsImage.length == 0) {
                  callback(new Error("第" + (i + 1) + "个规格商品图片未上传"))
                  return
                }
                let stock = parseInt(sku.stock)
                if(isNaN(stock)) {
                  callback(new Error("第" + (i + 1) + "个规格商品库存不正确"))
                  return
                }
              }
              callback()
            }
          }]
        }
      }
    },
    computed: {
      //能否选择规格
      canSelectType() {
        return this.form.goodsClassId != undefined && this.form.goodsClassId != ''
      },
      //对应表头的值
      titleValue() {
        return (spec, row) => {
          for (let s of row.specs) {
            if (s.specId == spec.specId) {
              return s.name
            }
          }
          return "未知"
        }
      }
    },
    methods: {
      //重新加载
      reload(id) {
        if(id == undefined) {
          this.clearData()
        }
        this.loading = true
        getClassifyDropDown()
          .then(r => {
            this.classOptions = this.zmRes(r)
            if(DBG) {
              this.refill(mock)
            } else {
              if(id != undefined) {
                this.flags=true
                return getGoodsDetails({id: id})
              }
            }
            return Promise.resolve()
          })
          .then(r => {
            this.loading = false
            if(r) {
              let z = this.zmRes(r)
              if(z) {
                this.refill(z)
              }
            }
          })
          .catch(e => {
            this.loading = false

          })
      },
      //清除数据
      clearData() {
        this.form = {
          goodsName: "",
          goodsClassId: "",
          listImage: "",
          detailImage: "",
          videoUrl: "",
          authUrl: "",
          details: "",
          fakeNumber: 0,
          needReal: true,
          payWithA: true,
          needVideo: true,
          needContract: true,
          needDelivery: true,
          hireRate: 0,
          skus: [],
        }
      },
      //回填数据
      refill(data) {
        let skus = data.skus
        if(skus && skus.length > 0) {
          let specs = skus[0].specs.map(r => {
            return {
              specId: r.specId,
              specName: r.specName
            }
          })
          this.specs = specs
        }
        this.form = {
          ...data
        }
      },
      //是否规格组合相同
      isSpecEqual(specA, specB) {
        if (specA.length != specB.length) {
          return false
        }
        if (specA.length == 0) {
          return true
        }
        for (let spec of specA) {
          let find = undefined
          for (let innerSpec of specB) {
            if (innerSpec.specId == spec.specId) {
              find = innerSpec
              break
            }
          }
          if (find == undefined) {
            return false
          }
          if (spec.id != find.id) {
            return false
          }
        }
        return true
      },
      //含有某个规格值的specs
      specsThat(specId, value) {
        let result = {
          hasValue: [],
          notValue: []
        }
        for(let sku of this.form.skus) {
          let specs = sku.specs
          let find = false
          for(let spec of specs) {
            if(spec.specId == specId && spec.id == value.id) {
              find = true
              break
            }
          }
          if(find) {
            result.hasValue.push(specs.filter(s => { return s.specId != specId }))
          } else {
            result.notValue.push(specs.filter(s => { return s.specId != specId }))
          }
        }
        return result
      },
      //specs取差集
      minusCollection(specsA, specsB) {
        let out = []
        for(let specA of specsA) {
          let inB = false
          for(let specB of specsB) {
            if(this.isSpecEqual(specA, specB)) {
              inB = true
              break
            }
          }
          if(!inB) {
            out.push(specA)
          }
        }
        return out
      },
      //删除规格
      onDelete(index) {
        //指定项
        this.form.skus.splice(index, 1)
        //判断是否某个spec已经没有sku对应了，需要删除spec
        let newSpecs = []
        for (let spec of this.specs) {
          let find = false
          for (let sku of this.form.skus) {
            if (find) {
              break
            }
            for (let innerSpec of sku.specs) {
              if (innerSpec.specId == spec.specId) {
                find = true
                break
              }
            }
          }
          if (find) {
            newSpecs.push(spec)
          }
        }
        if (newSpecs.length != this.specs.length) {
          this.specs = newSpecs
        }
      },
      //当选择了规格回调
      onChosen(param) {
        this.showSpecList = false
        //拿到之前的spec查看是否已经添加过
        let oldSpecs = this.specs
        //遍历specs查找是否已经添加过spec
        let find = undefined
        for (let spec of oldSpecs) {
          if (param.specId == spec.specId) {
            //找到了表示之前已经添加过该spec
            find = spec
            break
          }
        }

        if (find != undefined) {
          //遍历每一个新选择的specValue
          let newSkus = []
          for (let value of param.values) {
            //获取含有value的specs 和不含 value的specs集合
            let r = this.specsThat(param.specId, value)
            //不含value的specs与含有value的specs取差集
            let out = this.minusCollection(r.notValue, r.hasValue)
            //组合创建新的specs并新增sku
            for(let specs of out) {
              let newSpec = []
              for(let spec of specs) {
                newSpec.push({...spec})
              }
              newSpec.push({
                specName: param.specName,
                specId: param.specId,
                id: value.id,
                name: value.name
              })
              newSkus.push({
                specs: newSpec,
                merchantPrice: 0,
                sellPrice: 0,
                goodsImage: "",
                stock: 0
              })
            }
          }
          if(newSkus.length > 0) {
            this.form.skus = this.form.skus.concat(newSkus)
          }
        } else {
          //需要新增的skuValue
          let newValue = []

          this.specs.push({
            specId: param.specId,
            specName: param.specName
          })

          //如果没有选择则所有的value都是新增的
          newValue = param.values.map(v => {
            return {
              specName: param.specName,
              specId: param.specId,
              id: v.id,
              name: v.name
            }
          })

          //如果有新增的value,那么需要新增sku
          if (newValue.length > 0) {
            let newSku = []
            //新建不含选择spec的组合
            //如果当前有sku则在原来的基础上新增

            //新增的规格值组合
            let newCombination = newValue.map(v => {
              return [{
                specId: param.specId,
                id: v.id,
                name: v.name
              }]
            })

            //排除当前规格的规格值组合
            let oldCombination = []
            for (let sku of this.form.skus) {
              let newSpecs = sku.specs.filter(spec => {
                return spec.specId != param.specId
              })
              if (newSpecs.length > 0) {
                oldCombination.push(newSpecs)
              }
            }

            let combination = []
            for (let cbn of newCombination) {
              let array = cbn
              if (oldCombination.length > 0) {
                for (let old of oldCombination) {
                  combination.push(array.concat(old))
                }
              } else {
                combination.push(array)
              }
            }

            for (let cmb of combination) {
              newSku.push({
                specs: cmb,
                merchantPrice: 0,
                sellPrice: 0,
                goodsImage: "",
                stock: 0
              })
            }
            this.form.skus = newSku
          }
        }
      },
      //分类发生了变化，则需要清空商品规格
      onClassChange(clazz) {
        this.specs = []
        this.form.skus = []
      },
      //当编辑内容变化时
      onEditorChanged(html) {
        this.form.details = html
      },
      //点击退出
      handleClose() {
        this.$emit('success')
      },
      //点击确认
      onSubmit() {
        this.$refs['refForm'].validate((valid) => {
          if(valid) {
            this.doSubmit()
          }
        })
      },
      //确认提交
      doSubmit: function () {
        let id = this.id
        if(JSON.stringify(id)==='{}'||id===undefined){
          // 1.获取当前登陆用户ID
          let userInfo=  JSON.parse(sessionStorage.getItem("linshenxs-userInfo"))
          let account=userInfo.content.username
          getMerchantByAccount(
            {account: account}
          ).then(response => {
            this.form.merchantId=response.data.data.id
            this.$http.post('/admin/merchantMallGoods/addOrEditGoods',JSON.stringify(this.form),
              {headers:{'Content-Type':'application/json;charset=UTF-8'}})
              .then((res)=>{
                this.$message.success('操作成功')
                this.$emit('success')
              }).catch(e => {
              this.$message.success('操作失败')
            });

          }).catch(() => {
            this.tableLoading = false
          })
        }else{
          this.$http.post('/admin/merchantMallGoods/addOrEditGoods',JSON.stringify(this.form),
            {headers:{'Content-Type':'application/json;charset=UTF-8'}})
            .then((res)=>{
              this.$message.success('操作成功')
              this.$emit('success')
            }).catch(e => {
            this.$message.success('操作失败')
          });
        }
      }
    }
  }
</script>

<style scoped>

  .zm_info_body {
    display: flex;
    flex-direction: column;
    padding: 16px;
  }

  .zm_info_row {
    display: flex;
    flex-direction: row;
    align-items: center;
  }

  >>> .el-input-number__increase {
    right: 1px!important
  }

  .zm_info_body .zm_info_row:not(:first-child) {
    margin-top: 10px;
  }

  .upload {
    display: flex;
    flex-direction: column;
  }

</style>
