<template>
  <div class="member-tag">
    <div class="tag-container">
      <nav-crumb :navpath="navpath"></nav-crumb>

      <div class="member-box">
        <div class="tag-input">
          <el-input placeholder="请输入关键词回车搜索标签" prefix-icon="el-icon-search" style="width: 348px" v-model="memberTag" @keyup.native.enter="searchMemberList" clearable></el-input>
        </div>
        <div class="main-tag">
          <div class="tag-list">
            <div class="search-box"></div>
            <p class="user-info" @click="allTagList">我的用户</p>
            <div class="list-box">
              <TagType v-for="(list, i) in tagList" :key="i" :tag-list="list" @handleFristTag="handleFristTag"> </TagType>
            </div>
          </div>

          <div class="tag-all">
            <p class="tag-name">
              {{ tagName }}
              <el-button type="primary" class="add-newtag" @click="addNewTag" v-show="handTag == 1">新增标签</el-button>
            </p>

            <tag-container :data="memberTagList" :handTag="handTag" :groupId="groupId" @deleteHandTag="deleteHandTag" @returnTagData="returnTagData" ref="tagContainer"> </tag-container>

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

            <!-- 我的标签 -->
            <div class="my-pop-tagbox" v-if="groupListNumber > 0" @click="expendsGroupList">
              <p class="txt">已选标签</p>
              <p class="number-txt">{{ groupListNumber }}</p>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="foot-box">
      <vue-gic-footer></vue-gic-footer>
    </div>

    <div class="group-right-list" v-show="groupShow && groupListNumber">
      <el-collapseTransition>
        <div class="wapper">
          <div class="inner">
            <tags-group-list :selectedTagsData="selectedTags" :tagsGroupRelation="tagsGroupRelation" @addTags="addTags" @editTags="editTags" :activeTagsGroupIndex.sync="activeTagsGroupIndex" />
            <div class="form-item">
              <label for="">分组名称</label>
              <el-input v-model="tagConfig.groupName" :maxlength="10" style="width: 200px;" placeholder="请输入内容"></el-input>
              <span class="groupName-txt">{{ tagConfig.groupName.length }}/10</span>
            </div>
            <div class="form-item">
              <label for="">分组有效期</label>
              <el-date-picker v-model="tagConfig.date" type="date" placeholder="选择日期"> </el-date-picker>
            </div>
            <div class="form-item">
              <label for="">分组描述</label>
              <el-input type="textarea" v-model="tagConfig.textarea" :maxlength="200" style="width: 400px;" placeholder="请输入内容"></el-input>
              <span class="textarea-txt">{{ tagConfig.textarea.length }}/200</span>
            </div>
            <div class="form-item">
              <label for="">更新频率</label>
              <el-select class="w-200" v-model="tagConfig.updateType" placeholder="请选择">
                <el-option v-for="(item, index) in rateData" :key="item.label" :label="item.label" :value="index + 1"></el-option>
              </el-select>
              <el-select class="w-200 p-l-8" v-model="tagConfig.updateDay" v-show="tagConfig.updateType != 1" placeholder="请选择">
                <el-option v-for="(item, index) in rateData[tagConfig.updateType ? tagConfig.updateType - 1 : 0].options" :key="item" :label="item" :value="index + 1"></el-option>
              </el-select>
            </div>
            <p class="refresh-txt">更新频率（更新时间预计选择日期的凌晨0点至6点）</p>
          </div>
          <div class="fixed-btn">
            <el-button type="primary" @click="createNewGroup">创建会员分组</el-button>
            <el-button @click="groupShow = false">关闭</el-button>
          </div>
        </div>
      </el-collapseTransition>
    </div>
  </div>
</template>

<script>
import Vue from 'vue';
import { CollapseTransition } from 'element-ui';
import navCrumb from '@/components/nav/nav.vue';
import TagsGroupList from '../memberGroup/tags-group-list';
import TagType from './tag-type';
import TagContainer from './tag-container';
import { getMemberTag, getMemberTagList, addNewGroup } from '@/request/api';

Vue.component(CollapseTransition.name, CollapseTransition);

