<template>
  <div class="memberGroupList-wrap common-wrap">
    <nav-crumb :navpath="navpath"></nav-crumb>
    <div class="right-content">
      <!-- 左边的会员分组 -->
      <div class="left-box">
        <group-list @getRecommend="getRecommend" @second-list="getsecondList"></group-list>
      </div>
      <!-- 右边的表格 -->
      <div class="right-box" v-show="!isRecommend">
        <div class="common-wrap__opt">
          <el-input class="w-220 m-r-8" placeholder="请输入关键字搜索人群" prefix-icon="el-icon-search" v-model="tagSearch" clearable @clear="clearSearch" @keyup.enter.native="searchEnterFun"> </el-input>
          <el-select v-model="statusSelect" @change="searchByStatus" placeholder="请选择" class="w-220 m-l-0">
            <el-option :key="0" label="失效" :value="0"> </el-option>
            <el-option :key="1" label="有效" :value="1"> </el-option>
            <el-option key="" label="全部" value=""> </el-option>
          </el-select>
          <div class="batch-option">
            <el-select v-model="batchSelect" @change="batchHandleSelect" style="width: 150px;" placeholder="批量操作" class="w-220 m-l-0">
              <el-option :key="0" label="失效" :value="0"> </el-option>
              <el-option :key="1" label="删除" :value="1"> </el-option>
              <el-option :key="2" label="修改所属分类" :value="2"> </el-option>
            </el-select>
            <el-button type="primary" @click="toAddGroup" class="fr">新增分组</el-button>
          </div>
        </div>
        <div class="common-wrap__table m-t-20">
          <el-table v-loading="loading" :row-class-name="setRowClassName" ref="multipleTable" :data="groupTableData" tooltip-effect="dark" style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"> </el-table-column>
            <el-table-column label="分组名称" width="150px">
              <template slot-scope="scope">
                <el-popover placement="top-start" width="200" trigger="hover">
                  <div>
                    <p>名称：{{ scope.row.groupName }}</p>
                    <p>描述：{{ scope.row.describle }}</p>
                  </div>
                  <a slot="reference" @click="changeRoute('/memberGroupDetail?memberTagGroupId=' + scope.row.memberTagGroupId)" class="pointer a-href">{{ scope.row.groupName }}</a>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column label="是否实时"
              ><!-- width="80px" -->
              <template slot-scope="scope">
                {{ scope.row.isRealTime == 1 ? '实时' : '非实时' }}
              </template>
            </el-table-column>
            <el-table-column label="最近更新时间" show-overflow-tooltip
              ><!-- width="130px" -->
              <template slot-scope="scope">
                <p class="h-18">{{ scope.row.latestUpdateTime | formatTimeYMD }}</p>
                <p class="h-18">{{ scope.row.latestUpdateTime | formatTimeHMS }}</p>
              </template>
            </el-table-column>
            <el-table-column label="更新频率" show-overflow-tooltip>
              <template slot-scope="scope"
                ><!--  width="100px" -->
                <!-- {{ scope.row.updateType == 1 ? '每天一次' : scope.row.updateType == 2 ? (scope.row.updateDay ? '每周'+ weekArr[scope.row.updateDay - 1] : '每周一次') : (scope.row.updateDay ? '每月' + scope.row.updateDay + '号' : '每月一次')}} -->
                <template v-if="scope.row.isRealTime == 0">
                  {{ (scope.row.updateType, scope.row.updateDay | formatUpdateFrequency) }}
                </template>
                <template v-else>
                  --
                </template>
              </template>
            </el-table-column>
            <el-table-column prop="state" label="状态"
              ><!-- width="50px" -->
              <template slot-scope="scope">
                {{ scope.row.effectiveStatus == 1 ? '有效' : '失效' }}
              </template>
            </el-table-column>
            <el-table-column prop="peopleCover" label="覆盖人数" show-overflow-tooltip
              ><!-- width="150px" -->
              <template slot="header">
                覆盖人数
                <el-popover placement="top-start" width="200" trigger="hover">
                  <div>
                    默认显示上次页面缓存人数，可点击刷新按钮查看当页分组最新人数。
                  </div>
                  <el-button type="text" @click="getGroupList">刷新</el-button>
                  <i slot="reference" class="el-icon-more icon-transform-nine"></i>
                </el-popover>
              </template>

              <template slot-scope="scope">
                {{ (scope.row.memberCount || 0) | formatNum }} 人
              </template>
            </el-table-column>
            <el-table-column prop="appStatus" label="好办展示"
              ><!-- width="100px" -->
              <template slot-scope="scope">
                <el-switch :active-value="1" :inactive-value="0" v-model="scope.row.appStatus" active-color="#1890ff" @change="switchAppStatus(scope.row.appStatus, scope.row)"> </el-switch>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" show-overflow-tooltip
              ><!-- width="100px" -->
              <template slot-scope="scope">
                <p class="h-18">{{ scope.row.createTime | formatTimeYMD }}</p>
                <p class="h-18">{{ scope.row.createTime | formatTimeHMS }}</p>
              </template>
            </el-table-column>
            <el-table-column prop="recentUpdateDate" label="到期时间" show-overflow-tooltip
              ><!-- width="100px" -->
              <template slot-scope="scope">
                <p class="h-18">{{ scope.row.effectiveDate | formatTimeYMD }}</p>
                <p class="h-18">{{ scope.row.effectiveDate | formatTimeHMS }}</p>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="257px">
              <template slot-scope="scope">
                <!-- <el-button type="text" size="small" class="p-r-12" v-if="scope.row.effectiveStatus == 1" @click="toInvalid(scope.row)">失效</el-button> -->
                <router-link
                  :to="{
                    path: '/memberGroupDetail',
                    query: { memberTagGroupId: scope.row.memberTagGroupId }
                  }"
                  class="edit-btn el-button--text p-r-12"
                  >详情</router-link
                >

                <router-link
                  :to="{
                    path: '/memberGroupEdit',
                    query: { memberTagGroupId: scope.row.memberTagGroupId }
                  }"
                  class="edit-btn el-button--text p-r-12"
                  >编辑</router-link
                >
                <!-- <el-button type="text" size="small" class="p-r-12" @click="toDelTag(scope.row, scope.$index)">删除</el-button>
                <el-popover placement="top" width="50" trigger="hover">
                  刷新覆盖人数
                  <el-button slot="reference" type="text" size="small" @click="refreshGroup(scope.row)">刷新</el-button>
                </el-popover> -->
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="block common-wrap__page text-right" v-if="groupTableData.length != 0">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </div>
      </div>

      <div class="right-box recommend-box" v-show="isRecommend">
        <el-tabs v-model="activeName" @tab-click="handleTabClick">
          <el-tab-pane :label="item.recommendName" :name="item.recommendName" v-for="item in recommendItems" :key="item.tagGroupRecommendId">
            <recommend-table :data="recommendData"></recommend-table>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <vue-gic-footer></vue-gic-footer>
  </div>
