<template>
  <div>
    <el-card v-show="step==1" shadow="never" class="aui-card--fill">
      <el-table
        v-loading="dataListLoading"
        :data="dataList"
        border
        @selection-change="dataListSelectionChangeHandle"
        @sort-change="dataListSortChangeHandle"
        style="width: 100%;">
        <el-table-column prop="customerName" label="客户名称" header-align="left" align="left"></el-table-column>
        <el-table-column label="小程序首页配置" fixed="right" header-align="center" align="center" width="150">
          <template slot-scope="scope">
            <el-button type="text" size="small"
              @click="startSetWxIndex(scope.row.customerId, scope.row.customerName, 0)">政府端</el-button>
            <el-button type="text" size="small"
              @click="startSetWxIndex(scope.row.customerId, scope.row.customerName, 1)">居民端</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <div class="m-wx_index" v-show="step==2">
      <el-button type="default"
        @click="toStep(1)">取消返回</el-button>
      <el-button type="info"
        @click="isInPreview = true">预览</el-button>
      <el-button type="success"
        @click="save">保存</el-button>
      <el-button type="danger"
        @click="publish">发布</el-button>

      <el-row class="wrap" :gutter="20">
        <el-col :span="5">
          <h4>选择组件</h4>
          <div class="mw-cpt_type">
            <div class="d-function"  v-show="item.componentList.length > 0" :key="item.functionId" v-for="item in cptTypeList">
              <div class="d-info" @click="shiftCptTypeItemUnfold(item)">
                <img v-if="item.functionId==0" class="d-ico" src="@/assets/img/modules/wx-mini/index-set/common-cpt.png">
                <img v-if="item.functionId==1" class="d-ico" src="@/assets/img/modules/wx-mini/index-set/function-cpt1.png">
                <img v-if="item.functionId==2" class="d-ico" src="@/assets/img/modules/wx-mini/index-set/function-cpt2.png">
                <img v-if="item.functionId==3" class="d-ico" src="@/assets/img/modules/wx-mini/index-set/function-cpt3.png">
                <img v-if="item.functionId==4" class="d-ico" src="@/assets/img/modules/wx-mini/index-set/function-cpt4.png">

                <span class="d-name">{{ item.functionName }}</span>

                <img class="d-arrow" :class="{'z-unfold': item.isUnfold}" src="@/assets/img/modules/wx-mini/index-set/arrow-down.png">
              </div>
              <div class="d-list" v-show="item.isUnfold">
                <div class="d-item" :key="cptItem.componentId" v-for="cptItem in item.componentList">
                  <span class="d-item-region">({{ getCptRegionName(checkCptRegion(cptItem)) }})</span>
                  <span class="d-item-name">{{ cptItem.componentName }}</span>
                  <span class="d-item-btn z-disabled" v-if="checkCptRegion(cptItem)!=='cnt' && checkExistCpt(cptItem)">已添加</span>
                  <span class="d-item-btn" v-else @click="beforeAddCpt(cptItem)">
                    <img src="@/assets/img/modules/wx-mini/index-set/add.png">
                    <span>添加</span>
                  </span>
                </div>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="13">
          <div class="mw-show" :class="{'z-preview': isInPreview}">
            <div v-show="isInPreview" class="mw-show-close">
              <el-button type="default"
                @click="isInPreview = false" icon="el-icon-close" circle></el-button>
            </div>
            <div class="mw-phone">
              <div class="mw-phone-top" v-show="!isInPreview || topCptList.length>0" :class="{'z-none': !isInPreview}">
                <div class="mw-phone-hint" v-show="!isInPreview" :class="{'z-out-left': topCptList.length>0}">（{{ getCptRegionName('top') }}）</div>
                <div class="mw-cpt"
                  :class="{'z-focused': focusedCpt.tempOnlyId===item.tempOnlyId}"
                  @click="focusCpt(item)" :key="item.componentId"
                  v-for="item in topCptList">
                  <div class="mw-cpt-top_title" v-if="item.componentFrontId==='gridNameTitle'">
                    <div class="d-cpt-wrap">
                      <img src="@/assets/img/modules/wx-mini/index-set/page/dang.png">
                      <span>{{ item.demoData.content }}</span>
                    </div>

                    <div class="d-cpt-operate z-small"
                      v-show="focusedCpt.tempOnlyId===item.tempOnlyId"
                      @click.stop>
                      <div class="d-cpt-btn" @click="delCpt(item)">
                        <img src="@/assets/img/modules/wx-mini/index-set/del.png">
                        <p>删除</p>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div class="mw-phone-ban" v-show="!isInPreview || banCptList.length>0" :class="{'z-none': !isInPreview}">
                <div class="mw-phone-hint" v-show="!isInPreview" :class="{'z-out-left': banCptList.length>0}">（{{ getCptRegionName('ban') }}）</div>
                <div class="mw-cpt"
                  :class="{'z-focused': focusedCpt.tempOnlyId===item.tempOnlyId}"
                  @click="focusCpt(item)" :key="item.componentId"
                  v-for="item in banCptList">
                  <div class="mw-cpt-swiper" v-if="item.componentFrontId==='hotNewsSwiper'">
                    <div class="d-cpt-wrap">
                      <div class="d-cpt-subwrap">
                        <img src="@/assets/img/modules/wx-mini/index-set/page/swiper-bg.png">
                        <div>
                          <span>{{ item.demoData.content }}</span>
                          <i></i>
                          <i></i>
                          <i></i>
                          <i class="z-on"></i>
                        </div>
                      </div>
                    </div>

                    <div class="d-cpt-operate z-small"
                      v-show="focusedCpt.tempOnlyId===item.tempOnlyId"
                      @click.stop>
                      <div class="d-cpt-btn" @click="delCpt(item)">
                        <img src="@/assets/img/modules/wx-mini/index-set/del.png">
                        <p>删除</p>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div class="mw-phone-fixed" v-show="!isInPreview || fixedCptList.length>0" :class="{'z-none': !isInPreview}">
                <div class="mw-phone-hint" v-show="!isInPreview" :class="{'z-out-down': fixedCptList.length>0}">（{{ getCptRegionName('fixed') }}）</div>
                <div class="mw-cpt"
                  :class="{'z-focused': focusedCpt.tempOnlyId===item.tempOnlyId}"
                  @click="focusCpt(item)" :key="item.componentId"
                  v-for="item in fixedCptList">
                  <div class="mw-cpt-new_msg" v-if="item.componentFrontId==='newMessageButton'">
                    <div class="d-cpt-wrap">
                      <img src="@/assets/img/modules/wx-mini/index-set/page/msg.png">
                      <span>有新消息！</span>
                    </div>

                    <div class="d-cpt-operate z-small"
                      v-show="focusedCpt.tempOnlyId===item.tempOnlyId"
                      @click.stop>
                      <div class="d-cpt-btn" @click="delCpt(item)">
                        <img src="@/assets/img/modules/wx-mini/index-set/del.png">
                        <p>删除</p>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div class="mw-phone-cnt" v-show="!isInPreview || cntCptList.length>0" :class="{'z-none': !isInPreview}">
                <div class="mw-phone-hint" v-show="!isInPreview" :class="{'z-out-left': cntCptList.length>0}">（{{ getCptRegionName('cnt') }}）</div>
                <div class="mw-cpt"
                  :class="{'z-focused': focusedCpt.tempOnlyId===item.tempOnlyId}"
                  @click="focusCpt(item)"
                  :key="index"
                  v-for="(item, index) in cntCptList">
                  <div class="mw-cpt-cnt_news"
                    v-if="item.componentFrontId==='hotSubjectList'">
                    <div class="d-cpt-wrap">
                      <div class="list">
                        <div class="item">
                          <img src="@/assets/img/modules/wx-mini/index-set/page/news-pic.png">
                          <div class="d-news-title" :style="{backgroundColor: item.configuration.bgc}">{{ item.demoData.title }}</div>
                          <div class="d-news-info">
                            <span>来源：大港路党支部</span>
                            <span class="f-fr">2020-01-02</span>
                          </div>
                        </div>
                        <div class="item">
                          <img src="@/assets/img/modules/wx-mini/index-set/page/news-pic.png">
                          <div class="d-news-title" :style="{backgroundColor: item.configuration.bgc}">{{ item.demoData.title }}</div>
                          <div class="d-news-info">
                            <span>来源：大港路党支部</span>
                            <span class="f-fr">2020-01-02</span>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div class="mw-cpt-cnt_menus"
                    v-if="item.componentFrontId==='moreFunctionIcons'">
                    <div class="d-cpt-wrap">
                      <div class="list">
                        <div class="item">
                          <img src="@/assets/img/modules/wx-mini/index-set/page/menu-1.png">
                          <p>议事厅</p>
                        </div>
                        <div class="item">
                          <img src="@/assets/img/modules/wx-mini/index-set/page/menu-2.png">
                          <p>社群</p>
                        </div>
                        <div class="item">
                          <img src="@/assets/img/modules/wx-mini/index-set/page/menu-3.png">
                          <p>党建声音</p>
                        </div>
                        <div class="item">
                          <img src="@/assets/img/modules/wx-mini/index-set/page/menu-4.png">
                          <p>更多功能</p>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div class="mw-cpt-cnt_groups"
                    v-if="item.componentFrontId==='recommendGroupSlider'">
                    <div class="d-cpt-wrap">
                      <div class="list">
                        <div class="item">
                          <div class="d-group-no">
                            <img src="@/assets/img/modules/wx-mini/index-set/page/qi.png">
                            <span>1</span>
                          </div>
                          <div class="d-group-avatar">
                            <img src="@/assets/img/modules/wx-mini/index-set/page/avatar.jpg">
                          </div>
                          <div class="d-group-name">{{ item.demoData.title }}</div>
                          <div class="d-group-info">
                            <span>山东路45号-张三</span>
                          </div>
                          <div class="d-group-info">
                            <span>共240人</span>
                            <span>党员11人</span>
                          </div>
                          <div class="d-group-btn">加入</div>
                        </div>
                        <div class="item">
                          <div class="d-group-no">
                            <img src="@/assets/img/modules/wx-mini/index-set/page/qi.png">
                            <span>1</span>
                          </div>
                          <div class="d-group-avatar">
                            <img src="@/assets/img/modules/wx-mini/index-set/page/avatar.jpg">
                          </div>
                          <div class="d-group-name">{{ item.demoData.title }}</div>
                          <div class="d-group-info">
                            <span>山东路45号-张三</span>
                          </div>
                          <div class="d-group-info">
                            <span>共240人</span>
                            <span>党员11人</span>
                          </div>
                          <div class="d-group-btn">加入</div>
                        </div>
                        <div class="item">
                          <div class="d-group-no">
                            <img src="@/assets/img/modules/wx-mini/index-set/page/qi.png">
                            <span>1</span>
                          </div>
                          <div class="d-group-avatar">
                            <img src="@/assets/img/modules/wx-mini/index-set/page/avatar.jpg">
                          </div>
                          <div class="d-group-name">{{ item.demoData.title }}</div>
                          <div class="d-group-info">
                            <span>山东路45号-张三</span>
                          </div>
                          <div class="d-group-info">
                            <span>共240人</span>
                            <span>党员11人</span>
                          </div>
                          <div class="d-group-btn">加入</div>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div class="d-cpt-operate"
                    v-show="focusedCpt.tempOnlyId===item.tempOnlyId"
                    @click.stop>
                    <div class="d-cpt-btn" @click="changeCptDisplayOrder(item, 'up')">
                      <img src="@/assets/img/modules/wx-mini/index-set/up.png">
                      <p>上移</p>
                    </div>
                    <div class="d-cpt-btn" @click="delCpt(item)">
                      <img src="@/assets/img/modules/wx-mini/index-set/del.png">
                      <p>删除</p>
                    </div>
                    <div class="d-cpt-btn" @click="changeCptDisplayOrder(item, 'down')">
                      <img src="@/assets/img/modules/wx-mini/index-set/down.png">
                      <p>下移</p>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <transition v-show="focusedCpt.tempOnlyId" name="el-zoom-in-top">
            <div class="mw-set el-zoom-in-top" v-if="focusedCpt.tempOnlyId">
                <div class="d-set-head" @click="focusedCpt.demoIsUnfold = !focusedCpt.demoIsUnfold">
                  <span class="d-title">演示数据</span>
                  <img class="d-arrow"
                    :class="{'z-unfold': focusedCpt.demoIsUnfold}"
                    src="@/assets/img/modules/wx-mini/index-set/arrow-down.png">
                </div>
                <el-form v-show="focusedCpt.demoIsUnfold" ref="form">
                  <el-form-item>
                    <el-input type="textarea" v-model="focusedCpt.demoData"></el-input>
                  </el-form-item>
                </el-form>

                <div class="d-set-head" @click="focusedCpt.confIsUnfold = !focusedCpt.confIsUnfold">
                  <span class="d-title">高级选项</span>
                  <img class="d-arrow"
                    :class="{'z-unfold': focusedCpt.confIsUnfold}"
                    src="@/assets/img/modules/wx-mini/index-set/arrow-down.png">
                </div>
                <el-form v-show="focusedCpt.confIsUnfold" ref="form">
                  <el-form-item>
                    <el-input type="textarea" v-model="focusedCpt.configuration"></el-input>
                  </el-form-item>
                </el-form>

                <div class="d-operate">
                  <el-button type="default" size="small" round
                    @click="resetFocusedCptData">重置</el-button>
                  <el-button type="success" size="small" round
                    @click="saveFocusedCptData">保存</el-button>
                </div>
            </div>
          </transition>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<style lang="scss" src="@/assets/scss/modules/wx-mini/index-set.scss"></style>