export default {
  name: 'member-tag',

  componentName: 'member-tag',

  components: {
    navCrumb,
    TagType,
    TagContainer,
    TagsGroupList
  },

  data() {
    return {
      tagConfig: {
        groupName: '',
        textarea: '', // 描述
        date: '', // 有效期
        updateType: '', // 更新类型频率
        updateDay: '', // 更新类型时间
        isRealTime: 0, // 实时
        effectiveStatus: 1 // 有效状态nage
      },
      activeTagsGroupIndex: 0,
      groupShow: false,
      selectedTags: [[]],
      tagsGroupRelation: [],
      // 面包屑参数
      navpath: [
        {
          name: '首页',
          path: `${window.location.origin}/report/#/memberSummary`,
          relocation: true
        },
        {
          name: '会员管理',
          path: ''
        },
        {
          name: '会员标签',
          path: ''
        }
      ],
      tagList: [],
      memberTagList: [], // 会员标签列表
      tagName: '全部标签',
      memberTag: '', // 搜索会员标签关键字
      tagCategory: '', // 当前标签类别
      pageSize: 20,
      pageNum: 1,
      currentPage: 1,
      total: 0,

      // 更新频率
      rateData: [
        {
          label: '每日一次',
          options: []
        },
        {
          label: '每周一次',
          options: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
        },
        {
          label: '每月一次',
          options: [
            '1号',
            '2号',
            '3号',
            '4号',
            '5号',
            '6号',
            '7号',
            '8号',
            '9号',
            '10号',
            '11号',
            '12号',
            '13号',
            '14号',
            '15号',
            '16号',
            '17号',
            '18号',
            '19号',
            '20号',
            '21号',
            '22号',
            '23号',
            '24号',
            '25号',
            '26号',
            '27号',
            '28号'
          ]
        }
      ]
    };
  },

  computed: {
    groupListNumber() {
      return this.selectedTags.reduce((curr, el) => {
        return curr + el.length;
      }, 0);
    }
  },

  methods: {
    allTagList() {
      this.loadMemberTagList({});
      this.tagName = '全部标签';
      this.$store.commit('modiftTagName', '全部标签');
    },
    checkRealTime() {
      let arr = this.selectedTags.reduce((curr, el) => {
        return curr.concat(el);
      }, []);

      let newActiveArr = arr.map(el => el.isActive);
      this.tagConfig.isRealTime = newActiveArr.indexOf(0) > -1 ? 0 : 1;
    },
    createNewGroup() {
      this.checkRealTime();
      const param = {
        groupName: this.tagConfig.groupName,
        isRealTime: this.tagConfig.isRealTime,
        describle: this.tagConfig.describle,
        updateType: this.tagConfig.updateType,
        updateDay: this.tagConfig.updateDay,
        // effectiveStatus: '',
        requestProject: 'gic-member-tag-web',
        json: JSON.stringify(this.selectedTags),
        effectiveDateTmp: this.tagConfig.date
      };
      console.log(param);
      addNewGroup(param)
        .then(res => {
          if (res.errorCode == 1) {
            // console.log(res);
          }
        })
        .catch(err => {
          // console.log(err);
        });
    },
    expendsGroupList() {
      // if (this.selectedTags && this.selectedTags.length) {
      this.groupShow = true;
      // }
    },
    returnTagData(list) {
      // 把添加的标签数据加到显示组件中 activeTagsGroupIndex
      // 判断是否已经存在于当前二维数组里面
      this.selectedTags = JSON.parse(JSON.stringify(list));
      // let middleList = this.selectedTags.reduce((curr, el) => {
      //   return curr.concat(el);
      // }, []);

      // let index = middleList.findIndex(el => el.tagId === list.tagId);
      // // 不存在这个元素
      // if (index < 0) {
      //   this.selectedTags[this.activeTagsGroupIndex].push(list);
      // } else {
      //   // 否则就是修改
      // }
    },
    editTags() {
      //
      this.$refs.tagContainer.dialogVisible = true;
    },
    addTags() {
      //
    },
    async getTagList() {
      const Data = await getMemberTag();
      if (Data.result && Data.result.length) {
        this.tagList = Data.result;
      } else {
        this.tagList = [];
      }
    },

    async loadMemberTagList(opt) {
      try {
        const params = {
          requestProject: 'gic-member-tag-web',
          search: opt.searchName || null, // 标签名
          tagLevelGroupId: opt.id || 0, // 标签层级
          tagType: opt.type || null, // 标签类型
          pageNum: this.pageNum,
          pageSize: this.pageSize
        };
        const Data = await getMemberTagList(params);
        if (Data.result.result && Data.result.result.length) {
          this.memberTagList = Data.result.result.map(el => ({
            ...el,
            refersh: false
          }));
          this.total = Data.result.totalCount;
        } else {
          this.memberTagList = [];
          this.total = 0;
        }
      } catch (e) {
        // console.log(e);
      }
    },

    // 每页条数改变
    handleSizeChange(val) {
      this.pageSize = val;
      this.pageNum = 1;
      const param = this.JudgeIsHandTag();
      this.loadMemberTagList(param);
    },
    // 当前页码改变
    handleCurrentChange(val) {
      this.pageNum = val;
      const param = this.JudgeIsHandTag();
      this.loadMemberTagList(param);
    },
    /**
     * 判断是否是手工标签
     */
    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() {
      this.loadMemberTagList({
        searchName: this.memberTag
      });
      // this.tagName = '全部标签';
      // this.handTag = null;
    },
    // 一级标签
    handleFristTag(list) {
      this.middleWareVariable = {
        id: list.id,
        type: list.handTag,
        name: list.name
      };
      this.pageNum = 1;
      this.pageSize = 20;
      this.loadMemberTagList({
        id: list.id,
        type: list.handTag ? 1 : -1 // 手工标签传1
      });
      this.groupId = list.id;
      this.handTag = list.handTag;
      this.changeTagTitle(list.name);
      this.saveTagLevelGroupId(list);
    },
    changeTagTitle(name) {
      this.tagName = name || '全部标签';
      this.$store.commit('modiftTagName', this.tagName);
    },
    saveTagLevelGroupId(list) {
      if (list.handTag == 1) {
        const hangObj = {
          name: list.name,
          type: 1,
          id: list.id
        };
        localStorage.setItem('groupId', JSON.stringify(hangObj));
      }
    },
    // 添加手工标签
    addNewTag() {
      this.$router.push('/manualTagEdit');
    },
    // 删除手工
    deleteHandTag(id) {
      this.loadMemberTagList({
        id: id,
        type: 1 // 手工标签传1
      });
    }
  },

  beforeMount() {
    // 一二三级都需要一个变量来保存自己的信息 在切换页码和数量的时候也要传参数过去
    this.middleWareVariable = {};
    this.handTag = null;
    this.groupId = '';
    this.getTagList();
    if (localStorage.getItem('groupId')) {
      const hangObj = JSON.parse(localStorage.getItem('groupId'));
      this.middleWareVariable = JSON.parse(JSON.stringify(hangObj));
      this.loadMemberTagList({
        tagType: 1,
        id: hangObj.id
      });
      this.tagName = hangObj.name;
      this.$store.commit('modiftTagName', this.tagName);
      this.handTag = true;
    } else {
      this.loadMemberTagList({
        tagType: -1
      });
    }
  },
  mounted() {
    this.$on('refersh-member-list', () => {
      this.getTagList();
    });

    // 处理二级标签
    this.$on('handle-second-tag', list => {
      this.middleWareVariable = {
        id: list.id,
        type: list.handTag,
        name: list.name
      };
      this.pageNum = 1;
      this.pageSize = 20;
      this.loadMemberTagList({
        id: list.id,
        type: list.handTag ? 1 : -1 // 手工标签传1
      });
      this.groupId = list.id;
      this.handTag = list.handTag;
      this.changeTagTitle(list.name);
      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.loadMemberTagList({
        id: list.id,
        type: list.handTag ? 1 : -1 // 手工标签传1
      });
      this.groupId = list.id;
      this.handTag = list.handTag;
      this.changeTagTitle(list.name);
      this.saveTagLevelGroupId(list);
    });
  }
};
</script>

