<template>
  <div class="member-group">
    <div class="flex">
      <el-tabs v-model="activeType" class="tabs" ref="fixedGroup" @tab-click="onTabClick">
        <el-tab-pane label="我的客户分组" name="1"></el-tab-pane>
        <el-tab-pane label="固化分组" name="2"></el-tab-pane>
        <el-tab-pane label="金字塔客户分组" name="3"></el-tab-pane>
      </el-tabs>
    </div>
    <div class="right-content">
      <!-- 左边的会员分组 -->
      <div class="left-box" v-show="activeType != 3 || !isNew">
        <group-list ref="groupList" :addGroupDialog.sync="addGroupDialog" :activeType="activeType" @getRecommend="getRecommend" @second-list="getsecondList"></group-list>
         <div @click="addGroupDialog = true" :limit-code="$buttonCode.memberTagAddCateGory" v-if="$getButtonLimit($buttonCode.memberTagAddCateGory) && activeType != 3" class="add-category">
          <el-button v-show="activeType == 1" type="primary" class="ghost-btn add-group">新增分类</el-button>
        </div>
      </div>
      <!-- 右边的表格 -->
      <template v-if="showFixedList">
        <!-- 固化人群列表 -->
        <div class="right-box">
          <div class="common-wrap__opt">
            <div class="top m-b-20">
              <p class="tips">固化分组仅在分组生效开始时间查询一次数据，后续数据不会发生变化，分组失效后数据会自动清空。</p>
            </div>
            <el-input
              class="m-r-8 w-160"
              placeholder="请输入分组名称"
              prefix-icon="el-icon-search"
              v-model="tagSearch"
              clearable
              @clear="clearSearch"
              @keyup.enter.native="searchEnterFun"
            />
            <el-select v-model="statusSelect" @change="searchByStatus" placeholder="是否有效" class="w120  m-r-8" clearable>
              <el-option :key="0" label="失效" :value="0"> </el-option>
              <el-option :key="1" label="有效" :value="1"> </el-option>
            </el-select>

            <!-- 实时和非实时 -->
            <!-- <el-select v-model="isRealTime" @change="realTimeStatus" placeholder="是否实时" class="w120 m-l-0 m-r-8" clearable>
              <el-option :key="0" label="非实时" :value="0"> </el-option>
              <el-option :key="1" label="实时" :value="1"> </el-option>
            </el-select> -->

            <!--是否展示好办-->
            <el-select v-model="isHaoban" @change="changeHaoBan" placeholder="好办是否展示" class="w130 " clearable>
              <el-option :key="0" label="不展示" :value="0"> </el-option>
              <el-option :key="1" label="展示" :value="1"> </el-option>
            </el-select>
            <span class="look-self m-l-10" v-if="[2,3].includes($store.state.departAuth) || $store.state.isSuperAdmin">
               <el-checkbox v-model="isSelf">
                 仅看本人
               </el-checkbox>
               <el-tooltip placement="top" trigger="hover" content="其它账号创建的分组覆盖人数根据创建人管辖门店查询数据"><i class="iconfont icon-QuestionCircleOutlined icon" style="vertical-align: middle" /></el-tooltip>
            </span>
            <el-button type="primary m-l-10" v-if="$getButtonLimit($buttonCode.memberTagAddGroup)" :limit-code="$buttonCode.memberTagAddGroup" @click="toAddGroup('fixed')" class="fr">新增分组</el-button>
            <el-button class="btn-foled-all"  @click="$router.push('/memberGroupLog')">分组操作日志</el-button>
          </div>
          <div class="common-wrap__table m-t-20">
            <el-table
              key="fixedList"
              v-loading="loading"
              ref="multipleTable"
              :data="groupTableData"
              tooltip-effect="dark"
              row-key="memberTagGroupId"
            >
              <el-table-column label="分组名称" fixed="left" min-width="180">
                <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>
                    <router-link class="a-href" slot="reference" :to="`/memberGroupDetail?memberTagGroupId=${scope.row.memberTagGroupId}&type=2`">
                      {{ scope.row.groupName }}
                    </router-link>
                  </el-popover>
                </template>
              </el-table-column>
              <el-table-column prop="latestUpdateTime" min-width="100" label="更新时间">
                <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 prop="state" label="状态" min-width="80">
                <template slot="header">
                  状态
                  <el-tooltip effect="dark" placement="top">
                    <div slot="content">
                       <p>失效的非实时分组不再更新人数，营销活动无法选用失效的分组</p>
                    </div>
                    <i class="iconfont icon-QuestionCircleOutlined icon"></i>
                  </el-tooltip>
                </template>
                <template slot-scope="scope">
                  <span :class="scope.row.effectiveStatus == 1 ? 'dm-status--success' : 'dm-status--info'"></span>
                  {{ scope.row.effectiveStatus == 1 ? '有效' : '失效' }}
                </template>
              </el-table-column>
              <el-table-column label="分类名称" prop="groupClassifyName"></el-table-column>
              <el-table-column prop="peopleCover" label="覆盖人数" show-overflow-tooltip min-width="100">
                <template slot-scope="scope">
                  {{ (scope.row.memberCount || 0) | formatNum }}
                </template>
              </el-table-column>
              <el-table-column prop="appStatus" label="好办展示" min-width="100" :limit-code='$buttonCode.memberTagOpenHaoBan' v-if='$getButtonLimit($buttonCode.memberTagOpenHaoBan)'>
                <template slot="header">
                  好办展示
                  <el-tooltip effect="dark" content="开启后，默认次日更新至好办管理后台，如需立即更新，请至好办管理后台操作“同步”" placement="top">
                    <i class="iconfont icon-QuestionCircleOutlined icon"></i>
                  </el-tooltip>
                </template>
                <template slot-scope="scope">
                  <el-switch :active-value="1" :inactive-value="0" v-model="scope.row.appStatus" active-color="#2F54EB" @change="switchAppStatus(scope.row.appStatus, scope.row)"> </el-switch>
                </template>
              </el-table-column>
              <el-table-column prop="fixedTime" min-width="100" label="生效时间">
                <template slot-scope="scope">
                  <p class="h-18">{{ scope.row.fixedTime | formatTimeYMD }}</p>
                </template>
              </el-table-column>
              <el-table-column prop="effectiveDate" min-width="100" label="到期时间">
                <template slot-scope="scope">
                  <p v-if="!scope.row.isRealTime" class="h-18">{{ scope.row.effectiveDate | formatTimeYMD }}</p>
                  <p v-else class="h-18">--</p>
                </template>
              </el-table-column>
              <el-table-column label="创建人" prop="createUserName" min-width="110" v-if="[2,3].includes($store.state.departAuth) || $store.state.isSuperAdmin">
                <template slot-scope="{ row }">{{ row.createUserName || '--'}}</template>
              </el-table-column>
              <el-table-column prop="createTime" min-width="100" label="创建时间">
                <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 label="操作" width="180" fixed="right" v-if="$getButtonLimit($buttonCode.memberTagDelGroup) || $getButtonLimit($buttonCode.memberTagFixedPile)">
                <template slot-scope="scope">
                  <router-link
                    :to="`/memberGroupDetail?memberTagGroupId=${scope.row.memberTagGroupId}&type=2`"
                    class="edit-btn el-button--text m-r-20"
                    :limit-code='$buttonCode.memberTagGroupDetail'
                    v-if='$getButtonLimit($buttonCode.memberTagGroupDetail)'
                  >
                    详情
                  </router-link>
                  <el-button type="text" class="m-r-12" v-if="!scope.row.fixedPile && scope.row.effectiveStatus && $getButtonLimit($buttonCode.memberTagFixedPile)" :limit-code='$buttonCode.memberTagFixedPile' @click="handleFixedPile(scope.row)">分堆</el-button>
                  <el-button type="text" v-if="$getButtonLimit($buttonCode.memberTagDelGroup)" @click="handleDeleteFixedPile(scope.row)"  :limit-code='$buttonCode.memberTagDelGroup'>删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="block common-wrap__page text-right" v-if="groupTableData.length != 0">
            <dm-pagination
              background
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="pageSize"
              layout="total, prev, pager, next"
              :total="total">
            </dm-pagination>
          </div>
        </div>
      </template>
      <template v-else>
        <div class="right-box" v-show="!isRecommend">
          <div class="common-wrap__opt">
            <div class="top">
              <p class="tips">实时分组数据实时更新，非实时分组数据每天凌晨更新 1 次，非实时分组失效后数据会自动清空。</p>
              <div class="title m-b-20 m-t-16">
                <h2>
                  <span class="tips">共 {{ total || 0 }} 个分组，其中非实时分组 {{ classifyOptions.notRealTimeGroupNum || 0 }} 个，失效分组 {{ classifyOptions.notEffectiveGroupNum || 0 }} 个</span>
                </h2>
                <span class="count">剩余可创建非实时分组数量：{{ classifyOptions.residueCreateGroupNum || 0 }}</span>
              </div>
            </div>
            <el-input
              class="w-160 m-r-8"
              placeholder="请输入分组名称"
              prefix-icon="el-icon-search"
              v-model="tagSearch"
              clearable
              @clear="clearSearch"
              @keyup.enter.native="searchEnterFun"
            />
            <el-select v-model="statusSelect" @change="searchByStatus" placeholder="是否有效" class="m-r-8" style="width: 120px" clearable>
              <el-option :key="0" label="失效" :value="0"> </el-option>
              <el-option :key="1" label="有效" :value="1"> </el-option>
            </el-select>

            <!-- 实时和非实时 -->
            <el-select v-model="isRealTime" @change="realTimeStatus" placeholder="是否实时" class="m-l-0 m-r-8" style="width: 120px" clearable>
              <el-option :key="0" label="非实时" :value="0"> </el-option>
              <el-option :key="1" label="实时" :value="1"> </el-option>
            </el-select>

            <!--是否展示好办-->
            <el-select v-model="isHaoban" @change="changeHaoBan" placeholder="好办是否展示" class="w130" clearable>
              <el-option :key="0" label="不展示" :value="0"> </el-option>
              <el-option :key="1" label="展示" :value="1"> </el-option>
            </el-select>
            <div class="batch-option">
              <el-select v-model="batchSelect" @change="batchHandleSelect" @focus="handleFocus" placeholder="批量操作" style="width: 120px">
                <el-option :key="0" label="失效" :value="0" :limit-code='$buttonCode.memberTagBatchDeActive' v-if='$getButtonLimit($buttonCode.memberTagBatchDeActive)'> </el-option>
                <el-option :key="1" label="删除" :value="1" :limit-code='$buttonCode.memberTagBatchDel' v-if='$getButtonLimit($buttonCode.memberTagBatchDel)'> </el-option>
                <el-option :key="2" label="修改所属分类" :value="2" :limit-code='$buttonCode.memberTagBatchEditBelong' v-if='$getButtonLimit($buttonCode.memberTagBatchEditBelong)'> </el-option>
              </el-select>
              <el-tooltip v-if="$getButtonLimit($buttonCode.memberGroupHandleLog)" class="item" content="分组内的标签条件或者其他信息有过编辑的，均在此查看" placement="top">
                <el-button class="fr" :limit-code="$buttonCode.memberGroupHandleLog" @click="$router.push('/memberGroupLog')">分组操作日志</el-button>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" v-if="$getButtonLimit($buttonCode.memberTagAddGroup)" :content="countGroupText" placement="top">
                <el-button type="primary" :limit-code="$buttonCode.memberTagAddGroup" @click="toAddGroup" class="fr">新增分组</el-button>
              </el-tooltip>
            </div>
            <span class="look-self m-l-10" v-if="[2,3].includes($store.state.departAuth) || $store.state.isSuperAdmin">
               <el-checkbox v-model="isSelf">
                 仅看本人
                </el-checkbox>
                 <el-tooltip placement="top" trigger="hover" content="其它账号创建的分组覆盖人数根据创建人管辖门店查询数据"><i class="iconfont icon-QuestionCircleOutlined icon" style="vertical-align: middle" /></el-tooltip>
            </span>
          </div>
          <div class="common-wrap__table m-t-20">
            <el-table
              v-loading="loading"
              ref="multipleTable"
              :data="groupTableData"
              tooltip-effect="dark"
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="55"> </el-table-column>
              <el-table-column label="分组名称" fixed="left" min-width="200">
                <template slot-scope="scope">
                  <span :class="[scope.row.isRealTime ? 'real-time' : 'no-real-time']">{{ scope.row.isRealTime ? '实时' : '非实时'}}</span>
                  <el-popover placement="top-start" width="200" trigger="hover">
                    <div>
                      <p>名称：{{ scope.row.groupName }}</p>
                      <p>描述：{{ scope.row.describle }}</p>
                    </div>
                    <router-link class="a-href" slot="reference" :to="`/memberGroupDetail?memberTagGroupId=${scope.row.memberTagGroupId}&type=1`">
                      {{ scope.row.groupName }}
                    </router-link>
                  </el-popover>
                </template>
              </el-table-column>
              <el-table-column label="最近更新时间" width="110">
                <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 prop="state" label="状态" min-width="70">
                <template slot="header">
                  状态
                  <el-tooltip effect="dark" placement="top">
                    <div slot="content">
                      <p>失效的非实时分组不再更新人数，营销活动无法选用失效的分组</p>
                    </div>
                    <i class="iconfont icon-QuestionCircleOutlined icon"></i>
                  </el-tooltip>
                </template>
                <template slot-scope="scope">
                  <span :class="scope.row.effectiveStatus == 1 ? 'dm-status--success' : 'dm-status--info'"></span>
                  {{ scope.row.effectiveStatus == 1 ? '有效' : '失效' }}
                </template>
              </el-table-column>
              <el-table-column label="分类名称" prop="groupClassifyName"></el-table-column>
              <el-table-column prop="peopleCover" label="覆盖人数" min-width="100" show-overflow-tooltip >
                <template slot="header">
                  覆盖人数
                  <el-popover width="260" trigger="hover">
                    <div style="color: #303133;">
                      默认显示上次页面缓存人数，可点击刷新按钮查看当页分组最新人数。
                    </div>
                    <i slot="reference" class="iconfont icon-zhongzhi refresh" @click="refershMember('')"></i>
                  </el-popover>
                </template>

                <template slot-scope="scope">
                  {{ (scope.row.memberCount || 0) | formatNum }}
                </template>
              </el-table-column>
              <el-table-column prop="appStatus" label="好办展示" min-width="100" :limit-code='$buttonCode.memberTagOpenHaoBan' v-if='$getButtonLimit($buttonCode.memberTagOpenHaoBan)'>
                <template slot="header">
                  好办展示
                  <el-tooltip effect="dark" content="开启后，默认次日更新至好办管理后台，如需立即更新，请至好办管理后台操作“同步”" placement="top">
                    <i class="iconfont icon-QuestionCircleOutlined icon"></i>
                  </el-tooltip>
                </template>
                <template slot-scope="scope">
                  <el-switch :active-value="1" :inactive-value="0" v-model="scope.row.appStatus" active-color="#2F54EB" @change="switchAppStatus(scope.row.appStatus, scope.row)"> </el-switch>
                </template>
              </el-table-column>
              <el-table-column label="创建人" min-width="110" prop="createUserName" v-if="[2,3].includes($store.state.departAuth) || $store.state.isSuperAdmin">
                <template slot-scope="{ row }">{{ row.createUserName || '--'}}</template>
              </el-table-column>
              <el-table-column prop="recentUpdateDate" min-width="100" label="到期时间">
                <template slot-scope="scope">
                  <template  v-if="!scope.row.isRealTime">
                    <p class="h-18">{{ scope.row.effectiveDate | formatTimeYMD }}</p>
                    <p class="h-18">{{ scope.row.effectiveDate | formatTimeHMS }}</p>
                  </template>
                  <template v-else>--</template>
                </template>
              </el-table-column>

              <el-table-column prop="updateTime" min-width="110" label="最近编辑时间">
                  <template slot-scope="scope">
                  <p class="h-18">{{ scope.row.updateTime ? dateformat(new Date(scope.row.updateTime), 'yyyy-MM-dd') : '--' }}</p>
                  <p class="h-18">{{ scope.row.updateTime ? dateformat(new Date(scope.row.updateTime), 'hh:mm:ss') : '--' }}</p>
                  </template>
              </el-table-column>

              <el-table-column prop="createTime" min-width="100" label="创建时间">
                <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 label="操作" width="230" fixed="right" v-if="setAuth">
                <template slot-scope="scope">
                  <router-link
                    :to="`/memberGroupDetail?memberTagGroupId=${scope.row.memberTagGroupId}&type=1`"
                    class="edit-btn el-button--text m-r-20"
                    :limit-code='$buttonCode.memberTagGroupDetail'
                    v-if='$getButtonLimit($buttonCode.memberTagGroupDetail)'
                  >
                    详情
                  </router-link>
                  <router-link
                    :limit-code='$buttonCode.memberTagEditGroup'
                    v-if="isAllowEdit(scope.row) && $getButtonLimit($buttonCode.memberTagEditGroup)"
                    :to="`/memberGroupEdit?memberTagGroupId=${scope.row.memberTagGroupId}`"
                    class="edit-btn el-button--text m-r-20"
                  >
                    编辑
                  </router-link>
                  <!-- scope.row.memberTagGroupId -->
                  <el-button type="text" @click="effectiveGroup(scope.row)"
                    v-if="$getButtonLimit($buttonCode.memberTagDeActiveGroup) && !scope.row.isRealTime && scope.row.effectiveStatus"
                    :limit-code='$buttonCode.memberTagDeActiveGroup'
                    class="edit-btn el-button--text m-r-20">
                    失效
                  </el-button>
                  <el-button type="text" @click="deleteGroup(scope.row)"
                    :limit-code='$buttonCode.memberTagDelGroup'
                    v-if="$getButtonLimit($buttonCode.memberTagDelGroup)"
                    style="margin-left: 0"
                    class="edit-btn el-button--text">
                    删除
                  </el-button>
                </template>
              </el-table-column>

            </el-table>
          </div>
          <div class="block common-wrap__page text-right" v-if="groupTableData.length != 0">
            <dm-pagination
              background
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="pageSize"
              layout="total, prev, pager, next"
              :total="total">
            </dm-pagination>
          </div>
        </div>

        <div class="right-box" v-show="isTagRecommend">
          <div class="common-wrap__opt flex-between">
            <div class="desc">覆盖人数于每日上午8点半进行更新</div>
            <div class="batch-option">
              <el-button type="primary" class="fr ghost-btn" @click="isNew = !isNew">{{ `查看${isNew ? '旧' : '新'}版金字塔会员分层` }}</el-button>
            </div>
          </div>
          <div class="common-wrap__table m-t-20">
            <pyramid-group-table v-show="isNew" />
            <el-table
              v-show="!isNew"
              v-loading="loading"
              ref="multipleTable"
              :data="groupTableData"
              tooltip-effect="dark"
              style="width: 99%"
              @selection-change="handleSelectionChange">
              <el-table-column label="分层名称" prop="groupName" min-width="130">
                <template slot-scope="scope">
                  <span>{{ scope.row.groupName }}</span>
                </template>
              </el-table-column>
              <el-table-column label="最近更新时间" prop="latestUpdateTime" min-width="100">
                <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="分类名称" prop="groupClassifyName" min-width="100">
                <template slot-scope="scope">
                  {{ scope.row.groupClassifyName || '--' }}
                </template>
              </el-table-column>
              <el-table-column prop="peopleCover" label="覆盖人数" show-overflow-tooltip min-width="100">
                <template slot="header">
                  覆盖人数
                  <el-popover width="260" trigger="hover">
                    <div style="color: #303133;">
                      默认显示上次页面缓存人数，可点击刷新按钮查看当页分组最新人数。
                    </div>
                    <i slot="reference" class="iconfont icon-zhongzhi refresh" @click="refershMember('tag')"></i>
                  </el-popover>
                </template>
                <template slot-scope="scope">
                  {{ (scope.row.memberCount || 0) | formatNum }}
                </template>
              </el-table-column>
              <!-- <el-table-column prop="appStatus" label="好办展示" min-width="100" :limit-code='$buttonCode.memberTagOpenHaoBan' v-if='$getButtonLimit($buttonCode.memberTagOpenHaoBan)'>
                <template slot="header">
                  好办展示
                  <el-tooltip effect="dark" content="开启后，默认次日更新至好办管理后台，如需立即更新，请至好办管理后台操作“同步”" placement="top">
                    <i class="iconfont icon-QuestionCircleOutlined icon"></i>
                  </el-tooltip>
                </template>
                <template slot-scope="scope">
                  <el-switch :active-value="1" :inactive-value="0" v-model="scope.row.appStatus" active-color="#2F54EB" @change="switchAppStatus(scope.row.appStatus, scope.row)"> </el-switch>
                </template>
              </el-table-column> -->
              <el-table-column label="分组描述" min-width="250">
                <template slot-scope="{ row }">
                  {{ row.groupName | aliasTips }}
                </template>
              </el-table-column>
              <!-- <el-table-column label="操作" width="100" fixed="right" v-if='$getButtonLimit($buttonCode.memberTagGroupLevelDetail)'>
                <template slot-scope="scope">
                  <router-link
                    :to="`/memberLevelDetail?memberTagGroupId=${scope.row.memberTagGroupId}&aliasName=${scope.row.groupName}`"
                    :limit-code='$buttonCode.memberTagGroupLevelDetail'
                    v-if='$getButtonLimit($buttonCode.memberTagGroupLevelDetail)'
                    class="edit-btn el-button--text p-r-12">
                    详情
                  </router-link>
                </template>
              </el-table-column> -->
            </el-table>
          </div>
          <div class="block common-wrap__page text-right" v-if="groupTableData.length != 0 && !isNew">
            <dm-pagination
              background
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="pageSize"
              layout="total, prev, pager, next"
              :total="total"
            >
            </dm-pagination>
          </div>
        </div>

        <div class="right-box recommend-box" v-show="isRecommend && !isTagRecommend">
          <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>
      </template>
    </div>
    <!-- <vue-gic-footer></vue-gic-footer> -->
    <batch-list :batchVisiable.sync="batchVisiable" @refresh-list="refreshList" :operateNumber="operateNumber" :multipleSelection="multipleSelection" @submit="getGroupList" @after-del="handleDelGroupMsg"></batch-list>

    <el-dialog title="提示" :visible.sync="dialogDelTips.show" width="480px">
      <div class="fixed-dialog">
        <i class="el-alert__icon el-icon-warning icon-fixed" />
        <div style="padding-left: 12px">
          <p>{{ dialogDelTips.isSingle ? '当前' : '存在' }}分组正在被以下模块使用，请先删除对应的内容后再来删除分组</p>
          <div v-if="dialogDelTips.isSingle" class="error-tips">
            <p v-for="i in dialogDelTips.list" :key="i.link">
              <a target="_blank" class="error-tip-link" :href="i.link">{{ i.name }}</a>
            </p>
          </div>
          <div v-else class="error-tips">
            <div class="error-tip-row" v-for="(row, k) in dialogDelTips.list" :key="k">
              <span class="label">{{ row.groupName }}：</span>
              <p v-for="i in row.list" :key="i.link">
                <a target="_blank" class="error-tip-link" :href="i.link">{{ i.name }}</a>
              </p>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

    <el-dialog title="固化分组分堆" :visible.sync="dialogFixedPile.show">
      <p class="pile-info">
        <span class="title">{{ dialogFixedPile.groupName }}</span>
        <span class="fixed-count" v-if="dialogFixedPile.memberCount !== null">固化人数 {{ dialogFixedPile.memberCount }} 人</span>
        <el-tooltip class="item" effect="dark" placement="top" v-else>
          <span slot="content">尚未达到期初固化时间的人群，不会展示分堆人数，但系统会保存您的分堆设置，当系统达到期初固化时间之后，刷新列表即可查看到分堆人数。</span>
          <span class="fixed-count">暂未到达期初固化时间</span>
        </el-tooltip>
        <span>{{ dialogFixedPile.beginTime }} - {{ dialogFixedPile.endTime }}</span>
      </p>
      <el-form>
        <el-form-item label="分堆设置：" label-width="85px">
          <el-radio-group v-model="dialogFixedPile.pileType">
            <el-radio v-for="i in dialogFixedPile.pileTypes" :key="i.value" :label="i.value">{{ i.label }}</el-radio>
          </el-radio-group>
          <div class="pile-detail">
            <el-form>
              <el-form-item label="分堆比例：" label-width="85px" v-if="dialogFixedPile.pileType != 4">
                <el-radio-group v-model="dialogFixedPile.proportion">
                  <el-radio v-for="i in dialogFixedPile.proportions" :key="i" :label="i">{{ i }}</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="分堆比例：" label-width="85px" v-else>
                <template v-for="(i, k) in dialogFixedPile.custom">
                  <span class="pile-proportions-divider" v-if="k" :key="k">:</span>
                  <el-input-number class="pile-proportions-input" :key="k" v-model="dialogFixedPile.custom[k]" :min="1" :max="100" controls-position="right"></el-input-number>
                </template>
                <el-button type="text" @click="pileCustomChange('add')" v-if="dialogFixedPile.custom.length < 5">添加</el-button>
                <el-button type="text" @click="pileCustomChange('del')" v-if="dialogFixedPile.custom.length > 1">删除</el-button>
              </el-form-item>
              <el-form-item class="pile-name-row" v-for="(i, k) in dialogFixedPile.groupNames" :key="k" label="分堆人群：" label-width="85px">
                <el-input class="pile-name-input" v-model="dialogFixedPile.groupNames[k]" :maxlength="15" show-word-limit placeholder="请输入分堆人群名称"></el-input>
              </el-form-item>
            </el-form>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <span class="pile-counts">
          实时计算：
          <span>{{ pileCounts }}</span>
        </span>
        <el-tooltip content="每个固化人群仅支持进行一次分堆设置，请确认操作" placement="top">
          <el-button type="primary" @click="savePile" v-loading="dialogFixedPile.loading">{{ dialogFixedPile.loading ? '人群分堆中' : '确认并创建分堆' }}</el-button>
        </el-tooltip>
      </div>
    </el-dialog>
    <delete-or-deactive-dialog :visible.sync="optionsDialog.visible" @submit="onConfirmDialog" :type="optionsDialog.type" :title="optionsDialog.title" :data="optionsDialog.data" />
  </div>