</template>
<script>
/* eslint-disable */
import navCrumb from '@/components/nav/nav.vue';
import strLength from '@/common/js/strlen';
import showMsg from '@/common/js/showmsg';
import errMsg from '@/common/js/error';
import timeFormat from '@/common/js/timeFormat';
import { _debounce } from '@/common/js/public';
import { getRequest } from '@/api/api';
import { recommendList, recommendGroupList, findSecondMemberList } from '@/request/api';
import GroupList from './group-list';
import RecommendTable from './recommend-table';
// import { memberGroupList } from '@/request/api';
// import groupTransfer from '@/components/groupTransfer';
export default {
  name: 'memberGroupList',
  components: {
    // groupTransfer,
    navCrumb,
    GroupList,
    RecommendTable
  },
  data() {
    return {
      dialogVisible: true,
      isRecommend: false,
      recommendItems: [],
      recommendData: [], // 推荐分组的数据
      activeName: '',
      // 面包屑参数
      navpath: [
        {
          name: '首页',
          path: `${window.location.origin}/report/#/memberSummary`,
          relocation: true
        },
        {
          name: '会员管理',
          path: ''
        },
        {
          name: '会员分组',
          path: ''
        }
      ],

      tagSearch: '', // 搜索值绑定的参数

      // 会员分组列表数据
      groupTableData: [],

      // 分页参数
      currentPage: 1,
      pageSize: 20,
      total: 0,
      groupSetShow: false,
      loading: false,
      statusSelect: '',
      batchSelect: ''
    };
  },
  created() {
    this.loading = true;
    // this.getMemberGroupList();
  },
  filters: {
    formatTimeYMD(data) {
      return data && data != '- -' ? data.split(' ')[0] : '--';
    },
    formatTimeHMS(data) {
      return data && data != '- -' ? data.split(' ')[1] : '--';
    },
    formatNum(data) {
      const reg = /\d{1,3}(?=(\d{3})+$)/g;
      return (data + '').replace(reg, '$&,');
    },
    formatUpdateFrequency(type, day) {
      switch (type) {
        case 1:
          return '每天一次';
          break;
        case 2:
          let weekArr = ['一', '二', '三', '四', '五', '六', '日'];
          return day ? `每周${weekArr[day - 1]}` : '每周一次';
          break;
        case 3:
          return day ? `每月${day}号` : '每月一次';
          break;
        default:
          return '--';
      }
    }
  },
  methods: {
    // 会员分组二级
    getsecondList(list) {
      const param = {
        pageNum: 1,
        pageSize: 20,
        requestProject: 'gic-member-tag-web',
        memberTagGroupClassifyId: list.memberTagGroupClassifyId
      };
      findSecondMemberList(param).then(res => {
        if (res.errorCode == 1) {
          this.groupTableData = res.result.result.map(el => ({
            ...el,
            createTime: timeFormat.timeToDateTime(el.createTime)
          }));
        } else {
          this.groupTableData = [];
        }
      }).catch(err => {
        console.log(err);
      });
    },
    // 切换推荐分组
    handleTabClick(instance) {
      let tabId = this.checkTabIndex(instance);
      if (tabId) {
        this.getRecommendList(tabId);
      }
    },
    // 查找列表请求需要的id
    checkTabIndex(instance) {
      let index = this.recommendItems.findIndex(el => el.recommendName == instance.name);
      if (index >= 0) {
        return this.recommendItems[index].tagGroupRecommendId;
      }
    },
    // 推荐分组
    getRecommend() {
      this.isRecommend = true;
      recommendGroupList().then(res => {
        if (res.errorCode == 1) {
          this.recommendItems = res.result;
          if (this.recommendItems && this.recommendItems.length) {
            this.activeName = this.recommendItems[0].recommendName;
            // 查第一个列表的数据
            this.getRecommendList(this.recommendItems[0].tagGroupRecommendId);
          } else {
            this.recommendItems = [];
          }
        }
      }).catch(err => {
        console.log(err);
      });
    },
    /**
     * 推荐分组列 
     */
    getRecommendList(id) {
      const param = {
        tagGroupRecommendId: id,
        requestProject: 'gic-member-tag-web',
      };
      recommendList(param).then(res => {
        if (res.errorCode == 1) {
          this.recommendData = res.result;
        } else {
          this.recommendData = [];
        }
      }).catch(err => {
        console.log(err);
      });
    },

    // 勾选框全选
    handleSelectionChange() {

    },
    /**
     * 批量操作
     */
    batchHandleSelect(val) {

    },

    setRowClassName({ row, rowIndex }) {
      // console.log(row, rowIndex);
    },
    /**
     *
     */
    showGroupSet() {
      this.groupSetShow = true;
    },

    /**
     * 路由跳转
     */
    changeRoute(route) {
      this.$router.push(route);
    },

    /**
     * 新增分组
     */
    toAddGroup() {
      this.changeRoute('/memberGroupEdit');
    },

    /**
     * 搜索分组清空
     */
    clearSearch() {
      this.currentPage = 1;
      this.getGroupList();
    },

    /**
     * 搜索分组
     */
    searchEnterFun(e) {
      const that = this;
      // console.log(e)
      that.currentPage = 1;
      that.getGroupList();
    },

    /**
     * 分页---页码变化
     */
    handleSizeChange(val) {
      const that = this;
      // console.log(`每页 ${val} 条`);
      that.pageSize = val;
      that.getGroupList();
    },

    /**
     * 分页---当前页变化
     */
    handleCurrentChange(val) {
      const that = this;
      // console.log(`当前页: ${val}`);
      that.currentPage = val;
      that.getGroupList();
    },

    /**
     * 点击失效
     */
    toInvalid(info) {
      // console.log(info, "thisGroup");
      const that = this;
      that
        .$confirm('该分组失效后，不再更新数据，确认要失效吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          that.loading = true;
          let pramas = {
            effectiveStatus: '0',
            memberTagGroupId: info.memberTagGroupId
          };
          that.updateGroup(pramas, info);
        })
        .catch(() => {});
    },

    /**
     * 更新好办展示状态
     */
    switchAppStatus(status, obj) {
      console.log(status, obj);
      const that = this;
      that.loading = true;
      // const appStatus = status ? 1 : 0;
      const memberTagGroupId = obj.memberTagGroupId;
      let param = {
        memberTagGroupId,
        appStatus: status
      };
      that.updateGroup(param, obj);
    },

    /**
     * 刷新当前分组
     */
    refreshGroup(obj) {
      // console.log(obj);
      const that = this;
      that.loading = true;
      const memberTagGroupId = obj.memberTagGroupId;
      let params = {
        memberTagGroupId
      };
      getRequest('/member-tag-member/getMemberCountByGroupId.json', params)
        .then(res => {
          // console.log(res, 'count');
          obj.memberCount = res.data.result;
          that.loading = false;
          // let param = {
          //   memberTagGroupId,
          //   memberCount: res.data.result.page.totalCount
          // };
          // that.updateGroup(param, obj);
        })
        .catch(e => {
          that.loading = false;
          // console.log(e, 'error');
        });
    },

    /**
     * 简单更新当前分组 -- 失效/更改人数
     */
    updateGroup(pramas, info) {
      const that = this;
      getRequest('/member-tag-group/simpleUpdate.json', pramas)
        .then(res => {
          // console.log(res, 'updateResult');
          info.effectiveStatus = pramas.effectiveStatus || info.effectiveStatus;
          info.memberCount =
            pramas.memberCount || pramas.memberCount == 0 ? pramas.memberCount : info.memberCount;
          that.loading = false;
          that.$message.success({
            duration: 1000,
            message: '操作成功！'
          });
          that.loading = false;
        })
        .catch(e => {
          // console.log(e, 'error');
          that.loading = false;
        });
    },

    /**
     * 删除当前分组 -- 取消
     */
    cancelDelTag(index, row) {
      row.popVisible = false;
    },

    /**
     * 删除当前分组 -- 确定
     */
    toDelTag(obj, index) {
      const that = this;
      that
        .$confirm(
          `该分组覆盖${that.$options.filters['formatNum'](
            obj.memberCount || 0
          )}人，一旦删除无法恢复，确认要删除吗？`,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        .then(() => {
          // that.groupTableData.splice(index,1)
          that.loading = true;
          that.delGroup(obj.memberTagGroupId, index);
        })
        .catch(() => {});
    },

    /**
     * 删除当前分组 -- API
     */
    delGroup(id, index) {
      const that = this;
      const para = {
        memberTagGroupId: id // 搜索字段
      };
      getRequest('/member-tag-group/delete.json', para)
        .then(res => {
          // console.log(res, "delResult");
          var resData = res.data;
          that.loading = false;
          if (resData.errorCode == 1) {
            that.groupTableData.splice(index, 1);
            that.$message.success({
              duration: 1000,
              message: '删除成功！'
            });
            return;
          } else if (resData.errorCode == 200003) {
            that.$confirm(`该分组正在被活动使用，无法删除！`, '提示', {
              confirmButtonText: '确定',
              type: 'warning'
            });
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.loading = false;
          // console.log(error);
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    /**
     * 通过状态筛选列表
     */
    searchByStatus(val) {
      this.loading = true;
      console.log(val, this.statusSelect);
      this.getGroupList();
    },
    /**
     * 获取列表数据
     */
    getGroupList() {
      const that = this;
      const para = {
        groupName: that.tagSearch, // 搜索字段
        pageSize: that.pageSize,
        pageNum: that.currentPage,
        effectiveStatus: that.statusSelect
      };
      getRequest('/member-tag-group/findList.json', para)
        .then(res => {
          // console.log(res, "groupList");
          var resData = res.data;
          if (resData.errorCode == 1) {
            that.total = resData.result.totalCount;
            resData.result.result.forEach(function(ele, index) {
              if (!ele.latestUpdateTime) {
                ele.latestUpdateTime = '- -';
              }

              if (ele.createTime) {
                ele.createTime = timeFormat.timeToDateTime(ele.createTime);
              }
            });

            that.groupTableData = resData.result.result;
            that.loading = false;
            // showMsg.showmsg('保存成功','success')
            return;
          }
          that.loading = false;
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          // console.log(error);
          that.loading = false;
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    }
  },
  mounted() {
    this.getGroupList();
  }
};
</script>
<style lang="scss">
.common-wrap__opt {
  font-size: 0;
  .m-r-8 {
    margin-right: 8px;
  }
}
.h-18 {
  height: 18px;
  line-height: 18px;
}
.right-content {
  display: flex;
  .left-box {
    flex: 0 0 200px;
    background-color: #fff;
    border-right: 1px solid rgba(220,223,230,1);
  }
  .right-box {
    flex: 1;
    .batch-option {
      float: right;
      .fr {
        margin-left: 10px;
      }
    }
  }
}
</style>
