<template>
  <div class="memberGroupList-wrap common-wrap">
    <nav-crumb :navpath="navpath"></nav-crumb>
    <div class="right-content">
      <div class="right-box">
        <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>
          <el-button type="primary" @click="toAddGroup" class="fr">新增分组</el-button>
        </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%">
            <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" class="pointer a-href" :href="'#/memberGroupDetail?memberTagGroupId='+scope.row.memberTagGroupId">{{ 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-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>
    <vue-gic-footer></vue-gic-footer>
  </div>
</template>
<script>
  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, postRequest, postJson, postForm } from '@/api/api';
  // import groupTransfer from '@/components/groupTransfer';
  export default {
      name: 'memberGroupList',
      components: {
        // groupTransfer,
        navCrumb
      },
      data() {
        return {
          dialogVisible: true,
          // 面包屑参数
          navpath: [
            {
              name: '首页',
              path: `${window.origin}/report/#/memberSummary`,
              relocation: true
            },
            {
              name: '会员管理',
              path: ''
            },
            {
              name: '会员分组',
              path: ''
            }
          ],

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

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

          // 分页参数
          currentPage: 1,
          pageSize: 20,
          total: 0,
          groupSetShow: false,
          loading: false,
          statusSelect: ''
        }
      },
      created() {
        this.loading = true;
      },
      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) {
          let that = this;
          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: {
        setRowClassName({row, rowIndex}) {
          // console.log(row, rowIndex);
        },
        /**
         *
         */
        showGroupSet() {
          const that = this;
          that.groupSetShow = true;
        },

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

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

        /**
         * 搜索分组清空
         */
        clearSearch() {
          const that = this
          that.currentPage = 1;
          that.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) {
          const that = this
          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() {
        const that = this
        that.getGroupList()
      }
    }
</script>
<style lang="scss">
  .common-wrap__opt {
    font-size: 0;
    .m-r-8 {
      margin-right: 8px;
    }
  }
  .h-18 {
    height: 18px;
    line-height: 18px;
  }
</style>
