<template>
  <div class="micro-image-ad-box">
    <!--预览区-->
    <div class="design-preview-controller">
      <div v-if="formData.imageList.length"
           class="ad-view-box"
           :class="'ad-view-'+formData.indicator">
        <div v-if="formData.indicator ===1 || formData.indicator ===4 ">
          <img v-for="(item, index) in formData.imageList"
               :key="index"
               style="display: block"
               :src="item.url"
               alt="">
        </div>
      </div>
      <div v-else
           class="image-ad-view">
        <div class="image-ad-title">
          <img src="~@/assets/img/micro-page/p-ad-def.png" >
          {{$t('shopFeature.imageAd.widthSuggest')}}
        </div>
      </div>
    </div>
    <!--编辑区-->
    <div v-show="isShowEdit"
         class="design-editor-item design-hide-class">
      <div class="design-config-editor">
        <div class="design-editor-component-title">{{$t('shopFeature.imageAd.hotArea')}}</div>
        <div class="image-ad-edit">
          <div class="ad-edit-item-title">{{$t('shopFeature.imageAd.addPic')}}
            <span class="tips">{{$t('shopFeature.imageAd.max10Ads')}}</span>
          </div>
          <!--hot model-->
          <draggable :list="formData.imageList"
                      ghost-class="ghost"
                      handle=".ad-handle">
            <div v-for="(item,index) in formData.imageList"
                  :key="index"
                  class="ad-image-hot">
              <div class="add-ad-image"
                    @click="showHotAreaPop(index)">{{$t('shopFeature.imageAd.addHotArea')}}</div>
              <div class="add-ad-image"
                    @click="changeImg(index)">{{$t('shopFeature.tabNav.changePic')}} </div>
              <div class="ad-image-hot-box">
                <div v-show="item.activeBoxs.length"
                      class="ad-image-hot-content ad-handle">
                  <span v-for="(hotItem,hotIndex) in item.activeBoxs"
                        :key="hotIndex"
                        class="ad-hot-box-item"
                        :style="`transform: translate(${hotItem.translateX * hotScale}px,${hotItem.translateY * hotScale}px);width:${hotItem.width * hotScale}px;height:${hotItem.height * hotScale}px;`">
                    <el-dropdown trigger="click"
                                  size="small"
                                  @command="command">
                      <div class="cursor">
                        <p v-if="hotItem.type!=1 && hotItem.type!=4 ">{{ hotItem.title|| $t('shopFeature.imageAd.setRoute') }}</p>
                        <p class="hot-item-title" v-if="hotItem.type===1 || hotItem.type===4 ">{{ hotItem.type | typeNameFilter(that) }}</p>
                        <p class="hot-item-title" v-if="hotItem.type===1 || hotItem.type===4 " @click.stop="handleChangeLinkOrProd(index, hotIndex, hotItem.type)">{{ hotItem.title }}</p>
                      </div>
                      <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item v-for="(linkItem,linkIndex) in linkList"
                                          :key="linkIndex"
                                          :command="({linkItem,currentHotEditIndex:hotIndex,currentEditIndex:index})">
                          <span style="font-size: 12px;">{{ linkItem.title }}</span>
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </el-dropdown>
                    <i class="el-icon-close close-icon"
                        @click="item.activeBoxs.splice(hotIndex, 1)" />
                  </span>
                </div>
                <img class="ad-handle"
                      :src="item.url">
                <i class="el-icon-error close-icon"
                    @click="formData.imageList.splice(index, 1)" />
              </div>
            </div>
          </draggable>
          <!--选择图片框-->
          <div v-if="10 - formData.imageList.length !== 0"
               class="p-add-btn"
               @click="elxImgboxHandle">
            <i class="el-icon-plus" /> {{$t('shopFeature.imageAd.addBgImg')}}
          </div>
        </div>
      </div>
    </div>

    <el-dialog custom-class="up-dialog"
               :close-on-click-modal="false"
               top="5vh"
               :title="$i18n.t('shopFeature.imageAd.addHotArea')"
               :visible.sync="dialogHot"
               width="550px">
      <div class="ad-hot-box">
        <div v-if="dialogHot&&formData.imageList.length">
          <img :src="formData.imageList[currentEditIndex].url"
               class="box-img">
          <div v-for="(item,index) in cacheImageActiveBox"
               :key="index"
               v-drag="{cacheImageActiveBox,index}"
               class="ad-drag">
            <el-dropdown trigger="click"
                         size="small"
                         @command="command">
              <div class="cursor">
                <p v-if="item.type!=1 && item.type!=4 ">{{ item.title|| $t('shopFeature.imageAd.setRoute') }}</p>
                <p v-if="item.type===1 || item.type===4 ">{{ item.type | typeNameFilter(that) }}</p>
                <p class="hot-item-title" v-if="item.type===1 || item.type===4 " @click.stop="handleChangeLinkOrProd(currentEditIndex, index, item.type)">{{ item.title }}</p>
              </div>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-for="(linkItem,linkIndex) in linkList"
                                  :key="linkIndex"
                                  :command="({linkItem,currentHotEditIndex:index,isCacheImage:true})">
                  <span style="font-size: 12px;">{{ linkItem.title }}</span>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <i class="el-icon-close close-icon"
               @click="cacheImageActiveBox.splice(index, 1)" />
          </div>
        </div>
      </div>
      <div slot="footer"
           style="text-align: right;margin-top: 20px;">
        <el-button size="mini"
                   type="primary"
                   @click="addHotArea">{{$t('shopFeature.imageAd.addHotArea')}}</el-button>
        <el-button size="mini"
                   @click="saveHotBox">{{$t('shopFeature.imageAd.save')}}</el-button>
      </div>
    </el-dialog>
    <!-- 弹窗, 新增图片 -->
    <elx-imgbox ref="elxImgbox"
                @refreshPic="refreshPic"
                :maxSize="10"
                :imgSizeLimit="false"></elx-imgbox>
    <!-- 商品选择弹窗  -->
    <prods-select v-if="dialogChooseGoods"
                  ref="ProdsSelect"
                  :isSingle="true"
                  @refreshSelectProds="chooseGoodsFun"></prods-select>
    <!--选择微页面-->
    <el-dialog custom-class="up-dialog"
               :close-on-click-modal="false"
               top="5vh"
               :title="$i18n.t('shopFeature.tabNav.microPage')"
               :visible.sync="dialogChoosePages"
               width="42%">
      <div class="choose-goods-compent">
        <choose-feature :isGetChooseData="isGetChooseFeature"
                        @chooseChooseFeaturesFun="chooseChooseFeaturesFun"></choose-feature>
        <div slot="footer"
             style="text-align: right;margin-top: 20px;">
          <el-button size="mini"
                     type="primary"
                     @click="isGetChooseFeature=!isGetChooseFeature">{{$t('shopFeature.tabNav.confirm')}}</el-button>
          <el-button size="mini"
                     @click="dialogChoosePages = false">{{$t('shopFeature.tabNav.cancel')}}</el-button>
        </div>
      </div>
    </el-dialog>
    <!-- 弹窗: 输入自定义路径 -->
    <el-dialog custom-class="up-dialog" :title="$i18n.t('shopFeature.tabNav.customPath')" width="40%" top="30vh" :visible.sync="showPathInputDialog">
      <div class="custom-path-con">
        <span>{{$t('shopFeature.tabNav.routeLink')}}</span>
        <el-input style="margin-rigth: 10px;" :placeholder="$i18n.t('shopFeature.tabNav.pleaseFillThePath')" size="small" v-model="customPath">

        </el-input>
      </div>
      <div slot="footer" style="text-align: right;">
          <el-button size="mini"
                     type="primary"
                     @click="customPathComfirm">{{$t('shopFeature.tabNav.confirm')}}</el-button>
          <el-button size="mini"
                     @click="customPathCancel">{{$t('shopFeature.tabNav.cancel')}}</el-button>
        </div>
    </el-dialog>
  </div>
