<!--
 * @Descripttion: 场景人群
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2020-08-27 10:16:37
 * @LastEditors: 无尘
 * @LastEditTime: 2020-09-21 10:25:46
 -->

<template>
  <div class="common-app-right">
    <div class="crowd-scene-tip m-b-20">
      <common-alert-tip :width="'100%'" :tip-content="tipContent" :tip-two-content="tipTwoContent"></common-alert-tip>
    </div>
    <div class="crowd-scene-search flex flex-space-between m-b-20">
      <div>
        <el-input placeholder="请输入人群名称" maxlength="50" v-model="searchVal" style="width: 408px;" prefix-icon="el-icon-search" @keyup.native="value => toInput(value)" clearable @clear="clearInput"></el-input><el-select class="w-162 m-l-10" v-model="classifyId" placeholder="所有分类" @change="changeCondition">
          <el-option label="所有分类" value=""></el-option>
          <el-option v-for="item in classifyList" :key="item.sceneCrowdCategoryId" :label="item.sceneCrowdCategoryName" :value="item.sceneCrowdCategoryId"> </el-option>
        </el-select>
      </div>
      <div><el-button :disabled="totalNum >= 20" type="primary" @click="toSync">同步场景人群</el-button></div>
    </div>
    <div class="crowd-scene-table">
      <div class="crowd-scene-table_left">
        <el-table
          :data="memberCrowdData"
          v-loading="loading"
          ref="memberCrowdData"
          row-key="sceneCrowdId"
          style="width: 100%">
          <el-table-column v-show="searchVal === '' && classifyId === ''" prop="" label="" width="56" class-name="move-row-cell">
            <template>
              <span :class="['font-22 iconfont icontuozhuaiopen color-c0c4cc', searchVal === '' && classifyId === '' ? 'show-icon' : 'hide-icon']" style="cursor: move;"></span>
            </template>
          </el-table-column>
          <el-table-column
            prop=""
            label="人群名称"
            show-overflow-tooltip>
            <template slot-scope="scope">{{scope.row.sceneCrowdName || '--'}}</template>
          </el-table-column>
          <el-table-column
            prop=""
            label="所属分类"
            show-overflow-tooltip>
            <template slot-scope="scope">{{scope.row.sceneCrowdCategoryName || '--'}}</template>
          </el-table-column>
          <el-table-column
            prop=""
            label="到期时间">
            <template slot-scope="scope">
              <div class="line-18">{{ scope.row.sceneCrowdExpireTime | timeStampToYmd }} {{ scope.row.sceneCrowdExpireTime ? '' : '--'}}</div>
              <div class="line-18">{{ scope.row.sceneCrowdExpireTime | timeStampToHms }} {{ scope.row.sceneCrowdExpireTime ? '' : '--'}}</div>
            </template>
          </el-table-column>
          <el-table-column
            label="操作">
            <template slot-scope="scope">
              <el-button type="text" @click="toEdit(scope.$index, scope.row)">编辑可见范围</el-button>
              <el-button type="text" @click="toDel(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <sync-crowd-dialog v-if="showSync" :select-ids="selectIds" :total-num="totalNum" :brand-id="brandId" @refreshData="refreshData"></sync-crowd-dialog>
    <edit-visiable v-if="showSelectStore" :brand-id="brandId" :set-item-id="setItemId" :set-type="'crowd'" :select-mode="selectMode" :range-data="rangeData"  @refreshData="refreshData"></edit-visiable>
  </div>
</template>