<script>
import mixinViewModule from '@/mixins/view-module'
import { Loading } from 'element-ui'
import nextTick from 'dai-js/tools/nextTick'
import getRandomString from 'dai-js/tools/getRandomString'
import cloneDeep from 'lodash/cloneDeep'

export default {
  mixins: [mixinViewModule],
  data () {
    return {
      mixinViewModuleOptions: {
        getDataListURL: '/oper/crm/customer/getvalidcustomerlist',
        getDataListIsPage: false
      },

      dataList: [
        {
          customerName: '青岛李沧区党委',
          customerId: '1'
        },
        {
          customerName: '青岛市北区党委',
          customerId: '2'
        }
      ],

      // 步骤: 1列表选择 2首页配置
      step: 2,

      wxIndex: {
        customerId: '',
        customerName: '',
        clientType: ''
      },

      // 在预览中状态
      isInPreview: false,

      // 可用列表
      cptTypeList: [
        // 通用组件
        {
          functionId: '0',
          functionName: '通用组件',
          functionType: 1, // 1通用 2功能
          isUnfold: true,
          componentList: [
            {
              componentId: '1',
              componentName: '顶部标题',
              componentFrontId: 'gridNameTitle',
              configuration: {
                content: '青岛市党委'
              },
              demoData: {
                content: '青岛市市北区大港路第二网格'
              },
              configurationDescription: '请配置具体内容'
            },
            {
              componentId: '2',
              componentName: '轮播图',
              componentFrontId: 'hotNewsSwiper',
              configuration: {
                content: '青岛市党委'
              },
              demoData: {
                content: '我是标题'
              },
              configurationDescription: '请配置具体内容'
            },
            {
              componentId: '3',
              componentName: '消息通知',
              componentFrontId: 'newMessageButton',
              configuration: {
                content: '青岛市党委'
              },
              demoData: {
                content: '我是标题'
              },
              configurationDescription: '请配置具体内容'
            }
          ]
        },
        // 功能组件
        {
          functionId: '1',
          functionName: '议事厅',
          functionType: 2, // 1通用 2功能
          isUnfold: false,
          componentList: [
            {
              componentId: '5',
              componentName: '功能菜单',
              componentFrontId: 'moreFunctionIcons',
              configuration: {
                bgc: '#eee'
              },
              demoData: {
                title: '我是标题',
                content: '我是内容。我是内容。我是内容。'
              },
              configurationDescription: '请配置具体内容'
            },
            {
              componentId: '6',
              componentName: '热门群',
              componentFrontId: 'recommendGroupSlider',
              configuration: {
                bgc: '#fff'
              },
              demoData: {
                title: '我是标题',
                content: '我是内容。我是内容。我是内容。'
              },
              configurationDescription: '请配置具体内容'
            },
            {
              componentId: '7',
              componentName: '新闻列表',
              componentFrontId: 'hotSubjectList',
              configuration: {
                bgc: '#fff'
              },
              demoData: {
                title: '我是标题',
                content: '我是内容。我是内容。我是内容。'
              },
              configurationDescription: '请配置具体内容'
            }
          ]
        }
      ],
      // 当前应用组件列表
      cptList: [
        // {
        //   componentId: '1',
        //   componentName: '顶部标题',
        //   componentFrontId: 'top_title',
        //   configuration: {
        //     content: '青岛市党委'
        //   },
        //   demoData: {
        //     content: '我是标题'
        //   },
        //   configurationDescription: '请配置具体内容',
        //   displayOrder: 1,
        //   region: 1 // 区域 1top 2ban 3fixed 4cnt
        // }
      ],
      focusedCpt: {
        tempOnlyId: ''
      }
    }
  },

  components: {
  },

  computed: {
    cptTypeListTiled () {
      const { cptTypeList } = this
      let list = []
      cptTypeList.forEach(item => {
        list = [...list, ...item.componentList]
      })
      return list
    },
    topCptList () {
      return this.cptList.filter(item => this.checkCptRegion(item) === 'top')
    },
    banCptList () {
      return this.cptList.filter(item => this.checkCptRegion(item) === 'ban')
    },
    cntCptList () {
      console.log('cntCpt发生了变化')
      let arr = this.cptList.filter(item => this.checkCptRegion(item) === 'cnt')
      arr.sort((f, s) => f.displayOrder - s.displayOrder)
      return arr
    },
    fixedCptList () {
      return this.cptList.filter(item => this.checkCptRegion(item) === 'fixed')
    }
  },

  methods: {
    // 改变步骤
    toStep (s) {
      this.step = s
    },
    // 选择用户开始配置
    async startSetWxIndex (id, name, type) {
      this.wxIndex.customerId = id
      this.wxIndex.customerName = name
      this.wxIndex.clientType = type
      let loadingInstance = Loading.service()
      await nextTick(1000)
      loadingInstance.close()
      this.toStep(2)
      console.log(this.wxIndex)
    },

    // 保存配置
    save () {
      console.log('保存配置')
    },
    // 发布配置
    publish () {
      console.log('发布配置')
    },
    // 判断组件所属区域类别
    checkCptRegion (item) {
      const { componentFrontId } = item
      const fun = name => name === componentFrontId
      if (['gridNameTitle'].findIndex(fun) !== -1) {
        return 'top'
      } else if (['hotNewsSwiper'].findIndex(fun) !== -1) {
        return 'ban'
      } else if (['moreFunctionIcons', 'recommendGroupSlider', 'hotSubjectList'].findIndex(fun) !== -1) {
        return 'cnt'
      } else if (['newMessageButton'].findIndex(fun) !== -1) {
        return 'fixed'
      } else {
        return 'none'
      }
    },
    // 根据所属区域简称得到名字
    getCptRegionName (id) {
      return {
        'top': '标题区',
        'ban': '置顶区',
        'fixed': '浮窗区',
        'cnt': '功能区',
        'none': ''
      }[id]
    },
    // 添加组件到实例-前验证
    beforeAddCpt (item) {
      console.log('添加组件到实例-前验证')
      const regionType = this.checkCptRegion(item)
      const tempOnlyId = getRandomString(20)
      if (regionType === 'top') {
        if (this.topCptList.length > 0) {

        } else {
          this.addCpt(item, tempOnlyId, 1)
        }
      } else if (regionType === 'ban') {
        if (this.banCptList.length > 0) {

        } else {
          this.addCpt(item, tempOnlyId, 2)
        }
      } else if (regionType === 'fixed') {
        if (this.fixedCptList.length > 0) {

        } else {
          this.addCpt(item, tempOnlyId, 3)
        }
      } else if (regionType === 'cnt') {
        this.addCpt(item, tempOnlyId, 4, (this.cntCptList.length + 1) * 10)
      } else {
        return false
      }
    },
    // 实例内容组件重置displayOrder属性
    cntCptListResort () {
      console.log('实例内容组件重置displayOrder属性')
      this.cntCptList.forEach((item, index) => {
        item.displayOrder = (index + 1) * 10
      })
    },
    // 添加组件到实例
    addCpt (item, tempOnlyId, region, displayOrder = 0) {
      console.log('添加组件到实例')
      let trueItem = cloneDeep(item)
      trueItem.tempOnlyId = tempOnlyId
      trueItem.region = region
      trueItem.displayOrder = displayOrder
      this.cptList.push(trueItem)
    },
    // 改变实例组件显示顺序
    async changeCptDisplayOrder (item, type) {
      console.log('改变实例组件显示顺序')
      if (type === 'up') {
        item.displayOrder -= 11
      } else if (type === 'down') {
        item.displayOrder += 11
      }
      await nextTick()
      this.cntCptListResort()
    },
    // 删除组件
    delCpt (item) {
      this.cptList = this.cptList.filter(cptItem => item.tempOnlyId !== cptItem.tempOnlyId)
    },
    // 检测实例中是否存在某种类型组件
    checkExistCpt (item) {
      return this.cptList.some(cptItem => item.componentFrontId === cptItem.componentFrontId)
    },
    // 聚焦实例组件
    focusCpt (item) {
      console.log('聚焦实例组件')
      if (this.isInPreview) return
      if (this.focusedCpt.tempOnlyId === item.tempOnlyId) {
        this.focusedCpt = { tempOnlyId: '' }
      } else {
        this.focusedCpt = { ...cloneDeep(item), demoData: JSON.stringify(item.demoData), configuration: JSON.stringify(item.configuration), demoIsUnfold: true, confIsUnfold: false }
      }
    },
    // 保存聚焦组件数据
    saveFocusedCptData () {
      const { focusedCpt } = this
      this.cptList.forEach(item => {
        if (item.tempOnlyId === focusedCpt.tempOnlyId) {
          try {
            item.demoData = JSON.parse(focusedCpt.demoData)
            item.configuration = JSON.parse(focusedCpt.configuration)
          } catch (err) {
            this.$alert('json数据格式有误', '无法保存', {
              confirmButtonText: '确定'
            })
            console.log(err)
          }
        }
      })
    },
    // 重置聚焦组件数据
    resetFocusedCptData () {
      const { focusedCpt } = this
      this.cptList.forEach(item => {
        if (item.tempOnlyId === focusedCpt.tempOnlyId) {
          focusedCpt.demoData = JSON.stringify(item.demoData)
          focusedCpt.configuration = JSON.stringify(item.configuration)
        }
      })
    },

    // 改变可用列表组件展开与收起
    shiftCptTypeItemUnfold (item) {
      item.isUnfold = !item.isUnfold
    }
  }
}
</script>