</template>
<script>
import BatchList from '@/components/tag/batch-list';
import errMsg from '@/common/js/error';
import timeFormat from '@/common/js/timeFormat';
import { getRequest } from '@/api/api';
import deleteOrDeactiveDialog from './delete-deactive-dialog.vue';
import {
  recommendList,
  recommendGroupList,
  findSecondMemberList,
  refershMemberCount,
  memberTagGroupList,
  memberGroupList,
  // updateGradeTag,
  // getTagLists,
  batchModifyEffective,
  batchDeleteGroup,
  groupCount,
  gradeList,
  batchDeleteGroupVerify,
  fixedGroupAddPile,
  searchRecordPreson
} from '@/request/api';
import GroupList from './group-list';
import RecommendTable from './recommend-table';
import { aliasNames } from '@/config'
import PyramidGroupTable from './pyramid-group-table.vue';
import { dateformat } from '@/utils/formatTime'

export default {
  name: 'memberGroupList',
  components: {
    GroupList,
    RecommendTable,
    BatchList,
    PyramidGroupTable,
    deleteOrDeactiveDialog
  },
  data() {
    return {
      fixedPile: {
        value: [
          { groupId: 1, currSize: 1, memberCount: 200, groupName: '分堆人群名称分堆人群名称' },
          { groupId: 2, currSize: 3, memberCount: 600, groupName: '分堆人群名称' },
          { groupId: 3, currSize: 1, memberCount: 200, groupName: '分堆人群名称' },
        ]
      },
      countGroupText: '',
      isRealTime: '',
      operateNumber: -1,
      batchVisiable: false,
      dialogVisible: true,
      isRecommend: false,
      isTagRecommend: false,
      showFixedList: false,
      recommendItems: [],
      recommendData: [], // 推荐分组的数据
      activeName: '',
      canEdit: false,
      // 面包屑参数
      navpath: [
        {
          name: '首页',
          path: `${window.location.origin}/report/#/memberSummary`,
          relocation: true
        },
        {
          name: '会员管理',
          path: ''
        },
        {
          name: '会员分组',
          path: ''
        }
      ],

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

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

      multipleSelection: [], // 表格的多选框批量操作

      // 分页参数
      currentPage: 1,
      pageSize: 20,
      total: 0,
      groupSetShow: false,
      loading: false,
      statusSelect: '',
      batchSelect: '',
      dialogDelTips: {
        show: false,
        isSingle: true,
        list: [],
      },
      reqLock: false,
      expandRowKeys: [],
      dialogFixedPile: {
        show: false,
        loading: false,
        memberCount: null,
        beginTime: '',
        endTime: '',
        groupName: '',
        memberTagGroupId: '',
        pileType: 1, // 1两组  2三组 3四组  4自定义
        proportion: '1:1',
        groupNames: [],
        pileTypes: [
          { value: 1, label: '两组' },
          { value: 2, label: '三组' },
          { value: 3, label: '四组' },
          { value: 4, label: '自定义' }
        ],
        proportions: ['1:1', '2:3'],
        pileNames: ['分堆a', '分堆b', '分堆c', '分堆d', '分堆e'],
        custom: [1, 1],
        isHaoban: ''
      },
      activeType: '1', // 切换一级tab
      isNew: true, // 是否新版金字塔分层
      isSelf: false, // 是否仅自己查看
      classifyOptions: {},
      optionsDialog: { // 删除和失效弹框
        visible: false,
        title: '',
        type: '',
        data: {},
        isBatch: false
      },
      addGroupDialog: false,
      dateformat,
      flag: false
    };
  },
  watch: {
    tagSearch(newval) {
      this.params.groupName = newval;
    },
    batchVisiable(newval) {
      if (!newval) {
        this.batchSelect = '';
      }
    },
    'dialogFixedPile.pileType'(v) {
      let proportions = {
        1: ['1:1', '2:3'],
        2: ['1:1:1', '1:3:1', '3:4:3'],
        3: ['1:1:1:1', '2:3:3:2', '1:4:4:1'],
      }[v] || [];
      let { groupName, pileNames, custom } = this.dialogFixedPile;
      let len = (proportions[0] || '').split(':').length || custom.length;
      let index = 0;
      let names = [];
      console.log(v);
      while(index < len) {
        names.push(`${groupName}-${pileNames[index]}`);
        ++index;
      }
      this.dialogFixedPile.proportions = proportions;
      this.dialogFixedPile.proportion = proportions[0] || '';
      if (v != 4) this.dialogFixedPile.groupNames = names;
    },
    // 该页面用keeyalive缓存 通过路由判断调用哪个列表接口
    '$route'(to,from) {
      if(to.path.indexOf('memberGroupList') > -1) {
        if(from.path.indexOf('memberLevelDetail') > -1) {
          this._gradeList(this.memberTagGradeId);
        } else {
          this.getGroupList();
          this._groupCount();
        }
      }
    },
    isSelf() {
      this.params.pageNum = 1;
      this.currentPage = 1;
      this.getGroupList();
    }
  },
  filters: {
    aliasTips(name) {
      let item = aliasNames.find(el => el.name === name);
      if (item) {
        return item.title;
      }
      return '';
    },
    formatTimeYMD(data) {
      return data && data != '- -' ? String(data).split(' ')[0] : '--';
    },
    formatTimeHMS(data) {
      return data && data != '- -' ? String(data).split(' ')[1] : '--';
    },
    formatNum(data) {
      const reg = /\d{1,3}(?=(\d{3})+$)/g;
      return (data + '').replace(reg, '$&,');
    },
    formatUpdateFrequency(rowData) {
      const { updateType, updateDay, isRealTime } = rowData;
      if (isRealTime === 1) {
        return '--'
      }
      switch (updateType) {
        case 1:
          return '每天一次';
        case 2:
          let weekArr = ['一', '二', '三', '四', '五', '六', '日'];
          return updateDay ? `每周${weekArr[updateDay - 1]}` : '每周一次';
        case 3:
          return updateDay ? `每月${updateDay}号` : '每月一次';
        default:
          return '--';
      }
    }
  },

  methods: {
    // 失效
    effectiveGroup(data, isBatch = false) {
      this.optionsDialog = {
        visible: true,
        title: '失效',
        type: 'deactive',
        isBatch,
        data
      };
    },
    handleEffective(data) {
      const param = {
        requestProject: 'gic-member-tag-web',
        memberTagGroupIds: data.memberTagGroupId,
        effectiveStatus: 0
      };
      batchModifyEffective(param)
        .then(res => {
          if (res.errorCode == 1) {
            this.$message.success({
              message: '修改成功'
            });
            this.getGroupList();
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    // 删除
    deleteGroup(data, isBatch = false) {
      this.optionsDialog = {
        visible: true,
        title: '删除',
        type: 'delete',
        isBatch,
        data
      };
    },
    handleDeleteGroup(data) {
      if(this.reqLock) return;
      const param = {
        requestProject: 'gic-member-tag-web',
        memberTagGroupIds: data.memberTagGroupId
      };
      this.reqLock = true
      batchDeleteGroup(param).then(res => {
        if (res.errorCode == 1) {
          (res.result || []).length || this.$message.success({
            message: '删除成功'
          });
          this.$refs.groupList.getMemberGroupList();
          this.getGroupList();
          this.handleDelGroupMsg(res.result);
        }
      }).finally(() => this.reqLock = false);
    },
    // 删除失效弹框确定
    onConfirmDialog(data, type) {
      type == 'deactive' ? this.handleEffective(data) : this.handleDeleteGroup(data);
    },
    handleDelGroupMsg(list) {
      if(!list || !list.length) return
      let map = list.reduce((res, el) => {
        res[el.groupName] || (res[el.groupName] = { groupName: el.groupName, list: [] })
        res[el.groupName].list.push({
          link: el.businessLink,
          name: `{${el.businessModuleName}-${el.businessName}}`
        })
        return res
      }, {})
      list = Object.values(map)
      let isSingle = list.length == 1
      isSingle && (list = list[0].list)
      this.$set(this, 'dialogDelTips', { show: true, isSingle, list })
    },
    getMemberGroupList() {
      memberGroupList({
        requestProject: 'gic-member-tag-web'
      }).then(res => {
        if (res.errorCode === 1) {
          this.options[2].children = res.result.filter(el => el.classifyName != '未分类');
        }
      });
    },
    refershMember(tag) {
      if (this.flag) return;
      this.flag = true;
      const msgVm = this.$message.warning('覆盖人数正在刷新中……');
      let Ids;
      const param = {
        requestProject: 'gic-member-tag-web'
      };
      if (tag) {
        // 分层
        Ids = this.groupTableData.map(el => el.memberTagGroupId).join(',');
        param.memberTagGroupIds = Ids;
      } else {
        Ids = this.groupTableData.map(el => el.memberTagGroupId).join(',');
        param.memberTagGroupIds = Ids;
      }
      if (tag) {
        refershMemberCount(param).then(res => {
          if (res.errorCode == 1) {
            this._gradeList(this.memberTagGradeId);
            msgVm.close();
            this.flag = false;
            this.$message.success({message: '更新成功'});
          }
        });
      } else {
        refershMemberCount(param).then(res => {
          if (res.errorCode == 1) {
            this.getGroupList();
            msgVm.close();
            this.flag = false;
            this.$message.success({message: '更新成功'});
          }
        });
      }
    },
    refreshList() {
      this.getGroupList();
    },
    // 分层数据
    _gradeList(id) {
      const params = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        memberTagGradeId: id
      };
      const flag = 3;
      gradeList(params).then(res => {
        if (res.errorCode == 1) {
          if (flag != this.activeType) return;
          this.total = res.result.totalCount;
          this.groupTableData = res.result.result;
          // 刷新覆盖人数
          this.refreshRecordPerson(this.groupTableData);
        }
      });
    },
    // 会员分组二级
    getsecondList(list) {
      this.currentPage = 1;
      this.params.pageNum = 1;
      this.showFixedList = false
      if(list === 'showFixedList') {
        this.params.memberTagGroupClassifyId = '';
        this.showFixedList = true;
        this.params.pageNum = 1;
        this.params.pageSize = 20;
        this.getGroupList(2);
        return;
      }
      if (list === 'allLevel') {
        this.isTag = true;
        this.isRecommend = true;
        this.isTagRecommend = true;
        this.memberTagGroupId = '';
        this.currentPage = 1;
        this.params.pageNum = 1;
        this.params.pageSize = 20;
        this.pageSize = 20;
        this._gradeList();
        return;
      }
      if (list === 'all') {
        this.params.memberTagGroupClassifyId = '';
        this.isRecommend = false;
        this.isTagRecommend = false;
        this.currentPage = 1;
        this.pageSize = 20;
        this.getGroupList(1);
        return;
      }
      if (list.isTag) {
        // 分层数据 需要传memberTagGradeId字段
        this.isTag = true;
        this.isRecommend = true;
        this.isTagRecommend = true;
        const { memberTagGradeId } = list.list;
        this.memberTagGradeId = memberTagGradeId;
        if (memberTagGradeId) {
          this._gradeList(memberTagGradeId);
        }
      } else if(list.isFixed) {
        this.showFixedList = true
        this.params.memberTagGroupClassifyId = list.list.memberTagGroupClassifyId;
        this.params.fixedType = 1;
        findSecondMemberList(this.params).then(res => {
          if (res.errorCode == 1) {
            this.total = res.result.totalCount;
            this.groupTableData = res.result.result.map(el => ({
              ...el,
              createTime: timeFormat.timeToDateTime(el.createTime),
            }));
          } else {
            this.groupTableData = [];
          }
          // 刷新覆盖人数
          this.refreshRecordPerson(this.groupTableData);
        })
      } else {
        this.isRecommend = false;
        this.isTag = false;
        this.isTagRecommend = false;

        this.params.memberTagGroupClassifyId = list.memberTagGroupClassifyId;
        this.params.fixedType = 0;
        findSecondMemberList(this.params).then(res => {
          if (res.errorCode == 1) {
            this.classifyOptions = res.result.params || {};
            this.total = res.result.totalCount;
            this.groupTableData = res.result.result.map(el => ({
              ...el,
              createTime: timeFormat.timeToDateTime(el.createTime),
            }));
          } else {
            this.groupTableData = [];
          }
          // 刷新覆盖人数
          this.refreshRecordPerson(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(val) {
      this.multipleSelection = val;
    },
    /**
     * 批量操作
     */
    handleFocus() {
      if (!this.multipleSelection.length) {
        this.batchSelect = '';
        this.$message.warning({
          message: '请先勾选分组',
          duration: 2000
        });
        return false;
      }
    },
    batchHandleSelect(val) {
      if (!this.multipleSelection.length) {
        this.batchSelect = '';
        this.$message.warning({
          message: '请先勾选分组',
          duration: 2000
        });
        return false;
      } else {
        this.operateNumber = val;
        this.batchVisiable = true;
      }
    },

    /**
     *
     */
    showGroupSet() {
      this.groupSetShow = true;
    },

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

    /**
     * 新增分组
     */
    toAddGroup(type) {
      this.changeRoute(`/memberGroupAdd?type=${type}`);
    },

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

    /**
     * 搜索分组
     */
    searchEnterFun(e) {
      this.currentPage = 1;
      this.params.pageNum = 1;
      this.getGroupList();
    },

    /**
     * 分页--- 一页多少条
     */
    handleSizeChange(val) {
      this.params.pageSize = val;
      this.pageSize = val;
      if (this.isTagRecommend) {
        this._gradeList(this.memberTagGradeId);
      } else {
        this.getGroupList();
      }
    },

    /**
     * 分页--- 当前第几页
     */
    handleCurrentChange(val) {
      // isTagRecommend 为真表示分层数据
      this.params.pageNum = val;
      this.currentPage = val;
      if (this.isTagRecommend) {
        this._gradeList(this.memberTagGradeId);
      } else {
        this.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) {
      const that = this;
      that.loading = true;
      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 => {
          obj.memberCount = res.data.result;
          that.loading = false;
        })
        .catch(e => {
          that.loading = false;
        });
    },

    /**
     * 简单更新当前分组 -- 失效/更改人数
     */
    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.params.pageNum = 1;
      this.currentPage = 1;
      this.params.effectiveStatus = val;
      this.getGroupList();
    },
    realTimeStatus(val) {
      this.params.pageNum = 1;
      this.currentPage = 1;
      this.params.isRealTime = val;
      this.getGroupList();
    },
    // 切换好办展示
    changeHaoBan(val) {
      this.params.pageNum = 1;
      this.currentPage = 1;
      this.params.appStatus = val;
      this.getGroupList();
    },
    /**
     * 获取列表数据
     */
    getGroupList(type) {
      this.loading = true;
      this.params.fixedType = this.showFixedList ? 1 : 0;
      this.params.permissionType = this.isSelf ? 2 : 1;
      const flag = type; // 用来控制快速切换tab时，数据混乱得问题
      memberTagGroupList(this.params).then(res => {
        this.loading = false;
        if (res.errorCode == 1) {
          if (flag && flag != this.activeType) return;
          this.total = res.result.totalCount;
          this.classifyOptions = res.result.params || {};
          this.groupTableData = res.result.result.map(el => ({
            ...el,
            latestUpdateTime: !!el.latestUpdateTime ? el.latestUpdateTime : '--',
            createTime: timeFormat.timeToDateTime(el.createTime),
          }));
          this.canEdit = (this.groupTableData[0] || {}).canEdit || false;
          // 刷新覆盖人数
          this.refreshRecordPerson(this.groupTableData);
        }
      }).catch(err => {
        this.loading = false;
        console.log(err);
      }).finally(() => this.loading = false);
    },
    // 非实时限制
    _groupCount() {
      groupCount().then(res => {
        if (res.errorCode == 1) {
          const data = res.result;
          this.countGroupText = `您的非实时分组数量已达${data.currCount}/${data.totalCount}，实时分组数量不受限制。`;
        }
      });
    },
    isAllowEdit(row) {
      const { latestUpdateTime, isRealTime, effectiveStatus } = row;
      if(!!isRealTime || (!latestUpdateTime || latestUpdateTime === '--')) return true;
      if (effectiveStatus == 0) return true; // 失效也可编辑
      let lastDate = (latestUpdateTime || '').split(' ')[0];
      let now = new Date().toLocaleDateString().replace(/(\d+)\/(\d+)\/(\d+)/, (match, p1, p2, p3) => {
        return [p1, p2.padStart(2, '0'), p3.padStart(2, '0')].join('-');
      });
      if (lastDate !== now) return false;
      return true;
    },
    onExpandChange(row, expandedRows) {
      let keys = expandedRows.map(i => i.memberTagGroupId);
      this.$set(this, 'expandRowKeys', keys);
    },
    handleFixedPile(row) {
      this.dialogFixedPile.groupName = row.groupName;
      this.dialogFixedPile.memberCount = row.memberCount;
      this.dialogFixedPile.memberTagGroupId = row.memberTagGroupId;
      this.dialogFixedPile.beginTime = (row.fixedTime || '').replace(' 00:00:00', '').replace(/\-/g, '.');
      this.dialogFixedPile.endTime = (row.effectiveDate || '').replace(' 00:00:00', '').replace(/\-/g, '.');
      this.dialogFixedPile.pileType = 1;
      this.dialogFixedPile.proportion = '1:1';
      this.dialogFixedPile.custom = [1, 1];
      this.dialogFixedPile.proportions = ['1:1', '2:3'];
      let names = this.dialogFixedPile.pileNames
      this.dialogFixedPile.groupNames = [`${row.groupName}-${names[0]}`, `${row.groupName}-${names[1]}`];
      this.dialogFixedPile.show = true;
    },
    // 创建分堆
    savePile() {
      let {
        memberTagGroupId,
        pileType,
        proportion,
        groupNames,
        custom,
        loading
      } = this.dialogFixedPile;
      if(loading) return;

      proportion = pileType == 4 ? custom.join(':') : proportion
      if(pileType == 4) {
        if(!custom.length || custom.some(i => !i)) return this.$message.warning('请添加分堆比例');
        proportion = custom.join(':');
      }
      if(groupNames.some(i => i === '')) return this.$message.warning('请输入分堆名称');

      let params = {
        requestProject: 'gic-web',
        memberTagGroupId,
        pileType,
        proportion,
        groupNames: groupNames.join(',')
      };
      this.dialogFixedPile.loading = true;
      fixedGroupAddPile(params).then(res => {
        if (res.errorCode == 1) {
          this.dialogFixedPile.show = false;
          findSecondMemberList(this.params).then(res => {
            if (res.errorCode == 1) {
              this.total = res.result.totalCount;
              this.groupTableData = res.result.result.map(el => ({
                ...el,
                createTime: timeFormat.timeToDateTime(el.createTime)
              }));
            } else {
              this.groupTableData = [];
            }
          })
        }
      }).finally(() => this.dialogFixedPile.loading = false);
    },
    pileCustomChange(type) {
      type == 'add' && this.dialogFixedPile.custom.push(1);
      type == 'del' && this.dialogFixedPile.custom.pop();
      let { groupName, pileNames } = this.dialogFixedPile;
      this.dialogFixedPile.groupNames = this.dialogFixedPile.custom.map((i, k) => {
        let name = this.dialogFixedPile.groupNames[k];
        name === undefined && (name = `${groupName}-${pileNames[k]}`)
        return name;
      });
    },
    handleDeleteFixedPile(row) {
      if (this.reqLock) return;
      this.reqLock = true;

      const { fixedPile, memberTagGroupId } = row;
      const { value } = fixedPile || {};
      let ids = (value || []).map(item => item.groupId);
      ids.unshift(memberTagGroupId);
      const param = {
        requestProject: 'gic-member-tag-web',
        memberTagGroupIds: ids.join(',')
      };

      batchDeleteGroupVerify(param).then(res => {
        if (res.errorCode != 1) return;
        if ((res.result || []).length) return this.handleDelGroupMsg(res.result);

        let html = !fixedPile
          ? '<span>确认删除此固化人群？</span>'
          : '<div><i class="el-icon-warning" style="font-size:25px;margin-right:15px;color:#e6a23c"></i>确认删除以下分堆人群？</div>';
        value && value.forEach(item => {
          html += `
            <div style="color:#909399;padding-top:10px">
              <i class="iconfont icon-xuanze-" style="padding-left:40px"></i>
              <span>${item.groupName}</span>
            </div>
          `
        });

        this.$confirm(html, '提示', {
          dangerouslyUseHTMLString: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: !fixedPile ? 'warning' : ''
        }).then(() => {
          batchDeleteGroup(param).then(res => {
            if (res.errorCode == 1) {
              (res.result || []).length || this.$message.success({
                message: '删除成功'
              });
              this.$refs.groupList.getFixedMemberGroupList();
              this.getGroupList();
              this.handleDelGroupMsg(res.result);
            }
          });
        })
      }).finally(() => this.reqLock = false);
    },
    onTabClick() {
      this.pageSize = 20;
      this.params.pageSize = 20;
      this.currentPage = 1;
      this.params.pageNum = 1;
    },
    refreshRecordPerson(arr) {
      // 刷新覆盖人数
      arr.forEach(async el => {
        const { result } = await searchRecordPreson({ groupIds: el.memberTagGroupId });
        el.memberCount = result;
      })
    }
  },
  created() {
    this.loading = true;
    this.params = {
      groupName: this.tagSearch,
      pageSize: 20,
      pageNum: 1,
      isRealTime: '',
      effectiveStatus: this.statusSelect,
      requestProject: 'gic-member-tag-web',
      memberTagGroupClassifyId: '',
      fixedType: 0
    };
    if (this.$route.query.type != 'fixed') {
      this.getGroupList();
    }
    this._groupCount();
  },
  mounted() {
    if (this.$route.query.type == 'fixed') {
      this.loading = true;
      this.$nextTick(() => {
        this.$refs.fixedGroup.$el.querySelector('#tab-2').click();
      })
    }
  },
  computed: {
    pileCounts() {
      let info = this.dialogFixedPile;
      if(!info.show) return '';
      let nums = info.pileType == 4 ? info.custom : info.proportion.split(':');
      let sum = nums.reduce((sum, el) => sum + +el, 0);
      let part = Math.ceil(info.memberCount / sum);
      return nums.reduce((res, el, k) => {
        let val = el * part;
        if(k == nums.length - 1) {
          val = info.memberCount - res.reduce((sum, i) => sum + +i, 0)
        }
        res.push(val);
        return res;
      }, []).join(':');
    },
    setAuth() {
      return this.$getButtonLimit(this.$buttonCode.memberTagGroupDetail) || this.$getButtonLimit(this.$buttonCode.memberTagEditGroup) || this.$getButtonLimit(this.$buttonCode.memberTagDeActiveGroup) || this.$getButtonLimit(this.$buttonCode.memberTagDelGroup);
    }
  },
};
</script>
<style lang="scss">
.member-group {
  position: relative;
  height: calc(100% - 12px);
  overflow: hidden;
}
.icon {
  font-size: 14px !important;
  color: #606266;
}
.tips {
  color: #606266;
  font-size: 12px;
}
.common-wrap__opt {
  &.flex-between {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  font-size: 0;
  .m-r-8 {
    margin-right: 8px;
  }
  .desc {
    font-size: 12px;
    width: 270px;
    color: #606266;
  }
  .top {
    font-size: 14px;
  }
  .title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    h2 {
      font-weight: bold;
      color: #303133;
      line-height: 22px;
      font-size: 16px;
    }
    .count {
      color: #303133;
      font-size: 12px;
    }
  }
}
.btn-foled-all{
  float: right;
}
.h-18 {
  font-size: 14px;
  height: 18px;
  line-height: 18px;
}
.right-content {
  display: flex;
  justify-content: flex-start;
  align-items: stretch;
  height: 100%;
  .left-box {
    height: 100%;
    flex-shrink: 0;
    width: 220px;
    position: relative;
    padding-top: 10px;
    background-color: #fff;
    border-right: 1px solid rgba(220,223,230,1);
  }
  .right-box {
    width: 100%;
    flex: 1;
    overflow-y: scroll;
    padding-bottom: 10px;
    height: calc(100% - 20px);
    .batch-option {
      float: right;
      display: flex;
      .fr {
        margin-left: 10px;
      }
      .fl {
        margin-right: 10px;
      }
    }
    .look-self {
      display: inline-block;
      margin-top: 10px;
      i {
        font-size: 14px;
        margin-left: 5px;
      }
    }
    .refresh {
      color: #909399;
      cursor: pointer;
      &:hover {
        color: #2F54EB;
      }
    }
  }
}
.error-tips{
  margin: 20px 0;
  > p{
    margin: 0 0 15px 0;
  }
  .error-tip-link{
    color: #2F54EB;
  }
  .error-tip-row{
    margin: 0 0 15px 0;
    padding: 0 0 0 150px;
    position: relative;
    .label{
      position: absolute;
      top: 0;
      left: 0;
      text-align: right;
      width: 150px;
    }
    p{
      margin: 0 0 10px 0;
    }
  }
}
.fixed-pile{
  display: flex;
  .pile-label{
    flex-grow: 0;
    flex-shrink: 0;
    margin: 0 30px 0 10px;
    div{
      color: #303133;
      font-weight: 600;
      height: 40px;
      line-height: 40px;
    }
  }
  .pile-divider{
    flex-grow: 0;
    flex-shrink: 0;
    margin: 0 35px;
    div{
      text-align: center;
      color: #303133;
      font-weight: 600;
      font-size: 24px;
      height: 40px;
      line-height: 40px;
    }
  }
  .pile-col{
    div{
      text-align: center;
      color: #606266;
      height: 40px;
      line-height: 40px;
    }
    .curr-size{
      font-weight: 600;
      font-size: 24px;
      color: #303133;
    }
  }
}
.pile-info{
  line-height: 20px;
  margin: 0 0 23px 0;
  color: #303133;
  .title{
    font-size: 16px;
    font-weight: 600;
    margin-right: 20px;
  }
  .fixed-count{
    margin: 0 32px 0 0;
  }
}
.pile-detail{
  background: #F5F7FA;
  padding: 12px 20px;
  .pile-proportions-divider{
    margin: 0 5px 0 10px;
  }
  .pile-proportions-input{
    width: 90px;
    &:last-of-type{
      margin: 0 10px 0 0;
    }
  }
  .pile-name-input{
    width: 249px;
  }
  .pile-name-row{
    margin: 20px 0 0 0;
  }
}
.pile-counts{
  color: #303133;
  margin: 0 20px 0 0;
  font-size: 14px;
  span{
    font-size: 16px;
  }
}
.hide-expand /deep/ .el-table__expand-column .cell{
  height: 0 !important;
  overflow: hidden;
}
.tabs .el-tabs__nav-wrap::after {
  display: none;
}
.tabs .el-tabs__header {
  margin-bottom: 0;
}
.w160 {
  width: 160px;
}
.w120 {
  width: 120px;
}
.w130 {
  width: 130px;
}
.real-time, .no-real-time {
  display: inline-block;
  width: 44px;
  height: 18px;
  border-radius: 2px;
  text-align: center;
  line-height: 18px;
  font-size: 12px;
}
.no-real-time {
  background: #FEECDA;
  color: #FA8C16;
}
.real-time {
  background: #DEE3FC;
  color: #2f54eb;
}
</style>
<style lang="scss" scoped>
 .flex {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  border-bottom: 1px solid #e4e7ed;
}
.add-group {
  width: 100%;
  margin-top: 12px;
}
.icon-fixed {
  font-size: 21px;
  position: relative;
  top: -4px;
  display: inline-block;
  color: #fa8c16;
}
.fixed-dialog {
  display: flex;
  align-items: flex-start;
}
.add-category {
  margin: 0 20px;
}
</style>
