<template>
  <div class="member-tag">
    <div class="tag-container">
      <div class="member-box">
        <div class="flex">
          <el-tabs v-model="activeTag" @tab-click="handleClick">
            <el-tab-pane label="系统标签" name="system" v-if="isShowSystem"></el-tab-pane>
            <el-tab-pane label="手工标签" name="manual" ref="manualTab"></el-tab-pane>
            <el-tab-pane label="活动标签" name="active"></el-tab-pane>
          </el-tabs>
          <a href="https://www.yuque.com/exnmlu/hpbb1c/cz27hs" target="_blank" class="help-doc">查看帮助文档</a>
        </div>
        <div class="main-tag">
          <div class="tag-list">
            <div class="list-box" style="padding-bottom: 40px">
              <TagType v-for="(list, i) in setCurrentTagList" :active-tag="activeTag" :key="i" :tag-list="list" @handleFristTag="handleFristTag"> </TagType>
            </div>
          </div>

          <div class="tag-all">
            <p class="tag-name">
              <span class="sub-title"></span>
              <el-button
                type="primary"
                class="add-newtag"
                @click="editHandTag()"
                v-show="(handTag == 1 && !weimId.includes(groupId || params.id) || handTag == 2) && $getButtonLimit($buttonCode.memberTagAddTag)"
                :limit-code="$buttonCode.memberTagAddTag"
                >新增标签</el-button
              >
              <el-button
                type="primary"
                class="add-newtag"
                @click="$router.push('/syncTagHistory')"
                v-if="handTag == 1 && !isSync && $getButtonLimit($buttonCode.memberTagSyncTag)"
                :limit-code="$buttonCode.memberTagSyncTag"
                >同步标签</el-button
              >
              <el-input
                class="add-newtag"
                placeholder="请输入标签名称"
                prefix-icon="el-icon-search"
                style="width: 260px;float: left;margin-left: 0"
                v-model="memberTag"
                @keyup.native.enter="searchMemberList"
                @blur="searchMemberList"
                @clear="allTagList"
                clearable
              ></el-input>
            </p>
            <p class="tips" v-if="tagName == '金字塔会员分层' && !memberTagGradeEnsure">暂未开通金字塔分层功能，无法使用该标签，可以联系达摩项目经理进行开通！</p>

            <tag-container-manual
              v-show="activeTag == 'manual'"
              @setGroupId="setGroupId"
              @peopleHandTag="peopleHandTag"
              @deleteHandTag="deleteHandTag"
              :data="memberTagList"
              :groupId="groupId"
              :refersh="refershList"
              @addTag="selectedTag"
              @editHandTag="editHandTag"
              ref="tagContainer"
              :isWeim="weimId.includes(groupId || params.id)"
              @change="searchMemberList"
              @remote-sort="remoteSort"
            />
            <tag-container-system v-show="activeTag == 'system'" :data="memberTagList" :refersh="refershList" @addTag="selectedTag" @change="searchMemberList" />
            <tag-container-active v-show="activeTag == 'active'" :data="memberTagList" :refersh="refershList" @addTag="selectedTag" @change="searchMemberList" @ediActiveTag="editHandTag" @deleteHandTag="deleteHandTag" />

            <div class="page-box" v-if="total > 0">
              <dm-pagination
                background
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="pageNum"
                :page-sizes="[20, 30]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next"
                :total="total"
              ></dm-pagination>
            </div>

            <!-- 我的标签 -->
            <div class="my-pop-tagbox" @click="expendsGroupList" :limit-code="$buttonCode.memberTagCreateGroup" v-if="$getButtonLimit($buttonCode.memberTagCreateGroup)">
              <p class="txt">
                <el-badge v-if="groupListNumber != 0" :value="groupListNumber">
                  <i class="iconfont icon-biaoqian" style="margin-bottom:2px"></i>
                </el-badge>
                <i v-else class="iconfont icon-biaoqian" style="margin-bottom:2px" />
                <span>已选标签</span>
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="group-right-list" :class="{ 'group-transtion-list': groupShow }">
      <div class="group-title">
        <span class="label">已选标签 ({{ groupListNumber }})</span>
        <i class="el-icon-close icon-right" @click="groupShow = false" />
      </div>
      <div class="group-tips">
        <span class="desc">一个标签框内标签之间的关系为且，可添加多个标签框，多个标签框之间可切换“或者”/“剔除”</span>
      </div>
      <div class="wapper">
        <div class="inner">
          <tags-group-list
            :selectedTagsData="selectedTags"
            :tagsGroupRelation="tagsGroupRelation"
            @editTags="editTags"
            :activeTagsGroupIndex.sync="activeTagsGroupIndex"
            :activeTagIndex.sync="activeTagIndex"
          />
          <div class="form-item">
            <label for="">分组名称</label>
            <el-input v-model="tagConfig.groupName" :maxlength="10" placeholder="请输入分组名称" show-word-limit></el-input>
          </div>
          <div class="form-item" v-show="!tagConfig.isRealTime">
            <label for="">
              分组有效期至
              <el-tooltip content="分组有效期需早于所用标签的最早有效期，且最长不超过730天">
                <i class="iconfont icon-QuestionCircleOutlined m-l-4 tip-icon"></i>
              </el-tooltip>
            </label>
            <el-date-picker
              :clearable="false"
              v-model="tagConfig.date"
              :picker-options="pickerOptions"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="date"
              placeholder="选择日期"
              style="width: 100%"
            >
            </el-date-picker>
          </div>
          <div :class="['form-item']">
            <label for="">分组所属分类</label>
            <el-select v-model="tagConfig.memberTagGroupClassifyId" v-loadmore="onLoadmore" style="width: 100%" filterable placeholder="请选择">
              <el-option v-for="item in memberGroupList" :key="item.memberTagGroupClassifyId" :value="item.memberTagGroupClassifyId" :label="item.classifyName" />
            </el-select>
          </div>
          <div :class="['form-item']">
            <label for="" class="m-b-15">是否固化<el-link class="m-l-16" type="primary" :underline="false" target="_blank" href="https://www.yuque.com/exnmlu/hpbb1c/ke8o0d">什么是固化？</el-link></label>
            <el-radio-group v-model="tagConfig.fixedType" class="radio-group">
              <el-radio :label="0" class="m-b-0">否</el-radio>
              <el-radio :label="2" class="m-b-0">是</el-radio>
            </el-radio-group>
          </div>
          <div :class="['form-item', 'm-t-10']" v-if="tagConfig.fixedType">
            <label for="">固化生效时间</label>
            <el-date-picker
              :clearable="false"
              :picker-options="tagConfig.isRealTime ? realTimeOptions : fixedTimeOptions"
              v-model="tagConfig.fixedTime"
              value-format="yyyy-MM-dd"
              placeholder="选择日期"
              style="width: 100%"
            ></el-date-picker>
          </div>
          <div :class="['form-item']" v-if="tagConfig.fixedType">
            <label for="" class="m-b-15">是否同时生成非固化分组</label>
            <el-radio-group v-model="tagConfig.isTogether" class="radio-group">
              <el-radio :label="false" class="m-b-0">否</el-radio>
              <el-radio :label="true" class="m-b-0">是</el-radio>
            </el-radio-group>
          </div>
          <div class="form-item">
            <label for="">更新频次<span class="desc-labeltxt">{{ updateTypeDesc() }}</span></label>
            <el-select v-model="tagConfig.updateType" placeholder="请选择" disabled>
              <el-option v-for="(item, index) in rateData" :key="item.label" :label="item.label" :value="index + 1"></el-option>
            </el-select>
          </div>
          <div class="form-item">
            <label for="">分组描述</label>
            <el-input type="textarea" v-model="tagConfig.textarea" show-word-limit :maxlength="100" rows="4" resize="none" placeholder="请输入分组描述，最多100字"></el-input>
          </div>
          <p class="tips-count" v-show="!(tagConfig.fixedType && !tagConfig.isTogether) && tagConfig.isRealTime == 0 && realCount.totalCount <= realCount.currCount">
            您的非实时会员分组数量已达上限{{ realCount.totalCount }}，建议您删除或失效部分非实时会员分组！
          </p>
        </div>
      </div>
      <div class="fixed-btn">
        <!-- 当前人数大于总人数 -->
        <el-button type="primary" @click="createNewGroup" :disabled="!(tagConfig.fixedType && !tagConfig.isTogether) && tagConfig.isRealTime == 0 && realCount.totalCount <= realCount.currCount">创建会员分组</el-button>
      </div>
    </div>
    <edit-tag :showEditTagPop.sync="showEditTagPop" :tagData="tagData" :title="editPopType === 'add' ? '添加标签' : '更新标签'" @returnTagData="returnTagData" @refersh="refersh"></edit-tag>
     <dm-memberTag-val :options="manualTagPop" :current-type="activeTag" :showPop.sync="manualTagPop.show" @save="addNewTag"></dm-memberTag-val>
    <!-- <manual-tag-edit :options="manualTagPop" :current-type="activeTag" :showPop.sync="manualTagPop.show" @save="addNewTag"></manual-tag-edit> -->
    <Trash />
  </div>
