<template>
  <div element-loading-text="加载中" class="app-container">
    <el-form ref="addGoods" :model="goods" :rules="goodRules" label-width="100px">
      <template>
        <div class="step-title">第一步: 填写商品基本信息</div>
        <div style="display: flex; flex-wrap: wrap; justify-content: space-between;">
          <el-form-item style="width: 50%;" label="商品名称:" prop="name">
            <el-input v-model="goods.name" type="text" maxlength="32" show-word-limit size="small" />
          </el-form-item>
          <el-form-item style="width: 50%;" label="副标题:">
            <el-input v-model="goods.desc" size="small" />
          </el-form-item>
          <el-form-item style="width: 50%;" label="商品类型:">
            <el-cascader v-model="goods.type" disabled :options="typeList" :props="{ expandTrigger: 'hover' }" style="width: 100%" @change="handleChange">
              <template slot-scope="{ node, data }">
                <div v-if="data.value === 0" style="text-align: center;">
                  <i class="el-icon-circle-plus-outline" />&nbsp;&nbsp;新增
                </div>
                <div v-else>
                  <span>{{ data.label }}</span>
                  <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
                </div>
              </template>
            </el-cascader>
          </el-form-item>
          <el-form-item style="width: 50%;" label="商品单位:">
            <el-select v-model="goods.unit" placeholder="请选择" style="width: 100%">
              <el-option label="套" value="套" />
              <el-option label="件" value="件" />
              <el-option label="副" value="副" />
              <el-option label="盒" value="盒" />
            </el-select>
          </el-form-item>
          <!-- <el-form-item style="width: 50%;" label="是否上架：">
            <el-switch v-model="goods.is_show" />
          </el-form-item> -->
        </div>
        <el-form-item label="上传主图:" required>
          <el-upload :action="upload_url" :show-file-list="false" :http-request="thumbPictureUpload">
            <el-button size="mini">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">(建议尺寸画布600*480，大小50K,只能上传1张，如需修改请重新上传主图)</div>
          </el-upload>
          <div v-if="goods.thumb_url">
            <img :src="goods.thumb_url" class="thumbUrl">
          </div>
        </el-form-item>
        <el-form-item label="上传轮播图" required>
          <el-upload ref="bannerUpload" :action="upload_url" multiple :limit="15" :show-file-list="false" :http-request="bannerPictureUpload">
            <el-button size="mini">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">(建议尺寸画布600*480，大小50K)</div>
          </el-upload>
          <ul v-if="goods.banner_url.length>0" class="banner_list">
            <li v-for="(item, i) in goods.banner_url" :key="i" class="banner_item">
              <img :src="item">
              <div class="remove" @click="deleteBanner(i)">删除</div>
            </li>
          </ul>
        </el-form-item>
        <el-form-item label="商品详情:" required>
          <editor ref="infoEditor" :value="goods.content" />
        </el-form-item>
      </template>

      <template>
        <div class="step-title">第二步: 填写商品规格</div>
        <el-form-item label="规格设置:" required="">
          <div v-if="setSkuFlag">
            <div style="margin:10px 0">
              <add-tag v-for="(val, key, i) in tagList" :key="i" :title="changeKeyShow(key)" edit="edit" :typeid="goods.type[1]" :tag-list="val" @deleteSku="deleteTagResetSku" @numChange="numChange" @addSize="id => { tagList.num.push(100); goods.id.push(id) }" />
            </div>
          </div>
        </el-form-item>
        <el-form-item label="价格设置" required>
          <div class="many_price_set">
            <el-input v-model="goods.hgPrice" placeholder="请输入价格" type="number" size="small" style="width:350px;margin-bottom:10px;">
              <template slot="prepend">代理公司价格</template>
            </el-input>
          </div>
        </el-form-item>
      </template>
      <template>
        <el-button size="small">取消</el-button>
        <el-button type="primary" size="small" @click="handleSubmit">修改</el-button>
      </template>
    </el-form>
    <el-dialog top="50px" :visible.sync="dialogBannerVisable" size="tiny">
      <img v-for="(item, i) in goods.bannerUrl" :key="i" width="100%" :src="item">
    </el-dialog>
    <div v-if="thumbLoad" v-loading="thumbLoad" class="loadingShade" />
  </div>
</template>