<script>
import commonAlertTip from '@/components/common/common-alert-tip.vue';
import syncCrowdDialog from '@/components/app/my-customer/sync-crowd-dialog.vue';
import editVisiable from '@/components/app/my-customer/edit-visiable.vue';
import fetch from '@/api/my-customer-app.js';
const { getGroupData, getClassifyData, getVisiable, postSortGroup, delCrowd } = fetch;
import { _debounce } from '@/common/js/public.js';
import showMsg from '@/common/js/showmsg.js';
import Sortable from 'sortablejs';
export default {
  name: 'CrowdScenePage',
  components: {
    commonAlertTip,
    syncCrowdDialog,
    editVisiable
  },
  props: {
    brandId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      wxEnterpriseId: localStorage.getItem('haoBanUser') ? JSON.parse(localStorage.getItem('haoBanUser')).wxEnterpriseId : '',
      tipContent: 'GIC设置场景人群后，好办顾客人群列表最多同步20个人群，次日刷新，每日刷新一次；',
      tipTwoContent: 'GIC中设置的场景人群到期后，好办移动端将不再展示该条人群；',
      searchVal: '', // 搜索
      classifyId: '', // 选择分类
      classifyList: [], // 分类列表
      memberCrowdData: [], // 场景人群列表
      memberCrowdDataCopy: [], // 场景人群列表 copy 本地搜索
      totalNum: 0, // 获取的列表总数
      loading: false, // 列表加载
      showSync: false, // 同步弹窗显示
      showSelectStore: false, // 可见范围显示
      selectMode: '',  // 选择类型 0：所有； 1：分组； 2：门店
      rangeData: [], // 选择的分组或门店
      setItemId: '', // 选中的场景 id
      selectIds: [] // 已选的所以场景 id
    };
  },
  // 生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    const that = this;
    that.$emit('showTab', '/crowd-scene');
    if (!!that.brandId) {
      that.getGroupList();
      that.getGroupClassify();
    }
    that.rowDrop('memberCrowdData');
  },
  // methods
  methods: {
    /**
     * @description: 删除标签
     * @param {Number} index
     * @param {Object} row
     */
    toDel(index, row) {
      const that = this;
      that
        .$confirm('是否要删除该场景人群?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          that.delData(row.sceneCrowdId);
        })
        .catch(() => {});
    },
    delData(sceneCrowdId) {
      const that = this;
      const para = {
        sceneCrowdId,
        wxEnterpriseId: that.wxEnterpriseId,
        enterpriseId: that.brandId,
      };
      delCrowd(para, { headers: { sign: that.brandId } })
        .then(res => {
          that.getGroupList();
          if (res.code == '0000') {
            showMsg.showmsg('删除成功', 'success');
          }else {
            showMsg.showmsg(res.message || '接口异常', 'warning');
          }
        })
        .catch(function(error) {

        });
    },
    /**
     * @description: 刷新数据
     * @param {String}  res
     * @returns {Boolean}
     * @author: 无尘
     */
    refreshData(res) {
      const that = this;
      that.showSync = false;
      that.showSelectStore = false;
      that.searchVal = '';
      that.classifyId = '';
      that.selectMode = '';
      that.rangeData = [];
      if (res == 'close') {
        return false;
      }
      that.getGroupList();
    },
    /**
     * @description: 同步
     * @author: 无尘
     */
    toSync() {
      const that = this;
      that.selectIds = that.memberCrowdData.map(ele => ele.sceneCrowdId) || [];
      that.showSync = true;
    },
    /**
     * @description: 编辑可见范围
     * @param {Number} index
     * @param {Object} row
     * @author: 无尘
     */
    toEdit(index, row) {
      const that = this;
      that.getVisiableData(row.sceneCrowdId);
    },
    getVisiableData(sceneCrowdId) {
      const that = this;
      const para = {
        wxEnterpriseId: that.wxEnterpriseId,
        enterpriseId: that.brandId,
        relationId: sceneCrowdId,
        relationType: '0',
      };
      getVisiable(para, { headers: { sign: that.brandId } })
        .then(res => {
          that.selectMode = String(res.result.storeMode);
          that.rangeData = res.result.bindRange ? JSON.parse(res.result.bindRange) : [];
          that.setItemId = sceneCrowdId;
          that.showSelectStore = true;
        })
        .catch(function(error) {

        });
    },
    /**
     * @description: 搜索输入
     * @returns {Boolean}
     * @author: 无尘
     */
    toInput: _debounce(function() {
      const that = this;
      if (that.searchVal === '' && that.classifyId === '') {
        that.getGroupList();
        return false;
      }
      that.memberCrowdData = that.memberCrowdDataCopy.filter(ele => {
        if (that.classifyId === '') {
          return ele.sceneCrowdName.indexOf(that.searchVal) != -1;
        }
        return ele.sceneCrowdName.indexOf(that.searchVal) != -1 && ele.sceneCrowdCategoryId == that.classifyId;
      });
    }, 200),
    /**
     * @description: 搜索清除
     * @returns {Boolean}
     * @author: 无尘
     */
    clearInput() {
      const that = this;
      if (that.searchVal === '' && that.classifyId === '') {
        that.getGroupList();
        return false;
      }
      if (that.classifyId != '') {
        that.memberCrowdData = that.memberCrowdDataCopy.filter(ele => {
          return ele.sceneCrowdCategoryId == that.classifyId;
        });
      };
    },
    /**
     * @description: 条件
     * @returns {Boolean}
     * @author: 无尘
     */
    changeCondition() {
      const that = this;
      if (that.searchVal === '' && that.classifyId === '') {
        that.getGroupList();
        return false;
      }
      if (that.searchVal != '' && that.classifyId != '') {
        that.memberCrowdData = that.memberCrowdDataCopy.filter(ele => {
          return ele.sceneCrowdName.indexOf(that.searchVal) != -1 && ele.sceneCrowdCategoryId == that.classifyId;
        });
      }
      if (that.searchVal != '' && that.classifyId === '') {
        that.memberCrowdData = that.memberCrowdDataCopy.filter(ele => {
          return ele.sceneCrowdName.indexOf(that.searchVal) != -1;
        });
      }
      if (that.searchVal === '' && that.classifyId != '') {
        that.memberCrowdData = that.memberCrowdDataCopy.filter(ele => {
          return ele.sceneCrowdCategoryId == that.classifyId;
        });
      }
    },
    /**
     * @description: 拖拽排序
     * @param {String} data
     * @author: 无尘
     */
    rowDrop(data) {
      const tbody = this.$refs[data].$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0];
      const that = this;
      Sortable.create(tbody, {
        handle: '.icontuozhuaiopen',
        onEnd({ newIndex, oldIndex }) {
          if (newIndex == oldIndex) {
            return false;
          }
          let arr = JSON.parse(JSON.stringify(that[data]));
          const currRow = arr.splice(oldIndex, 1)[0];
          arr.splice(newIndex, 0, currRow);
          that.setSort(arr);
        }
      });
    },
    setSort(arr) {
      const that = this;
      const para = {
        wxEnterpriseId: that.wxEnterpriseId,
        enterpriseId: that.brandId,
        sceneCrowdIds: arr.map(ele => ele.sceneCrowdId).join(',')
      };
      postSortGroup(para, { headers: { sign: that.brandId } })
        .then(res => {
          that.getGroupList();
          if (res.code == '0000') {
            showMsg.showmsg('操作成功', 'success');
          }else {
            showMsg.showmsg(res.message || '接口异常', 'warning');
          }
        })
        .catch(function(error) {

        });
    },
    /**
     * @description: 获取分类
     * @author: 无尘
     */
    getGroupClassify() {
      const that = this;
      const para = {
        wxEnterpriseId: that.wxEnterpriseId,
        enterpriseId: that.brandId
      };
      getClassifyData(para, { headers: { sign: that.brandId } })
        .then(res => {
          that.classifyList = res.result || [];
        })
        .catch(function(error) {

        });
    },
    /**
     * @description: 获取人群数据
     * @author: 无尘
     */
    getGroupList() {
      const that = this;
      that.loading = true;
      that.memberCrowdData = [];
      that.memberCrowdDataCopy = [];
      const para = {
        wxEnterpriseId: that.wxEnterpriseId,
        enterpriseId: that.brandId,
        keyword: that.searchVal,
        sceneCrowdCategoryId: that.classifyId
      };
      getGroupData(para, { headers: { sign: that.brandId } })
        .then(res => {
          that.loading = false;
          if (!!res.result && !!res.result.length) {
            that.memberCrowdData = that.sortTable(res.result);
            that.memberCrowdDataCopy = JSON.parse(JSON.stringify(that.memberCrowdData));
          }else {
            that.memberCrowdData = [];
            that.memberCrowdDataCopy = [];
            that.totalNum = 0;
          }
          if (!that.searchVal && !that.classifyId && !!res.result && !!res.result.length) {
            that.totalNum = res.result.length;
          }
        })
        .catch(function(error) {
          that.loading = false;
        });
    },
    /**
     * @description: 排序
     * @param {Array} arr
     * @returns {Array}
     * @author: 无尘
     */
    sortTable(arr) {
      arr.sort(function(a, b) {
        return (a.sort - b.sort);
      });
      return arr;
    }
  },
  watch: {
    brandId(val) {
      const that = this;
      if (val) {
        that.searchVal = '';
        that.classifyId = '';
        that.classifyList = [];
        that.getGroupClassify();
        that.getGroupList();
      }
    }
  }
};
</script>
<style lang='less' scoped>
  .font-22 {
    font-size: 22px;
  }
  .common-bottom-border {
    cursor: pointer;
    padding-bottom: 2px;
    border-bottom: 1px dashed #2f54eb;
  }
  .w-162 {
    width: 162px;
  }
  .move-row-cell {
    .icontuozhuaiopen {
      display: none;
    }
    &:hover {
      .show-icon {
        display: inline-block;
        vertical-align: middle;
      }
    }
  }
  .crowd-scene-table {
    .line-18 {
      line-height: 18px;
    }
  }
</style>
