<!--
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 晨曦
 * @Date: 2021-06-10 46:45:37
 * @LastEditors: 晨曦
 * @LastEditTime: 2021-06-11 15:35:50
 会员标签页和其同步历史，待定目前不上线
 -->

<!--
  我的客户应用：
  <app-detail ></app-detail>
 -->
<template>
  <div class="app-detail-wrap member-tag">
    <div class="top p-20">
      <div role="alert" class="el-alert el-alert--info flex flex-align-start ">
        <i class="el-alert__icon el-icon-warning color-2f54eb"></i>
        <div class="el-alert__content">
          <p class="el-alert__title color-303133 font-13">
            1. 下方的标签是从【GIC后台-会员标签-手工标签-导购标签】中获取而来，若不一致，可刷新页面获取GIC后台最新的导购标签库。<br />
            2. 可选多个GIC导购标签批量同步至企微标签库。每天最多操作同步1次，每月最多4次，请酌情开启同步。<br />
            3. 当尚有“同步中”状态的导购标签时，不可进行其他操作如勾选标签或关闭同步等。<br />
            4. 同步完成后，系统会将所选GIC导购标签同步至企微标签库，且“会员”身上被打上的GIC导购标签结果也会同步至企微端，也即“会员”所对应的企微客户身上也会被打上对应的同步过去的导购标签。<br />
            5. 所选标签成功同步至企微侧后，标签名称会默认带有“GIC”前缀，便于和企微标签库中本身创建的标签区分；请勿在企微标签库中对GIC侧同步过去的标签进行修改，一旦在企微侧将GIC侧同步过去的标签组或标签组下的某标签值删除了，则该标签在此处将自动关闭同步，企微客户身上所打的该标签组下的标签值也会自动清除。
          </p>
        </div>
      </div>
    </div>
    <div class="bottom">
      <ul class="tag-category">
        <li :class="[-1 == tagCategoryId ? 'acitve' : '']" @click="onChangeCate(-1)">全部标签分组</li>
        <li v-for="item in tagCategory" :key="item.id" :class="['indent-tag', item.id == tagCategoryId ? 'acitve' : '']" @click="onChangeCate(item.id)">{{ item.name }}</li>
      </ul>
      <div class="tag-content">
        <div class="tag-content-top p-20">
          <div class="slect-wrap">
            <el-input v-model="search" placeholder="请输入内容" style="width: 223px" prefix-icon="el-icon-search" clearable @change="searchList" />
            <el-select class="w-160 m-l-10" placeholder="全部同步状态" v-model="syncStatus" @change="searchList">
              <el-option label="未同步" :value="0"></el-option>
              <el-option label="同步中" :value="1"></el-option>
              <el-option label="同步完成" :value="2"></el-option>
              <el-option label="全部同步状态" :value="-1"></el-option>
            </el-select>
          </div>
          <div class="btn-group">
            <el-button v-if="$getButtonLimit($buttonCode.syncTagLog)" :limit-code="$buttonCode.syncTagLog" @click="$router.push('/syncHistory')">同步历史</el-button>
            <el-button v-if="$getButtonLimit($buttonCode.willSyncTag)" :limit-code="$buttonCode.willSyncTag" @click="drawer = true" type="primary" :disabled="!canSync || !canUseCount" :class="['sync-btn', isShake ? 'shake' : '']">待开启同步标签（ {{ tagIds.length }} ）</el-button><span v-if="canUseCount === 0" class="no-use-count">本月同步次数已用尽</span>
          </div>
        </div>
        <div class="tag-content-bottom">
          <el-table v-loading="loading" ref="table" :data="tableData" tooltip-effect="dark" row-key="tagId" style="width: 100%" @selection-change="handleSelectionChange" @row-click="rowCheckChange">
            <el-table-column type="selection" width="55" :selectable="checkSelectable" :reserve-selection="true"></el-table-column>
            <el-table-column label="标签组" prop="tagName" show-overflow-tooltip>
              <template slot-scope="{ row }">
                <span>{{ row.tagName || '--' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="标签描述" prop="tagDescribe" show-overflow-tooltip>
              <template slot-scope="{ row }">
                <span>{{ row.tagDescribe || '--' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="标签值" min-width="240">
              <template slot-scope="{ row }">
                <div class="flex">
                  <p class="tag-val" v-for="item in row.tagItems.slice(0, 4)" :key="item.tagItemId">{{ item.tagItemName }}</p>
                  <el-button class="expendBtn" type="text" v-if="row.tagItems.length > 4" @click.stop="expendTag(row)">{{ row.expend ? '收起' : '展开' }}</el-button>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="同步状态" prop="syncFlag">
              <template slot-scope="{ row }">
                <span :class="['state-point', syncStatusClass[row.syncFlag]]">{{ syncStatusOpt[row.syncFlag] }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="{ row }">
                <p v-if="row.syncFlag == 2 && canSync">
                  <el-button type="text" @click="changeSync(row)">关闭同步</el-button>
                </p>
                <p v-else></p>
              </template>
            </el-table-column>
            <el-table-column type="expand" width="1">
              <template slot-scope="{ row }">
                <div class="expand-content">
                  <span class="tag-val" v-for="item in row.tagItems" :key="item.tagItemId">{{ item.tagItemName }}</span>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <div class="block common-wrap__page text-right m-t-24">
            <dm-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[20, 40, 60, 80]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"> </dm-pagination>
          </div>
          <el-drawer :modal="false" :title="`待开启同步标签（${tagIds.length}）`" :visible.sync="drawer" :direction="direction" :before-close="handleClose">
            <div v-if="tagIds.length" class="tag-list">
              <div class="header">
                <el-button type="text" @click="clearSlected">全部清空</el-button>
              </div>
              <ul class="tag-content">
                <li class="tag-content-item" v-for="item in tagIds" :key="item.tagId">
                  <div class="left">
                    <p class="title">{{ item.tagName }}</p>
                    <p class="describe">{{ item.tagDescribe || '- -' }}</p>
                  </div>
                  <i class="el-icon-error" @click="cancelSelect(item)"></i>
                </li>
              </ul>
              <div class="btn-wrap" @click="checkSync">
                <p class="title">确认开启同步</p>
                <p class="tip">注：每月可使用{{ totalCount }}次，目前还剩{{ canUseCount }}次</p>
              </div>
            </div>
            <div v-else class="empty">
              <svg class="icon svg-icon" aria-hidden="true" style="width:72px;height:46px;margin-bottom:10px;">
                <use xlink:href="#iconkongbiaoqian" size="46"></use>
              </svg>
              <p>请先选择需开启同步的标签组</p>
            </div>
          </el-drawer>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { tagCategoryList, tagList, closeSync, syncSet, checkSync } from '@/api/memberTag';
import errMsg from '@/common/js/error';
export default {
  name: 'app-detail',
  props: {
    brandId: {
      type: String,
      default() {
        return '';
      }
    }
  },
  mounted() {
    this.brandId && this.getTagCategoryList();
    this.brandId && this.getTableList();
    this.checkSyncCount();
  },
  data() {
    return {
      tableData: [],
      tagCategory: [],
      tagCategoryId: -1,
      tableList: [],
      tagIds: [],
      search: '',
      syncStatus: -1,
      wxEnterpriseId: JSON.parse(sessionStorage.getItem('userInfos')).wxEnterpriseId,
      pageSize: 20,
      currentPage: 1,
      total: 0,
      drawer: false,
      isShake: false,
      loading: false,
      selectIds: {},
      cancelIds: [],
      canSync: true, // 查询是否有同步中队列 true可同步 flase不可以
      totalCount: 4, // 总同步次数
      canUseCount: 0, // 剩余同步次数
      checkFirst: '',
      syncStatusOpt: { 0: '未同步', 1: '同步中', 2: '同步完成 ' },
      syncStatusClass: { 0: 'state-point-default', 1: 'state-point-loading-scale', 2: 'state-point-success', 3: 'state-point-error' }
    };
  },
  methods: {
    checkSyncCount() {
      checkSync().then(res => {
        if (res.data.result) {
          this.canSync = res.data.result.canSync;
          this.totalCount = res.data.result.totalCount;
          this.canUseCount = res.data.result.canUseCount;
        }
      });
    },
    checkSelectable(row) {
      return !this.canSync ? false : this.canUseCount === 0 ? false : row.tagItems.length && row.syncFlag === 0 ? true : false;
    },
    getTagCategoryList() {
      tagCategoryList({ enterpriseId: this.brandId }).then(res => {
        this.tagCategory = res.data.result;
      });
    },
    searchList() {
      this.currentPage = 1;
      this.getTableList();
    },
    getTableList() {
      this.loading = true;
      let params = {
        wxEnterpriseId: this.wxEnterpriseId,
        enterpriseId: this.brandId,
        classifyId: this.tagCategoryId,
        pageSize: this.pageSize,
        pageNum: this.currentPage,
        syncStatus: this.syncStatus,
        search: this.search
      };
      tagList(params)
        .then(res => {
          this.total = res.data.result.totalCount;
          if (Array.isArray(res.data.result.result) && res.data.result.result.length) {
            res.data.result.result.map((el, index) => {
              el.expend = false;
              el.index = index;
              el.check = false;
            });
            this.tableData = [].concat(res.data.result.result);
            this.$nextTick(() => {
              this.changePageToggleSelect();
            });
          } else {
            this.tableData = [];
          }
        })
        .finally(_ => {
          this.loading = false;
        });
    },
    // 关闭同步接口
    closeSync(row) {
      let that = this;
      let params = {
        memberTagId: row.tagId,
        enterpriseId: this.brandId,
        wxEnterpriseId: this.wxEnterpriseId
      };
      closeSync(params)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            that.$message.success(`${row.tagName}标签，取消同步`);
            that.getTableList();
          } else {
            errMsg.errorMsg(resData);
          }
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    expendTag(row) {
      row.expend = !row.expend;
      this.$refs.table.toggleRowExpansion(row, row.expend);
    },
    // 改变同步状态
    changeSync(row) {
      this.$confirm('此为敏感操作！关闭同步后，企微标签库中该标签将会被立即删除， “企微好友”身上所被打的该标签也会被清除，请再次确认您的操作！', '确认关闭同步？')
        .then(() => {
          this.closeSync(row);
        })
        .catch(() => {});
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.getTableList();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getTableList();
    },
    onChangeCate(id) {
      this.tagCategoryId = id;
      this.currentPage = 1;
      this.getTableList();
    },
    // 选中的row
    handleSelectionChange(rows) {
      this.tagIds = [].concat(rows);
      let selectIds = Object.assign({}, this.selectIds);
      rows.forEach(row => {
        if (selectIds[row.tagId] === undefined) {
          selectIds[row.tagId] = row;
        }
      });
      this.selectIds = Object.assign({}, selectIds);
      this.isShake = true;
      setTimeout(() => (this.isShake = false), 300);
    },
    rowCheckChange(row, column, event) {
      if (this.canSync && row.syncFlag === 0 && row.tagItems.length && this.canUseCount) {
        this.$refs.table.toggleRowSelection(row);
        row.check = !row.check;
      }
    },
    cancelSelect(row) {
      if (this.tableData.find(el => el.tagId === row.tagId)) {
        this.$nextTick(() => {
          this.$refs.table.toggleRowSelection(this.tableData[this.selectIds[row.tagId].index], false);
        });
      } else {
        this.cancelIds.push(row.tagId);
        this.tagIds.splice(
          this.tagIds.findIndex(el => el.tagId === row.tagId),
          1
        );
      }
    },
    changePageToggleSelect() {
      this.cancelIds.forEach((id, index) => {
        const item = this.tableData.find(el => el.tagId === id);
        if (item) {
          this.$nextTick(() => {
            this.$refs.table.toggleRowSelection(this.tableData[item.index], false);
          });
        }
      });
      this.cancelIds = [];
    },
    checkSync() {
      this.$confirm('由于数据量可能过大以及企微限制，系统执行较缓慢，请耐心等待', '确认开启同步？')
        .then(() => {
          this.handlePartSync();
        })
        .catch(() => {});
      this.drawer = false;
    },
    // 处理批量同步
    handlePartSync() {
      let that = this;
      that.loading = true;
      let ids = that.tagIds.map(el => el.tagId).toString();
      let params = {
        wxEnterpriseId: that.wxEnterpriseId,
        enterpriseId: that.brandId,
        tagIds: ids
      };
      syncSet(params)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            setTimeout(() => {
              that.$message.success('批量同步完成');
              that.selectIds = {};
              that.tagIds = [];
              that.$refs.table.clearSelection();
              that.getTableList();
            }, 3000);
          } else {
            that.loading = false;
            errMsg.errorMsg(resData);
          }
        })
        .catch(function(error) {
          that.loading = false;
          that.$message.error(error.message);
        });
    },
    clearSlected() {
      this.selectIds = {};
      this.tagIds = [];
      this.$refs.table.clearSelection();
    }
  },
  watch: {
    // 仅第一次赋值brandId调用
    brandId: function(newData) {
      this.getTagCategoryList();
      this.getTableList();
      this.checkSyncCount();
      this.clearSlected();
    }
  }
};
</script>

<style scoped lang="less">
span,
/deep/ .cell,
p,
li {
  font-family: PingFangSC-Regular, PingFang SC;
}
/deep/ .el-table__expand-column .cell {
  display: none !important;
}
/deep/ .el-table__body {
  border-collapse: initial !important;
}
/deep/ .el-table__expanded-cell {
  padding: 5px 30px !important;
}
/deep/ .popover-btn.el-button {
  padding: 4px 6px;
  min-width: auto !important;
  span {
    font-size: 12px;
    font-family: PingFangSC-Regular, PingFang SC;
  }
}
.w-160 {
  width: 160px;
}
.use-num {
  font-family: PingFang-SC-Bold, PingFang-SC;
  font-weight: bold;
  color: #303133;
  line-height: 20px;
}
.syncLoading {
  font-size: 12px;
  color: #909399;
  line-height: 17px;
}
.indent-tag {
  text-indent: 1em;
}
.member-tag {
  box-sizing: border-box;
  .top {
    border-bottom: 1px solid #e4e7ed;
    .el-alert--info {
      align-items: flex-start;
      width: 1033px;
      padding: 5px 16px 5px 17px;
      margin-right: 17px;
      font-size: 13px;
      background: #f0f5ff;
      border-radius: 2px;
      border: 1px solid #85a5ff;
      -webkit-box-align: flex-start;
      -webkit-align-items: flex-start;
      -ms-flex-align: flex-start;
      .el-alert__content {
        padding-left: 0;
        .el-alert__title {
          line-height: 22px;
        }
      }
      .el-alert__icon {
        margin-top: 5px;
        margin-right: 9px;
        font-size: 12px;
        color: #2f54eb;
      }
    }
  }
  .bottom {
    display: flex;
    height: calc(100% - 148px);
    .tag-category {
      padding-top: 16px;
      min-width: 230px;
      font-size: 14px;
      font-weight: 400;
      color: #606266;
      line-height: 20px;
      li {
        padding: 6px 21px;
        cursor: pointer;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
      .acitve {
        background: #f0f5ff;
        color: #2f54eb;
      }
      li:hover {
        background: #f0f5ff;
        color: #2f54eb;
      }
    }
    .tag-content {
      border-left: 1px solid #e4e7ed;
      flex: 1;
      .tag-content-top {
        display: flex;
        justify-content: space-between;
        align-items: center;
        .no-use-count {
          margin-left: 10px;
          font-size: 12px;
          font-weight: 400;
          color: #909399;
          line-height: 17px;
        }
      }
      .tag-content-bottom {
        padding: 0 20px 14px;
        .tag-val {
          max-width: 133px;
          padding: 2px 12px;
          margin-right: 10px;
          background: #f7f8fa;
          border-radius: 2px;
          font-size: 12px;
          border: 1px solid #dcdfe6;
          // text-align: center;
          line-height: 22px;
          box-sizing: border-box;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 1;
          -webkit-box-orient: vertical;
        }
        .expendBtn {
          font-size: 12px;
        }
        .expand-content {
          display: flex;
          flex-wrap: wrap;
          .tag-val {
            margin: 5px 10px 5px 0;
          }
        }
      }
    }
  }
  /deep/.el-drawer {
    width: 358px !important;
    height: 100vh;
  }
  /deep/.el-drawer__container {
    .el-drawer__header {
      height: 46px;
      padding: 0 22px 0 20px;
      margin-bottom: 0;
      line-height: 46px;
      background: #f5f7fa;
      span {
        font-size: 16px;
        font-weight: 600;
        color: #47494c;
        line-height: 22px;
      }
      .el-icon-close {
        font-size: 13px;
        color: #c0c4cc;
      }
    }
    .tag-list {
      display: flex;
      flex-direction: column;
      justify-content: flex-start;
      align-items: center;
      width: 100%;
      height: calc(100vh - 46px);
      .header {
        display: flex;
        justify-content: flex-end;
        width: 100%;
        height: 48px;
        padding: 19px 20px 9px 0;
        border-bottom: 1px solid #e4e7ed;
        box-sizing: border-box;
        .el-button {
          height: 20px;
          span {
            display: block;
            font-size: 14px;
            font-weight: 400;
            color: #365fee;
            line-height: 20px;
          }
        }
      }
      .tag-content {
        height: calc(100vh - 152px);
        padding: 13px 19px 0;
        overflow-y: scroll;
        overflow-x: hidden;
        width: 100%;
        box-sizing: border-box;
        .tag-content-item {
          display: flex;
          justify-content: flex-start;
          align-items: center;
          width: 100%;
          padding: 13px 0;
          transition: 0.4s;
          -webkit-touch-callout: none;
          -webkit-user-select: none;
          -khtml-user-select: none;
          -moz-user-select: none;
          -ms-user-select: none;
          user-select: none;
          .left {
            .title {
              width: 315px;
              margin-bottom: 7px;
              font-size: 14px;
              font-weight: 600;
              color: #3e4042;
              line-height: 14px;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
            .describe {
              width: 315px;
              font-size: 12px;
              font-weight: 400;
              color: #a5a7ad;
              line-height: 14px;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
          }
          .el-icon-error {
            margin-left: 40px;
            font-size: 20px;
            color: #e2e4e8;
            display: none;
            transition: all 0.5s;
            cursor: pointer;
            &:hover {
              color: #c4c6cf;
            }
          }
          &:hover {
            transform: translateX(-5px);
            .title,
            .describe {
              width: 252px;
            }
            .el-icon-error {
              display: block;
            }
          }
        }
      }
      .btn-wrap {
        width: 100%;
        height: 58px;
        padding-top: 9px;
        text-align: center;
        background: #2f54eb;
        box-sizing: border-box;
        cursor: pointer;
        -webkit-touch-callout: none;
        -webkit-user-select: none;
        -khtml-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
        user-select: none;
        .title {
          font-size: 16px;
          font-weight: 600;
          color: #ffffff;
          line-height: 22px;
        }
        .tip {
          font-size: 12px;
          font-weight: 400;
          color: rgba(255, 255, 255, 0.65);
          line-height: 17px;
        }
      }
    }
    .empty {
      display: flex;
      flex-direction: column;
      justify-content: flex-start;
      align-items: center;
      margin-top: 212px;
      p {
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #66686b;
        line-height: 20px;
        -webkit-touch-callout: none;
        -webkit-user-select: none;
        -khtml-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
        user-select: none;
      }
    }
  }
}
.limit-wrap {
  width: 95%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
@keyframes shake {
  0% {
    transform: rotateZ(2deg);
  }
  25% {
    transform: rotateZ(-2deg);
  }
  50% {
    transform: rotateZ(2deg);
  }
  75% {
    transform: rotateZ(-2deg);
  }
  100% {
    transform: rotateZ(0);
  }
}

.sync-btn.shake {
  animation-name: shake;
  animation-duration: 0.3s;
  animation-direction: alternate;
}
</style>