<script>
// api
import { uploadImage, updateGoods, getTypeList, getAddType, getInfo } from '@/api/goods/index'

import { ismoney } from '@/filters/index'
// 组件
import AddTag from './components/tag'
export default {
  name: 'GoodsEdit',
  components: { AddTag },
  data() {
    return {
      upload_url: 'http://192.168.0.15:8011/api/goods/uploadgoodsimage',
      goodRules: {
        name: [
          { required: true, message: '请输入商品名称', trigger: 'change' }
        ]
      },
      typeList: [],
      goods: {
        name: '',
        desc: '',
        content: '',
        banner_url: [],
        thumb_url: '',
        hgPrice: '',
        djPrice: '',
        tjPrice: '',
        type: '',
        is_show: false,
        total: '',
        unit: '套'
      },
      dialogBannerVisable: false,
      addTag: '',
      tagList: {
        size: ['S', 'M', 'L', 'XL', 'XXL', 'XXXL'],
        num: [100, 100, 100, 100, 100, 100]
        // color: ['红色', '黑色'],
        // type: ['男款(黑色)', '女款(黑色)']
      },
      spaceTable: [],
      thumbLoad: false,
      setSkuFlag: true,
      defaultTotal: '1'
    }
  },
  // 这一块主要作用为了关联商品规格和单个商品价格(sku)
  computed: {
    tagTable() {
      const tagList = Object.assign({}, this.tagList)
      return Object.values(tagList)
    },
    tagKeys() {
      const tagList = Object.assign({}, this.tagList)
      return Object.keys(tagList)
    }
  },
  mounted() {
    this.getTypeList()
  },
  methods: {
    getTypeList(click) {
      this._loading = this.$loading()
      getTypeList().then(({ data: { list }}) => {
        const add = list => {
          list.push({ label: '新增', value: 0 })
          list.forEach(e => {
            if (e.children) {
              add(e.children)
            }
          })
        }
        add(list)
        this.typeList = list
        this._loading.close()
        if (click) {
          document.getElementsByClassName('el-cascader')[0].click()
        }
        this.$request(getInfo({ id: this.$route.params.id }), ({ banner_url, content, desc, hgPrice, main_img, name, tagList, type, unit, id }) => {
          this.goods.banner_url = banner_url
          console.log(this.goods.banner_url)
          this.goods.content = content.toString()
          this.goods.desc = desc
          this.goods.hgPrice = hgPrice
          this.goods.thumb_url = main_img
          this.goods.name = name
          this.tagList = tagList
          this.goods.unit = unit
          this.goods.type = type
          this.goods.id = id
        })
      })
    },
    handleChange(val) {
      val.reverse()
      if (val[0] === 0) {
        this.$prompt('请输入新的类别', '提示', {
          inputPattern: /.+/,
          inputErrorMessage: '类别不能为空'
        }).then(({ value }) => {
          this._loading = this.$loading()
          getAddType({ pid: val[1] ? val[1] : 0, name: value }).then(() => {
            this.goods.type = ''
            this.getTypeList(true)
          })
        }).catch(() => {
          this.goods.type = ''
          document.getElementsByClassName('el-cascader')[0].click()
          this.$message.info('取消添加')
        })
      }
    },
    // 上传主图(缩略图)
    thumbPictureUpload(params) {
      this.thumbLoad = true
      const file = params.file
      const imgType = ['image/png', 'image/jpg', 'image/jpeg']
      if (imgType.indexOf(file.type) === -1) {
        this.$message.warning('上传图片格式必须为: png或jpg格式')
        return false
      }
      const formdata = new FormData()
      formdata.append('file', file)
      uploadImage(formdata).then(res => {
        this.thumbLoad = false
        try {
          const { message, code, data } = res
          if (code === 200) {
            this.goods.thumb_url = data
          } else {
            this.goods.thumb_url = ''
            this.$message.error(message)
          }
        } catch (e) {
          console.log(`上传商品主图失败: ${e}`)
        }
      }).catch(() => {
        this.thumbLoad = false
      })
    },
    // 轮播图上传
    bannerPictureUpload(params) {
      this.thumbLoad = true
      const file = params.file
      const imgType = ['image/png', 'image/jpg', 'image/jpeg']
      if (imgType.indexOf(file.type) === -1) {
        this.$message.warning('上传图片格式必须为: png或jpg格式')
        return false
      }
      const formdata = new FormData()
      formdata.append('file', file)
      uploadImage(formdata).then(res => {
        this.thumbLoad = false
        try {
          const { message, code, data } = res
          if (code === 200) {
            // console.log(data)
            this.goods.banner_url.push(data)
            console.log(this.goods.banner_url)
          } else {
            this.$message.error(message)
          }
        } catch (e) {
          console.log(`上传轮播图失败: ${e}`)
        }
      }).catch(() => {
        this.thumbLoad = false
      })
    },
    // 删除某一个轮播图
    deleteBanner(i) {
      this.goods.banner_url.splice(i, 1)
      console.log(this.goods.banner_url)
    },
    // 添加规格(规格设置)
    handleAddTag() {
      if (!this.addTag) {
        this.$message.error('规格设置不能为空')
        return false
      }
      const flag = this.tagList[this.addTag]
      if (flag) {
        this.$message({
          message: '已存在相同的规格',
          type: 'warning'
        })
        return false
      }
      this.$set(this.tagList, this.addTag, [])
      this.addTag = ''
    },
    // 转换显示
    changeKeyShow(key) {
      let out
      switch (key) {
        case 'size':
          out = '尺码'
          break
        case 'color':
          out = '颜色'
          break
        case 'type':
          out = '款式(颜色)'
          break
        case 'num':
          out = '数量'
          break
        default:
          out = '规格'
      }
      return out
    },
    // 删除标签时重置sku
    deleteTagResetSku(index) {
      this.goods.id.splice(index, 1)
      this.tagList.num.splice(index, 1)
      if (this.spaceTable.length > 0) {
        const { hgPrice, djPrice, tjPrice } = this.goods
        if (!hgPrice || !djPrice || !tjPrice) {
          this.$message.warning('价格填写不完整')
          return false
        }
        if (!ismoney(hgPrice) || !ismoney(djPrice) || !ismoney(tjPrice)) {
          this.$message.warning('价格格式错误')
          return false
        }
        const table = this.deepGenerateSpaces(this.tagTable)
        if (table.length < 1) {
          this.$message.warning('请添加商品规格')
          this.spaceTable = []
          return false
        }
        table.map((item, i) => {
          item['tjPrice'] = tjPrice
          item['djPrice'] = djPrice
          item['hgPrice'] = hgPrice
        })
        this.spaceTable = table
      }
    },
    // 批量设置sku
    handleManySetSku() {
      const { hgPrice, djPrice, tjPrice } = this.goods
      if (!hgPrice || !djPrice || !tjPrice) {
        this.$message.warning('价格填写不完整')
        return false
      }
      if (!ismoney(hgPrice) || !ismoney(djPrice) || !ismoney(tjPrice)) {
        this.$message.warning('价格格式错误')
        return false
      }
      const table = this.deepGenerateSpaces(this.tagTable)
      if (table.length < 1) {
        this.$message.warning('请添加商品规格')
        this.spaceTable = []
        return false
      }
      table.map((item, i) => {
        item['tjPrice'] = tjPrice
        item['djPrice'] = djPrice
        item['hgPrice'] = hgPrice
      })
      this.spaceTable = table
    },
    // 渲染sku
    renderSkuTable(row) {
      const valArr = Object.values(row)
      const outArr = valArr.slice(0, valArr.length - 3)
      return outArr.join('+')
    },
    // 根据tagList相关生成table设置
    deepGenerateSpaces(arr) {
      if (arr.length === 0) {
        return []
      } else {
        const table = this.recursionSpaces([], 0)
        return table
      }
    },
    // 根据tagList相关生成table设置->递归遍历生成table
    recursionSpaces(out, start) {
      const arr = Object.assign([], this.tagTable).filter(item => {
        return item.length > 0
      })
      if (arr.length < 1) {
        return []
      }
      const keysArr = this.tagKeys
      const end = arr.length
      let ipt = []
      for (let i = 0; i < arr[start].length; i++) {
        if (out.length === 0) {
          const data = {}
          data[keysArr[start]] = arr[start][i]
          ipt.push(data)
        } else {
          for (let j = 0; j < out.length; j++) {
            const data = Object.assign({}, out[j])
            data[keysArr[start]] = arr[start][i]
            ipt.push(data)
          }
        }
      }
      start += 1
      if (start < end) {
        ipt = this.recursionSpaces(ipt, start)
      }
      return ipt
    },
    // 删除单个sku
    handleDeleteGoodsSku(index) {
      this.spaceTable.splice(index, 1)
    },
    // 添加转换
    submitChange(goodsSku) {
      const out = Object.assign([], goodsSku)
      out.map(item => {
        item['type'] = `${item.type}(${item.color})`
        delete item['color']
      })
      return out
    },
    // 添加
    handleSubmit() {
      const { name, desc, banner_url, thumb_url, hgPrice, type, unit, is_show } = this.goods
      const content = this.$refs.infoEditor.getContent()
      // const goodsSku = this.spaceTable
      const tagList = Object.assign({}, this.tagList)
      this.$refs.addGoods.validate((valid) => {
        if (valid) {
          if (!thumb_url) {
            this.$message.warning('还未添加主图哦！！！')
          } else if (banner_url.length < 1) {
            this.$message.warning('还未添加轮播图哦！！！')
          } else if (!type) {
            this.$message.warning('还未添加商品分类哦！！！')
          } else if (this.tagList.size.length === 0) {
            this.$message.warning('请设置商品尺码!!')
          } else if (!hgPrice) {
            this.$message.warning('请设置商品价格哦！！！')
          } else {
            this.addGoods({
              name,
              desc,
              img_url: thumb_url,
              banner_url,
              content,
              tagList,
              hgPrice,
              unit,
              is_show,
              type: type[0]
            })
          }
        } else {
          this.$message.warning('商品属性还未填写完整哦!!!')
          return false
        }
      })
    },
    // 添加
    async addGoods(data) {
      data.id = this.goods.id
      const res = await updateGoods(data)
      try {
        const { message, code } = res
        this.$message({
          message,
          type: code === 200 ? 'success' : 'error'
        })
        if (code === 200) {
          // this.$router.back()
          // console.log(this.$store.state.tagsView.visitedViews.find(e => e.title === '修改商品'))
          this.$event.$emit('CLOSETAG', this.$store.state.tagsView.visitedViews.find(e => e.title === this.$route.meta.title))
        }
      } catch (e) {
        let message = res.message ? res.message : e.message
        message = e.message ? e.message : '请求失败'
        this.$message.error(message)
      }
    },
    // 数量
    changeGoodsTotal(value) {
      if (value) {
        this.defaultTotal = '0'
      }
    },
    // 默认不限量
    changeGoodsTotalDefault(value) {
      if (value === '1') {
        this.goods.total = ''
      } else {
        this.$refs.goodsTotal.focus()
      }
    },
    numChange(val, index) {
      this.$set(this.tagList.num, index, val)
    }
  }
}
</script>