</template>
<script>
/**
 * 创建新组件之后，在all-can-use-components中添加
 * 必须应用 microCreateMinis
 * 数据必须以formData包含
 * */
import '../../directive/index'
import {microCreateMinis} from '../../minis'
import {SlickList, SlickItem, HandleDirective} from 'vue-slicksort'
import draggable from 'vuedraggable'
import ProdsSelect from '@/components/prods-select'
import ElxImgbox from '@/components/elx-imgbox'
import ChooseFeature from '@/components/choose-feature'

/** 图片广告 */
export default {
  name: 'micro-image-ad-box',
  mixins: [microCreateMinis],
  directives: {handle: HandleDirective},
  data () {
    return {
      commonCheckFieldRules: 'checkData', // 当前组件默认的规则判断函数
      hotScale: 392 / 500,
      typeList: [
        {
          title: this.$i18n.t('shopFeature.imageAd.hotArea')
        }
      ],
      dialogHot: false, // 是否显示热区
      dialogChooseGoods: false, // 选择商品
      cacheImage: false, // 是否是正在编辑热区的
      /** 选择图片的弹窗 */
      elxImgboxVisible: false, // 显示选择图片
      isGetChooseImages: false, // 返回图片
      canChooseImagesNum: 1, // 可以添加的图片数量
      isChangeImg: false, // 是否为更换图片模式
      currentEditIndex: 0, // 当前编辑的图片
      currentHotEditIndex: 0, // 当前编辑的热区
      formData: {
        indicator: 4, // 选择模板: 1一行一个; 2轮播海报; 3横向滑动; 4热区
        imageList: [] // 图片列表
      },
      cacheImageActiveBox: [], // 缓存当前box list
      boxItem: {// 盒子模板
        link: '',
        type: '',
        title: '',
        left: 0,
        top: 0,
        translateX: 0,
        translateY: 0,
        width: 102,
        height: 102
      },
      linkList: [
        {
          type: 1,
          title: this.$i18n.t('shopFeature.imageAd.prodDetPage'),
          link: ''
        },
        {
          type: 2,
          title: this.$i18n.t('shopFeature.tabNav.cart'),
          link: ''
        },
        {
          type: 3,
          title: this.$i18n.t('shopFeature.tabNav.personalCenter'),
          link: ''
        },
        {
          type: 4,
          title: this.$i18n.t('shopFeature.tabNav.customPath'),
          link: ''
        }
        // {
        //   type: 5,
        //   title: this.$i18n.t('shopFeature.headerAd.microPage'),
        //   link: ''
        // }
      ],
      resourcesUrl: process.env.VUE_APP_RESOURCES_URL,
      dataForm: {
        featureGoodLists: []
      },
      that: this,
      // 微页面选择
      dialogChoosePages: false,
      isGetChooseFeature: false, // 是否可以返回微页面
      customPath: '', // 自定义路径
      showPathInputDialog: false // 自定义路径输入弹窗
    }
  },
  watch: {},
  components: {
    draggable,
    SlickList,
    SlickItem,
    ProdsSelect,
    ElxImgbox,
    ChooseFeature
  },
  filters: {
    typeNameFilter (val, that) {
      let str = ''
      switch (val) {
        case 1:
          str = that.$i18n.t('shopFeature.imageAd.prodDetPage')
          break
        case 2:
          str = that.$i18n.t('shopFeature.tabNav.cart')
          break
        case 3:
          str = that.$i18n.t('shopFeature.tabNav.personalCenter')
          break
        case 4:
          str = that.$i18n.t('shopFeature.tabNav.customPath')
          break
        case 5:
          str = that.$i18n.t('shopFeature.tabNav.microPage')
          break
      }
      return str
    }
  },
  computed: {},
  mounted () {
  },
  methods: {
    /**
     * 更改自定义路径/商品
     */
    handleChangeLinkOrProd (index, boxIndex, type) {
      this.currentEditIndex = index
      this.currentHotEditIndex = boxIndex
      if (type === 1) {
        this.dialogChooseGoods = true
        this.$nextTick(() => {
          this.$refs.ProdsSelect.init()
        })
        return
      }
      if (type === 4) {
        this.customPath = this.dialogHot ? this.cacheImageActiveBox[boxIndex].link : this.formData.imageList[this.currentEditIndex].activeBoxs[boxIndex].link
        this.showPathInputDialog = true
      }
    },

    /**
     * 选择图片
     * @param {String} type
     * type 1 单选; 2 多选
     */
    elxImgboxHandle (type) {
      if (this.disabled) {
        return false
      }
      this.elxImgboxVisible = true
      this.$nextTick(() => {
        this.$refs.elxImgbox.init(type || 2, 10 - this.formData.imageList.length)
      })
    },
    /**
     * 选择图片回调
     * @param {String} imagePath 无前缀的图片地址字符串(多图时用,分割)
     */
    refreshPic (imagePath) {
      let imgsList = imagePath.split(',')
      for (let i = 0; i < imgsList.length; i++) {
        imgsList[i] = this.resourcesUrl + imgsList[i]
      }
      if (imgsList.length) {
        if (this.isChangeImg) { // 更换图片模式
          this.formData.imageList[this.currentEditIndex].url = imgsList[0]
          this.formData.imageList[this.currentEditIndex].title = ''
          return
        }
        imgsList.map(res => {
          this.formData.imageList.push({
            url: res,
            title: '',
            link: '',
            type: '',
            imgTit: '',
            activeBoxs: []
          })
        })
      }
    },
    /** 显示添加热区 */
    showHotAreaPop (index) {
      this.dialogHot = true
      this.currentEditIndex = index
      this.cacheImageActiveBox = JSON.parse(JSON.stringify(this.formData.imageList[this.currentEditIndex].activeBoxs))
    },
    /** 点击添加热区 */
    addHotArea () {
      this.cacheImageActiveBox.push(JSON.parse(JSON.stringify(this.boxItem)))
    },
    /** 保存热区 */
    saveHotBox () {
      const hotAreaBoxs = this.cacheImageActiveBox
      let flag = true
      for (let i = 0; i < hotAreaBoxs.length; i++) {
        const el = hotAreaBoxs[i]
        if (!el.type) {
          flag = false
          this.$newMessage.error(this.$i18n.t('shopFeature.imageAd.setHotAreaRoute'))
          break
        }
      }
      if (flag) {
        this.formData.imageList[this.currentEditIndex].activeBoxs = hotAreaBoxs
        this.dialogHot = false
      }
    },
    /** 更换图片 */
    changeImg (index) {
      this.isChangeImg = true
      this.currentEditIndex = index
      this.elxImgboxHandle(1)
    },
    /** choose图片的回调 */
    chooseImagesEnd ($item) {
      this.elxImgboxVisible = false
      const $imgData = $item.data
      if ($imgData.length) {
        if (this.isChangeImg) { // 更换图片模式
          this.formData.imageList[this.currentEditIndex].url = $imgData[0].img
          this.formData.imageList[this.currentEditIndex].title = $imgData[0].productName
          return
        }
        $imgData.map(res => {
          this.formData.imageList.push({
            url: res.img,
            title: '',
            link: '',
            type: '',
            activeBoxs: []
          })
        })
      }
    },
    // 选择商品回调
    chooseGoodsFun ($event) {
      if ($event) {
        this.setLinkInfo({
          title: $event.prodName,
          link: $event.prodId,
          type: 1
        })
      }
      this.dialogChooseGoods = false
    },
    /** 设置跳转信息 */
    setLinkInfo (obj) {
      if (this.isCacheImage) { // 热区弹窗编辑模式
        this.cacheImageActiveBox[this.currentHotEditIndex].title = obj.title
        this.cacheImageActiveBox[this.currentHotEditIndex].link = obj.link
        this.cacheImageActiveBox[this.currentHotEditIndex].type = obj.type
        this.$forceUpdate()
        return
      }
      if (this.formData.indicator === 4) { // 热区非弹窗编辑模式
        this.formData.imageList[this.currentEditIndex].activeBoxs[this.currentHotEditIndex].title = obj.title
        this.formData.imageList[this.currentEditIndex].activeBoxs[this.currentHotEditIndex].link = obj.link
        this.formData.imageList[this.currentEditIndex].activeBoxs[this.currentHotEditIndex].type = obj.type
      }
      this.$forceUpdate()
    },
    /** 选择跳转路径 */
    command (eve) {
      this.isCacheImage = eve.isCacheImage || false
      let commandInfo = eve.linkItem

      if (eve.hasOwnProperty('currentHotEditIndex')) {
        this.currentHotEditIndex = eve.currentHotEditIndex
      }
      if (eve.hasOwnProperty('currentEditIndex')) {
        this.currentEditIndex = eve.currentEditIndex
      }
      // 商品详情: 打开弹窗选择商品
      if (eve.linkItem.type === 1) {
        this.dialogChooseGoods = true
        this.$nextTick(() => {
          this.$refs.ProdsSelect.init()
        })
        return
      }
      // 自定义路径: 弹出路径输入框
      if (eve.linkItem.type === 4) {
        this.showPathInputDialog = true
        this.customPath = ''
        return
      }
      // 微页面: 弹窗选择一个页面
      if (eve.linkItem.type === 5) {
        this.choosePage()
      }
      this.setLinkInfo({
        title: commandInfo.title,
        link: commandInfo.link,
        type: eve.linkItem.type
      })
    },

    /**
     * 自定义路径弹窗确认
     */
    customPathComfirm () {
      if (!this.customPath.trim()) {
        this.$newMessage.error(this.$i18n.t('shopFeature.tabNav.pleaseFillThePath'))
        return
      }
      this.setLinkInfo({
        title: this.customPath,
        link: this.customPath,
        type: 4
      })
      this.showPathInputDialog = false
      this.customPath = ''
    },
    /**
     * 自定义路径弹窗取消
     */
    customPathCancel () {
      this.showPathInputDialog = false
    },
     /**
     * @param {当前操作项索引}} index
     */
    choosePage () {
      this.dialogChoosePages = true
    },
     // 选择微页面回调
    chooseChooseFeaturesFun ($event) {
      this.dialogChoosePages = false
    },
    /**
     * 修改商品
     */
    changeProd (index) {
      this.currentHotEditIndex = index
      this.dialogChooseGoods = true
      this.$nextTick(() => {
        this.$refs.ProdsSelect.init()
      })
    },
    /* 校验 */
    checkData () {
      if (this.formData.imageList.length > 0) {
        this.myCheckResult(true)
      } else {
        // 弹窗提示错误消息
        this.showCheckForm()
        this.$newMessage.error(this.$i18n.t('shopFeature.tabNav.pleaseAddPic'))
      }
    }
  }
}
</script>

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