<!--
 * @Descripttion: 同步人群场景
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2020-08-28 10:31:09
 * @LastEditors: 无尘
 * @LastEditTime: 2020-09-21 10:31:24
-->
<!--
  <sync-crowd-dialog :brand-id="brandId" :select-ids="selectIds" :total-num="totalNum" @refreshData="refreshData"></sync-crowd-dialog>
  import syncCrowdDialog from '@/components/app/my-customer/sync-crowd-dialog.vue';
-->
<template>
  <el-dialog title="同步场景人群" :visible.sync="dialogVisible" width="726px" :before-close="handleClose">
    <div class="sync-tip m-b-20">
      <common-alert-tip :width="'400px'" :tip-content="tipContent"></common-alert-tip>
    </div>
    <div class="sync-search">
      <div class="flex flex-space-between">
        <div>
          <el-input placeholder="请输入人群名称" maxlength="50" v-model="searchVal" style="width: 292px;" prefix-icon="el-icon-search" @keyup.native="value => toInput(value)" clearable @clear="clearInput"></el-input><el-select class="w-165 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>
    </div>
    <div class="m-t-20">
      <el-table class="select-table"  v-loading="loadingPage" ref="multipleTable" height="400" :data="tableData" tooltip-effect="dark" :style="{ width: '100%' }" @selection-change="handleSelectionChange">
        <el-table-column type="selection" :selectable="selectable" width="55"> </el-table-column>
        <el-table-column prop="" label="人群名称" show-overflow-tooltip>
          <template slot-scope="scope">
            <div :class="[selectIds.includes(scope.row.sceneCrowdId) ? 'color-909399': 'color-606266']">{{selectIds.includes(scope.row.sceneCrowdId) ? '（已选择）':''}}{{ scope.row.sceneCrowdName || '--' }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="" label="所属分类" show-overflow-tooltip>
          <template slot-scope="scope">
            <div :class="[selectIds.includes(scope.row.sceneCrowdId) ? 'color-909399': 'color-606266']">{{ scope.row.sceneCrowdCategoryName || '--' }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="" label="到期时间">
          <template slot-scope="scope">
            <div :class="['line-18', selectIds.includes(scope.row.sceneCrowdId) ? 'color-909399': 'color-606266']">{{ scope.row.sceneCrowdExpireTime | timeStampToYmd }} {{ !scope.row.sceneCrowdExpireTime? '--':'' }}</div>
            <div :class="['line-18', selectIds.includes(scope.row.sceneCrowdId) ? 'color-909399': 'color-606266']">{{ scope.row.sceneCrowdExpireTime | timeStampToHms }} {{ !scope.row.sceneCrowdExpireTime? '--':'' }}</div>
          </template>
        </el-table-column>
      </el-table>
      <div v-if="tableData.length" class="block common-wrap__page text-right m-t-24">
        <dm-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-size="pageSize" layout="prev, pager, next" :total="total"> </dm-pagination>
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" :loading="loadingBtn" @click="submitForm">立即同步（{{multipleSelection.length}}/{{20 - totalNum}}）</el-button>
    </div>
  </el-dialog>
</template>
<script>
import commonAlertTip from '@/components/common/common-alert-tip.vue';
import fetch from '@/api/my-customer-app.js';
const { getSyncMemberData, getClassifyData, saveSync } = fetch;
import showMsg from '@/common/js/showmsg';
import { _debounce } from '@/common/js/public';
export default {
  name: 'SyncCrowdDialog',
  components: {
    commonAlertTip
  },
  props: {
    brandId: {
      type: String,
      default: ''
    },
    totalNum: {
      type: [ String, Number ],
      default: '0'
    },
    selectIds: {
      type: Array,
      default() {
        return [];
      }
    },
  },
  data() {
    return {
      wxEnterpriseId: localStorage.getItem('haoBanUser') ? JSON.parse(localStorage.getItem('haoBanUser')).wxEnterpriseId : '',
      dialogVisible: true,
      tipContent: '从GIC最多可同步20个场景人群',
      searchVal: '',
      classifyId: '',
      classifyList: [],
      // 分页参数
      loadingPage: false,
      currentPage: 1,
      pageSize: 20,
      total: 0,
      tableData: [],
      multipleSelection: [],
      loadingBtn: false
    };
  },
  mounted() {
    const that = this;
    if (that.brandId) {
      that.getTableList();
      that.getGroupClassify();
    }
  },
  methods: {
    /**
     * @description: 禁用当前已选数据
     * @param {Object} row
     * @param {Number} index
     * @return {Boolean}
     * @author: 无尘
     */
    selectable(row, index) {
      const that = this;
      if(that.selectIds.includes(row.sceneCrowdId)){
        return false;
      }else {
        return true;
      }
    },
    /**
     * @description: 确定保存
     * @param {String} form
     * @returns {Boolean}
     * @author: 无尘
     */
    submitForm: _debounce(function() {
      const that = this;
      if (!that.multipleSelection.length) {
        showMsg.showmsg('请选择场景人群', 'warning');
        return false;
      }
      if (that.multipleSelection.length > (20 - that.totalNum)) {
        showMsg.showmsg(`最多还可同步${20 - that.totalNum}个场景人群`, 'warning');
        return false;
      }
      that.loadingBtn = true;
      that.postAdd();
    }, 300),
    postAdd() {
      const that = this;
      const params = {
        wxEnterpriseId: that.wxEnterpriseId,
        enterpriseId: that.brandId,
        sceneCrowdIds: that.multipleSelection.map(ele => ele.sceneCrowdId).join(',')
      };
      saveSync(params, { headers: { sign: that.brandId } })
        .then(res => {
          that.loadingBtn = false;
          if (res.code == '0000') {
            showMsg.showmsg('同步成功', 'success');
            that.clearData();
            that.$emit('refreshData', 'success');
          }else {
            showMsg.showmsg(res.message || '接口异常', 'warning');
          }
        })
        .catch(function(error) {
          that.loadingBtn = false;
        });
    },
    /**
     * @description: 表格---多选
     * @param {Array} val
     * @returns {Boolean}
     * @author: 无尘
     */
    handleSelectionChange(val) {
      const that = this;
      // 1.选择的数量>可选数量
      const selNum = 20 - that.totalNum;
      if (val && val.length > selNum) {
        that.multipleSelection = val.slice(0, selNum);
        const ids = that.multipleSelection.map(ele => ele.sceneCrowdId);
        that.$refs.multipleTable.clearSelection();
        that.tableData.forEach(row => {
          if (ids.includes(row.sceneCrowdId)) {
            that.$refs.multipleTable.toggleRowSelection(row);
          }
        });
        return false;
      }
      that.multipleSelection = val;
    },
    /**
     * @description: 关闭
     * @author: 无尘
     */
    cancel() {
      const that = this;
      that.clearData();
      that.$emit('refreshData', 'close');
    },
    handleClose() {
      const that = this;
      that.clearData();
      that.$emit('refreshData', 'close');
    },
    clearData() {
      const that = this;
      that.tableData = [];
      that.multipleSelection = [];
      that.searchVal = '';
      that.classifyId = '';
      that.classifyList = [];
    },
    /**
     * @description: 搜索输入
     * @author: 无尘
     */
    toInput: _debounce(function() {
      const that = this;
      that.currentPage = 1;
      that.getTableList();
    }, 500),
    /**
     * @description: 搜索清除
     * @author: 无尘
     */
    clearInput() {
      const that = this;
      that.currentPage = 1;
      that.getTableList();
    },
    /**
     * @description: 条件
     * @author: 无尘
     */
    changeCondition() {
      const that = this;
      that.currentPage = 1;
      that.getTableList();
    },

    /**
     * @description: 分页---页码变化
     * @param {Number} val
     * @author: 无尘
     */
    handleSizeChange(val) {
      const that = this;
      that.currentPage = 1;
      that.pageSize = val;
      that.getTableList();
    },

    /**
     * @description: 分页---当前页变化
     * @param {Number} val
     * @author: 无尘
     */
    handleCurrentChange(val) {
      const that = this;
      that.currentPage = val;
      that.getTableList();
    },
    /**
     * @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: 无尘
     */
    getTableList() {
      const that = this;
      that.loadingPage = true;
      const para = {
        wxEnterpriseId: that.wxEnterpriseId,
        enterpriseId: that.brandId,
        keyword: that.searchVal,
        sceneCrowdCategoryId: that.classifyId,
        pageNum: that.currentPage, // 当前页
        pageSize: that.pageSize, // 一页显示个数
      };
      getSyncMemberData(para, { headers: { sign: that.brandId } })
        .then(res => {
          that.loadingPage = false;
          that.tableData = res.result.result || [];
          that.total = res.result.totalCount;
        })
        .catch(function(error) {
          that.loadingPage = false;
        });
    }
  },
  watch: {
    brandId(val) {
      const that = this;
      if (val) {
        that.getTableList();
        that.getGroupClassify();
      }
    }
  }
};
</script>
<style type="text/less" lang="less" scoped>
  .line-18 {
    line-height: 18px;
  }
  .w-165 {
    width: 165px;
  }
  .dialog-footer {
    margin-top: -20px;
  }
  .el-table {
    .cell {
      &.el-tooltip {
        div {
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
    }
  }
</style>