<style lang="scss" scoped>
  .step-title{
    background: #e5e5e5;
    font-size: 12px;
    padding: 15px;
    margin-bottom: 15px;
  }
  .space-price{
    display: flex;
    align-items: center;
    justify-content: center;

    .price-input{
      width: 120px;
    }
  }
  .space-price-header{
    display: flex;
    align-items: center;
    justify-content: flex-start;

    p{
      margin: 0;
    }
  }

  .banner_list{
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
    padding: 0;

    .banner_item{
      width: 145px;
      height: 145px;
      margin-bottom: 15px;
      margin-right: 15px;
      position: relative;
      list-style: none;
    }

    img{
      display: block;
      width: 145px;
      height: 145px;
    }
    .banner_item:hover .remove{
      display: block;
    }

    .remove{
      display: none;
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      color: #fff;
      background: #000;
      opacity: .6;
      height: 30px;
      text-align: center;
      line-height: 30px;
      z-index: 1000;
      cursor: pointer;
    }
  }

  .thumbUrl{
    display: block;
    width: 145px;
    height: 145px;
    margin-bottom: 15px;
    margin-right: 15px;
  }

  .many_price_set{
    border: 1px solid #e5e5e5;
    padding: 25px;
    width: 402px;
    text-align: right;
    box-sizing: border-box;

    .tip {
      color: #ff0000;
      font-size: 10px;
      margin: 0;
    }
  }
</style>

<style lang="scss">
  .el-form-item__label{
    font-size: 12px !important;
    color: #333 !important;
  }
</style>