</template>

<script>
import Vue from 'vue';
import { CollapseTransition } from 'element-ui';
import TagsGroupList from '../memberGroup/tags-group-list';
import TagType from './tag-type';
import TagContainer from './tag-container';
import TagContainerSystem from './tag-container-system';
import TagContainerActive from './tag-container-active';
// import ManualTagEdit from '../manualTag/manualTagEdit';
import { getMemberTag, getMemberTagList, addNewGroup, memberGroupList, groupCount, getMemberTagGradeEnsure, isAutomaticSync, isShowSystemTag } from '@/request/api';
import EditTag from '../memberGroup/edit-tag';
import Trash from '@/components/Trash.vue';
import { parseTime } from '@/utils';
import { dateformat } from '@/utils/formatTime';
Vue.component(CollapseTransition.name, CollapseTransition);
let fixBeginTime = +new Date() + 1000 * 60 * 60 * 24;

const shortTimeFn = (text, day, type) => {
  return {
    text,
    onClick(picker) {
      let curDate = new Date();
      if (type == 'day') {
        curDate.setDate(day + curDate.getDate());
      } else {
        curDate.setMonth(day + curDate.getMonth());
        curDate = new Date(+new Date(curDate) - 24 * 60 * 60 * 1000);
      }
      picker.$emit('pick', curDate);
    }
  }
}
export default {
  name: 'member-tag',

  componentName: 'member-tag',

  components: {
    TagType,
    TagContainerManual: TagContainer,
    TagsGroupList,
    EditTag,
    // ManualTagEdit,
    Trash,
    TagContainerSystem,
    TagContainerActive
  },

  data() {
    return {
      pager: {
        pageNum: 1,
        total: 1
      },
      handTag: null,
      realCount: Object.create(null),
      margin60: false,
      refershList: {},
      tagConfig: {
        groupName: '',
        // 会员分组分类id
        memberTagGroupClassifyId: '0',
        textarea: '', // 描述
        date: '', // 有效期
        updateType: '', // 更新类型频率
        updateDay: '', // 更新类型时间
        isRealTime: 0, // 实时
        effectiveStatus: 1, // 有效状态nage
        fixedType: 0, // 是否固化人群
        fixedTime: parseTime(new Date().setHours(24,0,0,0), '{y}-{m}-{d}'), // 期初固化时间
        isTogether: false
      },
      activeTagsGroupIndex: 0,
      activeTagIndex: 0,
      groupShow: false,
      selectedTags: [[]],
      tagsGroupRelation: [],
      pickerOptions: {
        disabledDate(time) {
          let curDate = new Date().getTime();
          let twoYears = 2 * 365 * 24 * 3600 * 1000;
          let y = curDate + twoYears;
          return time.getTime() < Date.now() - 8.64e7 || time.getTime() > y;
        },
        shortcuts: [
          shortTimeFn('一天', 0, 'day'),
          shortTimeFn('一周', 6, 'day'),
          shortTimeFn('一个月', 1, 'month'),
          shortTimeFn('三个月', 3, 'month'),
          shortTimeFn('六个月', 6, 'month'),
        ]
      },
      fixedTimeOptions: {
        disabledDate: (date)=> {
          let begin = new Date().setHours(24,0,0,0);
          let end = new Date(this.tagConfig.date).getTime();
          return date.getTime() < begin || date.getTime() > end ;
        }
      },
      realTimeOptions: {
        disabledDate: date => {
          return date.getTime() < +new Date()
        }
      },
      // 面包屑参数
      navpath: [
        {
          name: '首页',
          path: `${window.location.origin}/report/#/memberSummary`,
          relocation: true
        },
        {
          name: '客户管理',
          path: ''
        },
        {
          name: '客户标签',
          path: ''
        }
      ],
      tagList: [],
      memberTagList: [], // 会员标签列表
      tagName: '全部系统标签',
      memberTag: '', // 搜索会员标签关键字
      showSearchResult: false, // tagName后面加“搜索结果”
      tagCategory: '', // 当前标签类别
      pageSize: 20,
      pageNum: 1,
      total: 0,

      // 分组分类
      memberGroupList: [],
      // 更新频率
      rateData: [
        {
          label: '实时更新',
          value: 1
        },
        {
          label: '每日一次',
          value: 2
        },
        {
          label: '生效后更新一次',
          value: 3
        },
        {
          label: '生效后更新一次',
          value: 4
        },
      ],

      showEditTagPop: false,
      tagData: {},
      editPopType: 'add',
      manualTagPop: {
        show: false,
        popTitle: '',
        // popTitle: '编辑手工标签',
        // tagId: '6285cee7e2e14dddae3e2322c6ef6089'
        tagId: '',
        tagLevelGroupId: '',
        tagTwoLevelGroupId: '',
        isSync: false
      },
      memberTagGradeEnsure: true, // 是否开启会员分层
      weimId: ['3d11ac15963b4c0790762e6147ea9315', '5bdac971673b4f40a9af981e3c9215bf'],
      isSync: false, // 是否开启自动同步开关
      activeTag: 'system',
      manualOrderBy: -1,
      isShowSystem: true
    };
  },
  computed: {
    groupListNumber() {
      let listNumber = 0;
      let index = 0;
      while (index < this.selectedTags.length) {
        listNumber += this.selectedTags[index].length;
        index++;
      }
      this.checkRealTime();
      return listNumber;
    },
    marginSixty() {
      return this.selectedTags.length > 1;
    },
    setCurrentTagList() {
      const { activeTag } = this;
      const travel = arr => {
        arr.forEach(el => {
          if (el.children) {
            travel(el.children);
          } else {
            el.children = [];
          }
        });
      };
      if (activeTag == 'manual') {
        const arr = this.tagList.filter(el => el['handTag'] === 1);
        travel(arr);
        return arr;
      } else if (activeTag == 'active') {
        const arr = this.tagList.filter(el => el['handTag'] === 2);
        travel(arr);
        return arr;
      } else {
        return this.tagList.filter(el => {
          return el['handTag'] === 0;
        });
      }
    }
  },
  directives: {
    loadmore: {
      inserted(el, binding) {
        const SELECTDOWN_DOM = el.querySelector('.el-select-dropdown .el-select-dropdown__wrap');
        SELECTDOWN_DOM.addEventListener('scroll', function() {
          const CONDITION = this.scrollHeight - this.scrollTop <= this.clientHeight;
          if (CONDITION) {
            binding.value();
          }
        })
      }
    }
  },

  methods: {
    validPeriodDateChange(v) {
      this.tagConfig.fixedTime = parseTime(fixBeginTime);
    },
    getMemberTagGradeEnsure() {
      getMemberTagGradeEnsure({ requestProject: 'gic-member-tag-web' }).then(res => (this.memberTagGradeEnsure = res.result));
    },
    _groupCount() {
      groupCount().then(res => {
        if (res.errorCode == 0) {
          this.realCount = res.result;
        }
      });
    },
    // 设置默认的分组有效期
    defaultDate() {
      let curDate = new Date();
      curDate.setMonth(3 + curDate.getMonth());
      curDate = new Date(+new Date(curDate) - 24 * 60 * 60 * 1000);
      this.tagConfig.date = dateformat(curDate, 'yyyy-MM-dd') + ' 23:59:59';
    },
    // 刷新
    refersh(list) {
      list.changeRefersh = true;
      this.refershList = list;
    },
    allTagList() {
      localStorage.setItem('groupId', '');
      this.params.id = '';
      this.params.type = -1;
      this.loadMemberTagList(this.params);
      this.tagName = this.activeTag == 'manual' ? '全部手工标签' : this.activeTag == 'active' ? '全部活动标签' : '全部系统标签';
      // this.handTag = null;
      this.pageNum = 1;
      this.$store.commit('modiftTagName', '我的用户');
    },
    checkRealTime() {
      let arr = this.selectedTags.reduce((curr, el) => {
        return curr.concat(el);
      }, []);
      let newActiveArr = arr.map(el => el.isActive);
      // 0 非实时 1 实时
      this.tagConfig.isRealTime = newActiveArr.indexOf(0) > -1 ? 0 : 1;
    },

    createNewGroup() {
      this.selectedTags.forEach((tagsGroup, tagsGroupIndex) => {
        let relation = this.tagsGroupRelation[tagsGroupIndex - 1];
        tagsGroup.forEach(item => {
          item.levelType = relation ? relation : 'or';
        });
      });
      const curFixedType = this.tagConfig.fixedType ? this.tagConfig.isTogether ? 2 : 1 : 0;
      const param = {
        groupName: this.tagConfig.groupName,
        memberTagGroupClassifyId: this.tagConfig.memberTagGroupClassifyId,
        isRealTime: this.tagConfig.isRealTime,
        describle: this.tagConfig.textarea,
        updateType: this.tagConfig.updateType,
        updateDay: this.tagConfig.updateDay,
        effectiveStatus: 1,
        requestProject: 'gic-member-tag-web',
        json: JSON.stringify(this.selectedTags),
        effectiveDateTmp: `${this.tagConfig.date.split(' ')[0]} 23:59:59`,
        fixedType: curFixedType
      };
      // 必填项目
      const isEmpty = this.selectedTags.length === 0 || this.selectedTags.some(item => item.length === 0);
      if (isEmpty) {
        this.$message.warning({ message: '请至少保留一个标签！' });
        return;
      }
      if (param.groupName == '') {
        this.$message.warning({ message: '会员分组名称不能为空！' });
        return;
      }

      if (param.effectiveDateTmp == '') {
        this.$message.warning({ message: '会员分组有效期不能为空！' });
        return;
      }

      // if (param.isRealTime === 0 && param.updateType !== 1 && param.updateDay === '') {
      //   this.$message.warning({ message: '会员分组更新频率不能为空！' });
      //   return;
      // }

      if (!this.tagConfig.isRealTime && param.fixedType && new Date(this.tagConfig.fixedTime).setHours(0,0,0,0) > new Date(this.tagConfig.date).setHours(0,0,0,0)) {
        this.$message.error({ message: '固化生效时间不能晚于分组有效期' });
        return false;
      }

      if (param.fixedType) {
        param.fixedTime = this.tagConfig.fixedTime;
      }

      addNewGroup(param)
        .then(res => {
          if (res.errorCode == 0) {
            console.log(this.tagConfig.fixedType);
            const type = this.tagConfig.fixedType ? 'fixed' : '';
            this.$router.push({ path: 'memberGroupList', query: { type } });
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    expendsGroupList() {
      // if (this.selectedTags && this.selectedTags.length) {
      this.groupShow = true;
      // }
    },
    returnTagData(tagData) {
      let tagParams = JSON.parse(tagData.tagParams);
      tagData.newTagVal = JSON.stringify(tagParams.selectedVal);
      tagData.level = this.activeTagsGroupIndex;
      switch (this.editPopType) {
        case 'add':
          const isHad = this.selectedTags[this.activeTagsGroupIndex].some(item => item.tagId === tagData.tagId);
          if (isHad) {
            this.selectedTags[this.activeTagsGroupIndex].forEach((tag, tagIndex) => {
              if (tag.tagId === tagData.tagId) {
                this.selectedTags[this.activeTagsGroupIndex].splice(tagIndex, 1, tagData);
              }
            });
          } else {
            this.selectedTags[this.activeTagsGroupIndex].push(tagData);
          }
          break;
        case 'edit':
          // 注意有坑
          let tagsGroup = this.selectedTags[this.activeTagsGroupIndex];
          tagsGroup.splice(this.activeTagIndex, 1, { ...tagsGroup[this.activeTagIndex], ...tagData });
          this.selectedTags.splice(this.activeTagsGroupIndex, 1, tagsGroup);
          break;
      }
    },
    editTags() {
      this.editPopType = 'edit';
      this.showEditTagPop = true;
      this.$nextTick(_ => {
        this.tagData = Object.assign({}, this.tagData, this.selectedTags[this.activeTagsGroupIndex][this.activeTagIndex]);
        this.tagData.editCondition = true;
      });
    },
    // 新增选择标签
    selectedTag(tagData) {
      this.editPopType = 'add';
      this.tagData = Object.assign({}, this.tagData, tagData);
      this.tagData.editCondition = false;
      this.showEditTagPop = true;
    },
    // 新增第三级手工标签
    editHandTag(list) {
      console.log(list);
      /**
       * 第一级标签切换时，重置manualTagPop.tagTwoLevelGroupId和manualTagPop.tagLevelGroupId为空
       * 第二级标签切换时，修改manualTagPop.tagTwoLevelGroupId为当前第二级标签的tagLevelGroupId，重置manualTagPop.tagLevelGroupId为空
       * 第三级标签切换时，修改manualTagPop。tagLevelGroupId为当前第三级标签的tagLevelGroupId，修改manualTagPop.tagTwoLevelGroupId为parentLevelGroupId
       *
       * 编辑三级手工标签，修改manualTagPop.tagId为list.tagId
       * 新增三级手工标签，重置manualTagPop.tagId为空
       *
       * 然后将manualTagPop传递给manualTagEdit组件
       * */
      let popTitle = '';
      if (this.activeTag == 'active') popTitle = list ? '编辑活动标签' : '新增活动标签';
      else if (this.activeTag == 'manual') {
        popTitle = list ? '编辑手工标签' : '新增手工标签';
      }
      this.manualTagPop.tagId = list ? list.tagId : '';
      this.manualTagPop.popTitle = popTitle;
      this.manualTagPop.show = true;
    },
    async getTagList() {
      const Data = await getMemberTag();
      if (Data.result && Data.result.length) {
        this.tagList = Data.result;
      } else {
        this.tagList = [];
      }
    },

    async loadMemberTagList(opt) {
      const tagType =  this.activeTag == 'active' ? '2' : this.activeTag == 'manual' ? '1' : '0';
      try {
        const params = {
          requestProject: 'gic-member-tag-web',
          search: opt.searchName || null, // 标签名
          tagLevelGroupId: opt.id || '', // 标签层级
          tagType, // 标签类型
          showMemberCount: 1, // 覆盖人数
          pageNum: opt.pageNum || 1,
          pageSize: opt.pageSize || 20,
          orderType: this.activeTag == 'manual' ? this.manualOrderBy : -1
        };
        const Data = await getMemberTagList(params);
        this.showSearchResult = !!opt.showSearchResult;
        if (Data.result.result && Data.result.result.length) {
          this.memberTagList = Data.result.result.map(el => ({
            ...el,
            refersh: false,
            numRool: true,
            oldSort: el.sort
          }));
          this.total = Data.result.totalCount;
          localStorage.setItem('groupId', '');
        } else {
          this.memberTagList = [];
          this.total = 0;
        }
      } catch (e) {
        // console.log(e);
      }
    },

    // 每页条数改变
    handleSizeChange(val) {
      this.pageSize = val;
      this.params.pageSize = val;
      // const param = this.JudgeIsHandTag();
      this.loadMemberTagList(this.params);
    },
    // 当前页码改变
    handleCurrentChange(val) {
      this.params.pageNum = val;
      this.pageNum = val;
      this.loadMemberTagList(this.params);
    },
    /**
     * 判断是否是手工标签
     */
    JudgeIsHandTag() {
      let param = null;
      let keys = Object.keys(this.middleWareVariable);
      // 长度大于0就表示 有手工标签的值
      if (keys.length) {
        param = {
          id: this.middleWareVariable.id,
          type: this.middleWareVariable.type == 1 ? 1 : 0
        };
      }
      return param;
    },

    // 模糊查询会员标签
    searchMemberList() {
      console.log(this.activeTag);
      if (this.memberTag) {
        this.tagName = this.memberTag;
      } else {
        this.tagName = this.activeTag == 'manual' ? '全部手工标签' : this.activeTag == 'active' ? '全部活动标签' : '全部系统标签';
      }
      // this.handTag = null;
      this.loadMemberTagList({
        searchName: this.memberTag,
        showSearchResult: true,
        id: this.groupId
      });
      this.pageNum = 1;
      // this.handTag = null;
    },
    // 一级标签
    handleFristTag(list) {
      this.pageNum = 1;
      this.pageSize = 20;
      this.params.pageNum = 1;
      this.params.pageSize = 20;
      this.saveHandTagData(list);
      this.saveTagLevelGroupId(list);
      this.handTag = list.handTag;
      this.groupId = list.id;
      this.loadMemberTagList(this.params);
      this.manualTagPop.tagTwoLevelGroupId = '';
      this.manualTagPop.tagLevelGroupId = '';
      const name = ['手工标签', '活动标签'].includes(list.name) ? `全部${list.name}` : list.name;
      this.changeTagTitle(name);
    },
    changeTagTitle(name) {
      this.tagName = name || '全部系统标签';
      this.$store.commit('modiftTagName', this.tagName);
    },
    saveTagLevelGroupId(list = {}) {
      this.params.id = list.id;
      if (list.handTag == 1) {
        // const hangObj = {
        //   name: list.name,
        //   type: 1,
        //   id: list.id
        // };
        // 要存下来是不是手工标签
        // this.params.type = 1;
        // localStorage.setItem('groupId', JSON.stringify(hangObj));
      } else {
        this.params.type = -1;
        localStorage.setItem('groupId', '');
      }
    },
    // 添加手工标签后刷新标签列表
    addNewTag() {
      const params = Object.assign({}, this.params, { searchName: this.memberTag, showSearchResult: true });
      this.loadMemberTagList(params);
    },
    // 删除手工
    deleteHandTag(id) {
      this.loadMemberTagList({
        id: id,
        searchName: this.memberTag,
        showSearchResult: true,
        type: 1 // 手工标签传1
      });
    },

    // 保存手工标签的数据 一 二 三 级
    saveHandTagData(list) {
      localStorage.setItem('middleHandtag', JSON.stringify(list));
    },
    onLoadmore() {
      if (this.pager.pageNum >= this.pager.total) return;
      this.pager.pageNum++;
      this.getMemberGroupList();
    },
    getMemberGroupList() {
      if (this.pager.pageNum == 1) {
        this.memberGroupList = [];
      }
      memberGroupList({ requestProject: 'gic-member-tag-web', type: 0, pageSize: 20, pageNum: this.pager.pageNum })
        .then(res => {
          let { errorCode, message, result } = res;
          if (errorCode != 0) {
            this.$message.error(message);
            return;
          }
          if (Array.isArray(result.result)) {
            this.memberGroupList = this.memberGroupList.concat(result.result);
          }
          this.pager.total = result.totalPage;
        })
        .catch(err => {
          console.log(err);
        });
    },
    // 是否开启自动同步
    getSyncFlag() {
      isAutomaticSync({}).then(res => {
        if (res.errorCode == 0) {
          this.isSync = res.result;
          this.manualTagPop.isSync = res.result;
        }
      });
    },
    setGroupId() {
      const levelGroupInfo = {
        id: this.groupId,
        name: this.tagName
      };
      localStorage.setItem('groupId', JSON.stringify(levelGroupInfo));
    },
    // 点击活动标签、手工标签
    handleClick() {
      this.params.pageNum = 1;
      this.memberTag = '';
      const { activeTag, tagList, allTagList, handleFristTag } = this;
      if (activeTag === 'system') {
        this.handTag = 0;
        allTagList();
      } else if (activeTag === 'manual') {
        const manualTag = tagList.find(el => el.handTag == 1);
        this.handTag = 1;
        handleFristTag(manualTag);
      } else if(activeTag === 'active') {
        const activeTag = tagList.find(el => el.handTag == 2);
        this.handTag = 2;
        handleFristTag(activeTag);
      }
    },
    // 手工标签排序
    remoteSort(prop, order) {
      this.manualOrderBy = order == 'descending' ? 0 : 1;
      this.loadMemberTagList(this.params);
    },
    getShowSystem() {
      return isShowSystemTag().then(res => {
        this.isShowSystem = res.result;
        if(!res.result) {
          this.activeTag='manual';
          const manualTag = this.tagList.find(el => el.handTag == 1);
          this.handTag = 1;
          this.handleFristTag(manualTag);
        };
      })
    },
    updateTypeDesc() {
      const { isRealTime, fixedType } = this.tagConfig;
      if (isRealTime && !fixedType) {
        return `(创建成功后更新)`;
      } else if (!isRealTime && !fixedType) {
        return `(更新时间预计选择日期的0点至9点)`;
      } else if (!isRealTime && fixedType) {
        return `(更新时间预计固化生效日期的0点至9点)`;
      } else if (isRealTime && fixedType) {
        return `(创建成功后更新)`;
      }
    },
    watchUpdateType(isRealTime, fixedType) {
      if (isRealTime && !fixedType) {
        return 1;
      } else if (!isRealTime && !fixedType) {
        return 2;
      } else if (!isRealTime && fixedType) {
        return 3;
      } else if (isRealTime && fixedType) {
        return 4;
      }
    }
  },

  async beforeMount() {
    this._groupCount();
    // 一二三级都需要一个变量来保存自己的信息 在切换页码和数量的时候也要传参数过去
    this.middleWareVariable = {};
    /**
     * 列表数据的参数
     *
     * 如果选中手工标签就判断是不是手工标签 是的话我们就存下手工标签的id和类型
     * 如果是其他的就去掉 groupId 的storage内容
     *
     */
    this.params = {
      requestProject: 'gic-member-tag-web',
      id: '',
      searchName: this.memberTag,
      type: -1,
      pageNum: 1,
      pageSize: 20
    };
    this.tagConfig = {
      ...this.tagConfig,
      groupName: '',
      memberTagGroupClassifyId: '0',
      isRealTime: '',
      textarea: '',
      updateType: 1,
      updateDay: '',
      date: ''
    };
    this.handTag = null;
    this.groupId = '';
    await this.getTagList();
    await this.getShowSystem();
    if (localStorage.getItem('groupId')) {
      const hangObj = JSON.parse(localStorage.getItem('groupId'));
      this.middleWareVariable = JSON.parse(JSON.stringify(hangObj));
      if (!this.isShowSystem) return;
      this.params.type = 1;
      this.params.id = hangObj.id;
      this.$store.commit('modiftTagName', this.tagName);
      this.handTag = 1;
      this.loadMemberTagList(this.params);
    } else {
      if (!this.isShowSystem) return;
      this.loadMemberTagList(this.params);
      this.$store.commit('modiftTagName', '我的用户');
    }
  },
  mounted() {
    this.$on('refersh-member-list', () => {
      this.getTagList();
    });

    // window.onload = this.onLoadV();

    // 处理二级标签
    this.$on('handle-second-tag', list => {
      this.middleWareVariable = {
        id: list.id,
        type: list.handTag,
        name: list.name
      };
      this.pageNum = 1;
      this.pageSize = 20;
      this.saveHandTagData(list);
      this.handTag = list.handTag;
      this.groupId = list.id;
      this.saveTagLevelGroupId(list);
      this.loadMemberTagList(this.params);
      this.manualTagPop.tagTwoLevelGroupId = list.tagLevelGroupId;
      this.manualTagPop.tagLevelGroupId = '';
      this.changeTagTitle(list.name);
    });
    // 处理三级标签
    this.$on('edit-third-tag', _ => {
      let list = JSON.parse(localStorage.getItem('middleHandtag'));
      this.saveTagLevelGroupId(list);
    });

    this.$on('handle-third-tag', list => {
      this.middleWareVariable = {
        id: list.id,
        type: list.handTag,
        name: list.name
      };
      this.pageNum = 1;
      this.pageSize = 20;
      this.params.pageNum = 1;
      this.params.pageSize = 20;
      this.saveHandTagData(list);
      this.saveTagLevelGroupId(list);
      this.groupId = list.id;
      this.handTag = list.handTag;
      this.loadMemberTagList(this.params);
      this.manualTagPop.tagTwoLevelGroupId = list.parentLevelGroupId;
      this.manualTagPop.tagLevelGroupId = list.tagLevelGroupId;
      this.changeTagTitle(list.name);
    });
    this.defaultDate();
    this.getMemberGroupList();
    this.getMemberTagGradeEnsure();
    this.getSyncFlag();
  },
  watch: {
    'tagConfig.isRealTime'(newVal) {
      const { fixedType } = this.tagConfig;
      this.tagConfig.updateType = this.watchUpdateType(newVal, fixedType);
    },
    'tagConfig.fixedType'(newVal) {
      const { isRealTime } = this.tagConfig;
      this.tagConfig.updateType = this.watchUpdateType(isRealTime, newVal);
    },
  }
};
</script>
<style lang="scss">
.member-tag .el-tabs__nav-wrap::after {
  display: none;
}
.member-tag .el-tabs__header {
  margin-bottom: 0;
}
</style>
<style lang="scss" scoped>
.deal-list-mask {
  position: fixed;
  top: 0px;
  right: 0px;
  left: 0px;
  bottom: 0px;
  background-color: transparent;
  z-index: 10;
}
.member-tag {
  position: relative;
  width: 100%;
  height: calc(100% - 12px);
  .tag-container {
    height: 100%;
    box-sizing: border-box;
  }
  .foot-box {
    margin-top: -100px;
  }
  .main-tag {
    display: flex;
    justify-content: flex-start;
    align-items: stretch;
    border-top: 1px solid #ebeef5;
    padding: 0 20px;
    height: 100%;
    overflow: hidden;
    .tag-list {
      overflow-y: auto;
      flex: 0 0 360px;
      height: 100%;
      border-right: 1px solid #ebeef5;
      .user-info {
        font-size: 16px;
        color: #909399;
        cursor: pointer;
      }
      .light-active {
        color: #2f54eb;
      }
    }
    .tag-all {
      flex: 1;
      position: relative;
      padding-bottom: 40px;
      overflow-y: auto;
      .tag-name {
        overflow: hidden;
        line-height: 34px;
        padding: 20px;
        font-size: 16px;
        color: #303133;
        font-weight: bold;
      }
      .page-box {
        float: right;
        margin: 20px;
      }
      .add-newtag {
        float: right;
        margin-left: 15px;
      }
    }
  }
  .member-box {
    overflow: hidden;
    margin: 4px 0 20px;
    height: 100%;
    background-color: #fff;
  }
  .my-pop-tagbox {
    position: fixed;
    z-index: 10;
    right: 29px;
    bottom: 230px;
    height: 90px;
    width: 45px;
    // color: #fff;
    background-color: #fff;
    box-shadow: 0px 4px 12px 0px rgba(220, 223, 230, 0.6);
    color: #2f54eb;
    // border-radius: 50%;
    cursor: pointer;
    .txt {
      padding: 9px 8px 7px 11px;
      text-align: center;
      // padding-top: 25px;
      font-size: 14px;
      line-height: 17px;
      i {
        font-size: 24px;
        position: relative;
        top: 3px;
      }
      span {
        margin-top: 9px;
        display: inline-block;
        width: 28px;
        color: #303133;
        line-height: 20px;
      }
    }
    .number-txt {
      text-align: center;
      padding-top: 5px;
      font-size: 14px;
    }
    &:hover {
      transition: all ease 0.4s;
      width: 50px;
    }
  }
  .group-right-list {
    position: fixed;
    width: 600px;
    top: 50px;
    right: -600px;
    bottom: 0px;
    box-shadow: 0 0 5px #bbb;
    background-color: #fff;
    z-index: 1001;
    padding: 0 21px;
    transition: all 0.3s ease-in;
    .group-title {
      padding: 24px 0;
      color: #303133;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .label {
        font-size: 16px;
        font-weight: 600;
      }
      .icon-right {
        cursor: pointer;
      }
    }
    .group-tips {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      margin-bottom: 17px;
      .desc {
        display: inline-block;
        font-size: 12px;
        color: #606266;
        line-height: 17px;
      }
    }
    .form-item {
      margin-top: 24px;
      margin-bottom: 24px;
      color: #303133;
      label {
        display: flex;
        margin-bottom: 10px;
        align-items: center;
        font-size: 14px;
      }
      .form-tip-icon {
        margin-left: 5px;
        display: flex;
        justify-content: center;
        align-items: center;
        width: 14px;
        height: 14px;
        font-size: 12px;
        color: #909399;
        border: 1px solid #909399;
        border-radius: 14px;
        cursor: pointer;
      }
    }
    .refresh-txt {
      color: #606266;
    }
    .wapper {
      height: calc(100% - 180px);
      padding: 10px 0;
      overflow-y: auto;
      .desc-labeltxt {
        padding: 0 10px;
        color: #606266;
        font-size: 12px;
      }
    }
    .marginwapper {
      margin-left: 0px;
    }
    .fixed-btn {
      position: absolute;
      height: 56px;
      line-height: 56px;
      right: 0px;
      left: 0px;
      bottom: 0px;
      width: 100%;
      text-align: center;
      background-color: #fff;
      box-shadow: 0px -2px 8px 0px rgba(220, 223, 230, 0.6);
    }
    .tips-count {
      font-size: 12px;
      color: red;
    }
  }
  .group-transtion-list {
    transition: all 0.3s ease-in;
    right: 0px;
  }
  .groupName-txt {
    position: relative;
    color: #909399;
    top: 2px;
    left: -45px;
    font-size: 12px;
  }
  .textarea-txt {
    float: right;
    transform: translate(0, 10px);
    color: #909399;
    font-size: 12px;
  }
}
.tips {
  font-size: 12px;
  color: #909399;
  padding: 0 0 15px 20px;
}
.margin-60 {
  margin-left: 60px;
}
.help-doc {
  color: #2f54eb;
  display: inline-block;
  line-height: 20px;
  font-size: 14px;
}
.flex {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}
.sub-title {
  display: inline-block;
  position: relative;
  top: 2px;
}
.tip-icon {
  color: #606266;
  font-size: 14px;
}
.radio-group {
  display: flex;
}
</style>