<style lang="scss" scoped>
.member-tag {
  position: relative;
  width: 100%;
  overflow-y: auto;
  .tag-container {
    min-height: 100%;
    box-sizing: border-box;
    padding-bottom: 93px;
  }
  .foot-box {
    margin-top: -100px;
  }
  .main-tag {
    display: flex;
    border-top: 1px solid #ebeef5;
    .tag-list {
      overflow-y: auto;
      flex: 0 0 470px;
      padding: 23px 0 0 25px;
      // height: 580px;
      border-right: 1px solid #ebeef5;
      .user-info {
        font-size: 16px;
        color: #909399;
        cursor: pointer;
      }
    }
    .tag-all {
      position: relative;
      flex: 1;
      position: relative;
      .tag-name {
        line-height: 34px;
        padding: 10px 20px;
        font-size: 16px;
        color: #303133;
        font-weight: bold;
      }
      .page-box {
        float: right;
        margin: 20px;
      }
      .add-newtag {
        float: right;
        margin-bottom: 10px;
      }
    }
  }
  .member-box {
    margin: 20px 32px 0;
    background-color: #fff;
    .tag-input {
      padding: 16px 20px;
    }
  }
  .my-pop-tagbox {
    position: absolute;
    z-index: 2;
    right: 40px;
    bottom: 100px;
    height: 70px;
    width: 70px;
    color: #fff;
    background-color: #1890ff;
    box-shadow: 0 0 5px #555;
    border-radius: 50%;
    cursor: pointer;
    .txt {
      text-align: center;
      padding-top: 25px;
      font-size: 12px;
    }
    .number-txt {
      text-align: center;
      padding-top: 5px;
      font-size: 14px;
    }
    &:hover {
      transition: all ease 0.3s;
      transform: scale(1.2);
    }
  }
  .group-right-list {
    position: absolute;
    top: 0px;
    right: 0px;
    bottom: 0px;
    padding: 10px;
    box-shadow: 0 0 5px #bbb;
    background-color: #fff;
    z-index: 10;
    transition: all 0.3s ease-in-out;
    .form-item {
      margin-top: 20px;
      margin-bottom: 20px;
      color: #606266;
      label {
        display: block;
        margin-bottom: 10px;
      }
    }
    .wapper {
      height: 700px;
      overflow-y: auto;
    }
    .marginwapper {
      margin-left: 0px;
    }
    .fixed-btn {
      position: absolute;
      bottom: 20px;
      width: 100%;
      text-align: center;
    }
  }
  .groupName-txt {
    position: relative;
    color: #909399;
    top: 2px;
    left: -45px;
  }
  .textarea-txt {
    position: relative;
    color: #909399;
    left: -70px;
  }
}
</style>
