<template>
  <div class="micro-goods-box">
    <!-- 预览区域 -->
    <div class="design-preview-controller">
      <div style="background-color: white; border-radius: 10px; margin: 5px">
        <div style="margin-bottom: 10px">
          <el-image :src="formData.bgImg.indexOf('https') < 0? resourcesUrl + formData.bgImg: formData.bgImg" v-if="formData.bgImg"/>
          <span :style="{position: 'absolute',right: '26px', top: '26px', fontColor: formData.moreTextColor }">{{formData.moreText}} > </span>
          <div :style="{fontSize: (formData.descSize / 2) + 'px', color: formData.descColor, marginLeft: '8px', marginTop: '8px'}">{{formData.desc}}</div>
        </div>
        <el-row>
          <el-col style="width: 205px; height: 308px; margin-left: 8px">
            <el-image style="border-radius: 16px" :src="formData.videoCover.indexOf('https') < 0? resourcesUrl + formData.videoCover: formData.videoCover" v-if="formData.videoCover"/>
          </el-col>
          <el-col style="width: 125px;height: 125px; margin-left: 8px">
            <el-row>
              <el-image style="width: 125px;height: 125px; border-radius: 16px;" :src="formData.vGoods[0].pic.indexOf('https') < 0? resourcesUrl + formData.vGoods[0].pic: formData.vGoods[0].pic" v-if="formData.vGoods.length > 0"/>
              <div v-if="formData.vGoods.length > 0" style="width: 125px; overflow: hidden;text-overflow: ellipsis;white-space: nowrap; margin-bottom: 8px; margin-top: 4px">{{formData.vGoods[0].prodName}}</div>
            </el-row>
            <el-row>
              <el-col style="width: 125px;height: 125px">
                <el-image style="width: 125px;height: 125px; border-radius: 16px;" :src="formData.vGoods[1].pic.indexOf('https') < 0? resourcesUrl + formData.vGoods[1].pic: formData.vGoods[1].pic" v-if="formData.vGoods.length > 1"/>
                <div v-if="formData.vGoods.length > 1" style="width: 125px; overflow: hidden;text-overflow: ellipsis;white-space: nowrap; margin-bottom: 8px; margin-top: 4px">{{formData.vGoods[1].prodName}}</div>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
        <el-row>
          <el-col></el-col>
        </el-row>
        <div class="goods-list">
          <div v-for="(item, index) in goodsList" :key="index">
            <div>
              <div class="goods-item" :class="{ goodsItem1: formData.size === 1 }"
                   :style="formData.back_type==='1' ? 'backgroundImage:url(' + formData.back_imgsrc + ');background-repeat: no-repeat;background-size: 100%;padding-bottom:'+formData.bottom_height+'px' : 'background: '+ formData.back_color +';padding-bottom:'+formData.bottom_height+'px'">
                <!--图片-->
                <div style="margin-left: 8px;margin-right: 8px; margin-top: 8px">
                  <el-image style="width: 100px;height: 100px;border-radius: 16px;" :src="item.pic.indexOf('https') < 0? resourcesUrl + item.pic: item.pic" v-if="item.pic"/>
                </div>
                <!--end 图片-->
                <div class="goods-box-info" :class="{ goodsBoxInfo1: formData.size === 1 }" :style="{display: 'flex', justifyContent: 'center', marginTop: formData.info_top +'px'}">
                  <div :style="'width: '+formData.info_unit+'%;'">
                    <div v-if="formData.showContent.find(x => x === 1)" class="goods-info-title" style="width: 100px; overflow: hidden; text-overflow: ellipsis;">{{ item.prodName }}
                    </div>
                    <div v-if="formData.showContent.find(x => x === 2) && item.brief" class="goods-info-desc">
                      {{ item.brief }}
                    </div>
                  </div>
                </div>
              </div>

            </div>
          </div>
          <div class="empty-tips" v-if="goodsList.length == 0">
            {{ $t('shopFeature.goods.pleaseAddProd') }}
          </div>
        </div>
      </div>
    </div>

    <!-- 右侧编辑区域-->
    <div v-if="isShowEdit" class="design-editor-item design-hide-class">
      <div class="design-config-editor">
        <div class="design-editor-component-title">{{ $t('shopFeature.allCanUse.goodsList') }}</div>
        <!-- 视频介绍 -->
        <!-- 选择商品 -->
        <div class="design-editor-component-container">
          <el-form ref="formData" :model="formData" label-position="left" class="goods-select-form">
            <el-form-item label="选择背景">
              <div @click="changeImgType(1)">
                <img-upload v-model="formData.bgImg" v-if="!formData.bgImg" @input="changeImg"></img-upload>
              </div>
              <el-image :src="formData.bgImg" v-if="formData.bgImg"></el-image>
              <div v-if="formData.bgImg" @click="formData.bgImg = ''" class="default-btn">删除</div>
            </el-form-item>
            <el-form-item label="产品专区介绍">
              <div style="display: block;">
                <el-input type="textarea" style="width: 340px" size="mini" :rows="4" v-model="formData.desc"></el-input>
                <span>字体大小</span>
                <el-input-number placeholder="字体大小" size="small" controls-position="right" v-model="formData.descSize" :min="0" style="width:112px;margin-right: 20px" />
                <span>字体颜色</span>
                <el-color-picker v-model="formData.descColor" size="small"></el-color-picker>
              </div>
            </el-form-item>
            <el-form-item label="查看更多的文本">
              <div style="display: inline-flex;align-items: center">
                <el-input style="width: 210px" type="text" size="mini" v-model="formData.moreText"></el-input>
                <el-input-number placeholder="字体大小" size="mini" controls-position="right" v-model="formData.moreTextSize" :min="0" style="width:112px" />
                <el-color-picker v-model="formData.moreTextColor" size="small"></el-color-picker>
              </div>
              <el-input type="text" v-model="formData.moreLink" placeholder="跳转链接" size="small"></el-input>
              <div style="display: inline-flex">
                <span>上边距：</span><el-input size="mini" type="text" v-model="formData.marginTop" placeholder="上边距" style="width: 100px; margin-right: 36px"></el-input>
                <span>下边距：</span><el-input size="mini" type="text" v-model="formData.marginBottom" placeholder="下边距" style="width: 100px;"></el-input>
              </div>
            </el-form-item>
            <el-form-item label="大视频和封面">
              <el-row>
                <el-col :span="12">
                  <span>大视频</span>
                  <video-upload v-model="formData.video" />
                </el-col>
                <el-col :span="12">
                  <span>视频封面</span>
                  <div @click="changeImgType(2)">
                    <img-upload v-model="formData.videoCover" @input="changeCover"></img-upload>
                  </div>
                </el-col>
              </el-row>
            </el-form-item>
            <!-- 竖版商品选择 -->
            <el-form-item label="竖向商品" class="goods-select-con">
              <div  class="goods-select-list">
                <transition-group>
                  <div v-for="(item, index) in vGoodsList" :key="index" class="goods-select-item">
                    <div class="goods-select-item-img"
                         :style="{ backgroundImage: 'url(' + item.pic + ')' }"></div>
                    <span class="close-item" @click="vGoodsList.splice(index, 1)">x</span>
                    <span @click="showGoodsEdit(item, 1)" style="color: blue; cursor: pointer">修改</span>
                  </div>
                </transition-group>
                <div class="goods-select-item">
                  <div class="goods-select-item-img add-btn" @click="selectProdHandle(1)">
                    <i class="el-icon-plus"></i>
                  </div>
                </div>
              </div>
            </el-form-item>
            <!-- 横版滚动商品选择 -->
            <el-form-item label="横向滚动商品" class="goods-select-con">
              <div  class="goods-select-list">
                <transition-group>
                  <div v-for="(item, index) in goodsList" :key="index" class="goods-select-item">
                    <div  @dragenter="dragenter($event, index)" @dragover="dragover($event, index)" @dragstart="dragstart(index)" draggable >
                      <div class="goods-select-item-img" :class="{ 'goods-empty': !goodsList[0].prodId }"
                           :style="{ backgroundImage: 'url(' + item.pic + ')' }"></div>
                      <span class="close-item" @click="goodsList.splice(index, 1)">x</span>
                      <span @click="showGoodsEdit(item, 2)" style="color: blue; cursor: pointer">修改</span>
                    </div>
                  </div>
                </transition-group>
                <div class="goods-select-item">
                  <div class="goods-select-item-img add-btn" @click="selectProdHandle(2)">
                    <i class="el-icon-plus"></i>
                  </div>
                </div>
              </div>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
    <prods-select v-if="dialogChooseGoods" ref="ProdsSelect" @refreshSelectProds="chooseGoodsFun"></prods-select>
    <!-- 弹窗, 新增图片 -->
    <elx-imgbox ref="elxImgbox" @refreshPic="refreshPic" :maxSize="10" :imgSizeLimit="false" :prod-index="prodIndex"></elx-imgbox>
    <el-dialog :visible.sync="goodsEditVisible" v-if="goodsEditVisible" width="400px">
      <span>商品名称</span>
      <el-input size="small" placeholder="请输入商品名称" v-model="currentEditGoods.prodName"></el-input>
      <img-upload v-model="currentEditGoods.pic" style="width: 100px; height: 100px;"/>
      <el-button size="small" @click="editGoods">确认修改</el-button>
    </el-dialog>
  </div>
</template>
<script>
/**
 * 创建新组件之后，在all-can-use-components中添加
 * 必须应用 microCreateMinis
 * 数据必须以formData包含
 * */
import {microCreateMinis} from '../../minis'
import ProdsSelect from '@/components/prods-select'
import ElxImgbox from '@/components/elx-imgbox'
import VideoUpload from '@/components/video-upload'
import ImgUpload from '@/components/img-upload'

/** 商品组件 */
export default {
  name: 'micro-goods-box',
  mixins: [microCreateMinis],
  props: {},
  data () {
    return {
      selectImgType: 1,
      goodsEditVisible: false,
      currentEditGoods: {},
      goodsType: 1,
      dragIndex: '',
      enterIndex: '',
      resourcesUrl: process.env.VUE_APP_RESOURCES_URL,
      commonCheckFieldRules: 'checkData', // 当前组件默认的规则判断函数
      dialogChooseGoods: false,
      isGetChooseData: false, // 是否该是获取选择的数据
      iconList: [{
        value: 'el-icon-circle-plus-outline',
        label: '1'
      }, {
        value: 'el-icon-goods',
        label: '2'
      }, {
        value: 'el-icon-s-goods',
        label: '3'
      }],
      currentEditIndex: undefined,
      prodIndex: undefined,
      formData: {
        moreTextSize: '',
        moreLink:'',
        marginTop: '0',
        marginBottom: '0',
        descColor: '',
        descSize:'',
        bgImg: '',
        videoCover:'',
        desc: '',
        size: 2, // 一行多少个
        showContent: [1, 2, 3, 4],//1.商品名称2.商品描述3.商品价格4.按钮
        button_type: '2',
        goods: [],
        vGoods:[],
        button_img_width: 54,
        button_img_height: 24,
        button_imgsrc: undefined,//购买按钮背景图
        buy_btn_type: 1, // 购买按钮的样式
        button_text: '去定制',// 购买按钮的文本
        icon_class: 'el-icon-s-goods', //购买按钮的icon
        button_font_size: 10,// 购买按钮的字体大小
        button_font_color: '#FFFFFF',// 购买按钮的字体大小
        button_border_radius: 5, //购买按钮边框弧度
        button_back_color: '#FB4A73', //购买按钮背景颜色
        goodsDetail:[],
        back_type: '2',
        back_color: '#ffffff',
        back_imgsrc: undefined, //商品卡片背景图
        img_unit: 100,
        info_unit: 90,
        info_top: 10,
        bottom_height: 10
      },
      // 商品显示内容
      goodsShowContent: [
        {
          value: 1,
          label: this.$i18n.t('shopFeature.goods.prodName')
        },
        {
          value: 2,
          label: this.$i18n.t('shopFeature.goods.prodDesc')
        },
        {
          value: 3,
          label: this.$i18n.t('shopFeature.goods.prodPrice')
        },
        {
          value: 4,
          label: '按钮'
        }],
      // 一行几个
      lineSize: [
        {
          value: 1,
          label: this.$i18n.t('shopFeature.goods.oneLineItem1')
        },
        {
          value: 2,
          label: this.$i18n.t('shopFeature.goods.oneLineItem2')
        },
        {
          value: 3,
          label: this.$i18n.t('shopFeature.goods.oneLineItem3')
        }
      ],
      // 获取的接口数据
      goodsList: [],
      vGoodsList:[],
      // 默认数据
      demoGoods: [],
    }
  },
  watch: {
    goodsList: {
      deep: true,
      handler (val) {
        if (val.length) {
          if (!this.goodsList.find(x => x.myGoodsType === 1)) {
            this.formData.goods = []
            val.map(res => {
              let good = {prodId: res.prodId, prodName: res.prodName, pic: res.pic, price: res.price}
              this.formData.goods.push(good)
            })
            this.goodsList.concat(val)
          } else {

          }
        } else {
          this.goodsList = this.demoGoods
        }
      }
    },
    vGoodsList: {
      deep: true,
      handler (val) {
        if (val.length) {
          if (!this.vGoodsList.find(x => x.myGoodsType === 1)) {
            this.formData.vGoods = []
            val.map(res => {
              let good = {prodId: res.prodId, prodName: res.prodName, pic: res.pic, price: res.price}
              this.formData.vGoods.push(good)
            })
            this.vGoodsList.concat(val)
          } else {

          }
        }
      }
    }
  },

  filters: {
    buy_btn_type (val) { // 标题
      let str = ''
      switch (val) {
        case 6:
          str = 'danger'
          break
        case 8:
          str = 'danger'
          break
      }
      return str
    }
  },
  components: {
    ProdsSelect,
    ElxImgbox,
    VideoUpload,
    ImgUpload

  },
  computed: {
    theme () {
      return this.$store.getters.theme
    }
  },
  mounted () {
    for (let i = 0; i < 4; i++) {
      this.demoGoods.push(
        {
          myGoodsType: 1,
          brief: this.$i18n.t('shopFeature.goods.prodDesc'),
          pic: require('@/assets/img/micro-page/def.png'),
          prodName: this.$i18n.t('shopFeature.goods.prodName'),
          price: '90'
        }
      )
    }
    if (!this.goodsList.length) {
      this.goodsList = this.demoGoods
    }
    if (Object.keys(this.dataField).length !== 0) {
      // this.getGoodsInfo(this.dataField.goods, '');
      this.goodsList = this.dataField.goods;
      this.vGoodsList = this.dataField.vGoods;
    }
  },
  methods: {
    showGoodsEdit(item, goodsType){
      this.goodsType = goodsType
      this.goodsEditVisible = true;
      this.currentEditGoods = item;
      if(item.pic.indexOf('https') >= 0){
        this.currentEditGoods.pic = item.pic.replace(this.resourcesUrl, '')
      }
    },
    editGoods(newGoods){
      if(this.goodsType === 1){
        for(let vGood in this.vGoodsList){
          let item = this.vGoodsList[vGood]
          if(item.prodId === this.currentEditGoods.prodId){
            item.pic = this.resourcesUrl + this.currentEditGoods.pic
            item.prodName = this.currentEditGoods.prodName
            this.goodsEditVisible = false
            this.$forceUpdate()
            return;
          }
        }
      }else{
        for(let good in this.goodsList){
          let item = this.dataField.goodsList[good]
          if(item.prodId === this.currentEditGoods.prodId){
            item.pic = this.resourcesUrl + this.currentEditGoods.pic
            item.prodName = this.currentEditGoods.prodName
            this.goodsEditVisible = false
            this.$forceUpdate()
            return;
          }
        }
      }

    },
    changeImgType(selectImgType){
      this.selectImgType = selectImgType;
    },
    changeCover(imagePath){
      if(this.selectImgType === 1){
        this.formData.bgImg = imagePath;
      }else{
        this.formData.videoCover = imagePath
      }
    },
    dragstart(index) {
      this.dragIndex = index;
    },
    dragenter(e, index) {
      e.preventDefault();
      // 避免源对象触发自身的dragenter事件
      if (this.dragIndex !== index) {
        const moving = this.goodsList[this.dragIndex];
        this.goodsList.splice(this.dragIndex, 1);
        this.goodsList.splice(index, 0, moving);
        // 排序变化后目标对象的索引变成源对象的索引
        this.dragIndex = index;
      }
    },
    dragover(e, index) {
      e.preventDefault();
    },
    /**
     * 选择图片回调
     * @param {String} imagePath 无前缀的图片地址字符串(多图时用,分割)
     */
    refreshPic(imagePath) {
      if(this.currentEditIndex===1){
        this.formData.button_imgsrc = this.resourcesUrl + imagePath
      }else{
        this.formData.back_imgsrc = this.resourcesUrl + imagePath
      }
      // console.log(this.formData.button_imgsrc)

    },
    /** 更换图片 */
    changeImg(imagePath) {
      // console.log(index)
      // this.isChangeImg = true
      // this.currentEditIndex = index
      // this.elxImgboxHandle(1)
      // // this.canChooseImagesNum = 1
      this.formData.bgImg = this.resourcesUrl + imagePath
    },
    elxImgboxHandle(type) {
      if (this.disabled) {
        return false
      }
      this.elxImgboxVisible = true
      this.$nextTick(() => {
        this.$refs.elxImgbox.init(type || 2, 1)
      })
    },
    // 选择商品操作
    selectProdHandle(goodsType) {
      this.dialogChooseGoods = true
      this.goodsType = goodsType;
      this.$nextTick(() => {
        this.$refs.ProdsSelect.init()
      })
    },
    // 选择商品回调
    chooseGoodsFun($event) {
      if ($event) {
        if(this.goodsType === 1){
          if (this.vGoodsList.find(x => x.myGoodsType === 1)) {
            this.vGoodsList = []
          }
          $event.map(newGoodItem => {
            if (this.formData.vGoods.indexOf(newGoodItem.prodId) === -1) {
              this.vGoodsList.push(newGoodItem)
            }
          })
        }else{
          if (this.goodsList.find(x => x.myGoodsType === 1)) {
            this.goodsList = []
          }
          $event.map(newGoodItem => {
            if (this.formData.goods.indexOf(newGoodItem.prodId) === -1) {
              this.goodsList.push(newGoodItem)
            }
          })
        }
      }
      this.dialogChooseGoods = false
    },
    /** 批量获取商品详情 */
    getGoodsInfo(prodIds, prodType) {
      this.$http({
        url: this.$http.adornUrl('/prod/prod/listProdByIdsAndType'),
        method: 'get',
        params: this.$http.adornParams({
          prodIds,
          prodType
        })
      }).then(({data}) => {
        this.goodsList = this.sortList(data)
        this.goodsList.forEach(item => {
          if (!item.pic.includes('http')) {
            item.pic = process.env.VUE_APP_RESOURCES_URL + item.pic
          }
        })
       if(!!this.formData.goodsDetail){
         this.formData.goodsDetail.forEach(gd =>{
             gd.button_type = !!gd.button_type? gd.button_type: this.formData.button_type,
             gd.button_img_width = !!gd.button_img_width? gd.button_img_width: this.formData.button_img_width,
             gd.button_img_height = !!gd.button_img_height? gd.button_img_height: this.formData.button_img_height,
             gd.button_text = !!gd.button_text? gd.button_text: this.formData.button_text,
             gd.button_font_color = !!gd.button_font_color? gd.button_font_color: this.formData.button_font_color,
             gd.button_font_size = !!gd.button_font_size? gd.button_font_size: this.formData.button_font_size,
             gd.button_border_radius = !!gd.button_border_radius? gd.button_border_radius: this.formData.button_border_radius,
             gd.button_back_color = !!gd.button_back_color? gd.button_back_color: this.formData.button_back_color,
             gd.route_path = !!gd.route_path? gd.route_path : this.formData.route_path
         })
       }
        if(this.formData.goodsDetail.length === 0){
          this.goodsList.forEach(item =>{
            this.formData.goodsDetail.push(
              { prodId: item.prodId,
                button_type:this.formData.button_type,
                button_img_width:this.formData.button_img_width,
                button_img_height:this.formData.button_img_height,
                button_text:this.formData.button_text,
                button_font_color:this.formData.button_font_color,
                button_font_size:this.formData.button_font_size,
                button_border_radius:this.formData.button_border_radius,
                button_back_color:this.formData.button_back_color,
                route_path:this.formData.route_path,
              })
          })
        }
      })
    },
    /**
     * 按照添加的顺序排序
     */
    sortList(goodsList) {
      let showArr = this.dataField.goods
      goodsList.forEach(item => {
        item.sortId = showArr.indexOf(item.prodId)
      })
      return goodsList.sort((a, b) => {
        return a.sortId - b.sortId
      })
    },
    /* 校验 */
    checkData() {
      if (this.formData.goods.length > 0) {
        this.myCheckResult(true)
      } else {
        this.$newMessage.error(this.$i18n.t('shopFeature.goods.pleaseAddProd'))
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
