<!--
 * @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侧同步过去的标签进行修改。
          </p>
        </div>
      </div>
    </div>
    <div class="bottom">
      <ul class="tag-category">
        <li v-for="item in tagCategory" :key="item.id" :class="[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" /><el-select class="w-168 m-l-10" v-model="conditionObj.statusFlag" placeholder="全部同步状态" clearable @change="changeCondition">
              <el-option label="有效" value="1"></el-option>
              <el-option label="失效" value="0"></el-option>
            </el-select>
          </div>
          <div class="btn-group">
            <el-button @click="$router.push('/syncHistory')">同步历史</el-button>
            <el-button @click="handlePartSync" type="primary" :class="['sync-btn', isShake ? 'shake' : '']">待开启同步标签（ {{ tagIds.length }} ）</el-button>
          </div>
        </div>
        <div class="tag-content-bottom">
          <el-table 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"></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="qywxTagName">
              <template slot-scope="{ row }">
                <span>{{ row.syncFlag || '--' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" prop="syncFlag">
              <template slot-scope="{ row }">
                <p v-if="row.syncFlag == 1">
                  <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 title="我是标题" :visible.sync="drawer" :direction="direction" :before-close="handleClose">
            <span>我来啦!</span>
          </el-drawer>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { tagCategoryList, tagList, syncSet, closeSync } from '@/api/memberTag';
import errMsg from '@/common/js/error';
export default {
  name: 'app-detail',
  props: {
    brandId: {
      type: String,
      default() {
        return '';
      }
    },
    tabType: {
      type: String,
      default() {
        return '1';
      }
    },
    activeGroupId: {
      type: String,
      default() {
        return '';
      }
    }
  },
  mounted() {
    this.brandId && this.getTagCategoryList();
    this.brandId && this.getTableList();
    this.$emit('showTab', '15');
  },
  data() {
    return {
      tableData: [],
      tagCategory: [],
      tagCategoryId: '',
      tableList: [],
      tagIds: [],
      search: '',
      wxEnterpriseId: JSON.parse(localStorage.getItem('userInfos')).wxEnterpriseId,
      pageSize: 20,
      currentPage: 1,
      total: 0,
      drawer: false,
      isShake: false
    };
  },
  methods: {
    getTagCategoryList() {
      tagCategoryList({ enterpriseId: 'ff8080815dacd3a2015dacd3ef5c0000' }).then(res => {
        this.tagCategory = res.data.result;
      });
    },
    getTableList() {
      let params = {
        wxEnterpriseId: 'ca66a01b79474c40b3e7c7f93daf1a3b',
        classifyId: this.tagCategoryId,
        enterpriseId: 'ff8080815dacd3a2015dacd3ef5c0000',
        pageSize: this.pageSize,
        pageNum: this.currentPage
        // search: this.search
        // enterpriseId: this.brandId,
        // classifyId: this.tagCategoryId,
        // wxEnterpriseId: this.wxEnterpriseId
      };
      tagList(params).then(res => {
        this.total = res.data.result.totalCount;
        // this.tableData = this.tableData.map(el => {
        //   this.$set(el, 'popoverFlag', false);
        //   this.$set(el, 'expend', false);
        //   return el;
        // });
        res.data.result.result.map(el => {
          el.popoverFlag = false;
          el.expend = false;
        });
        this.tableData = res.data.result.result;
      });
    },
    // 开启同步接口
    openSync(type, ids) {
      let id;
      let that = this;
      id = ids.toString();
      let params = {
        wxEnterpriseId: 'ca66a01b79474c40b3e7c7f93daf1a3b',
        tagIds: id,
        enterpriseId: 'ff8080815dacd3a2015dacd3ef5c0000'
      };
      syncSet(params)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            if (type == 'part') {
              if (that.tagIds.some(el => !el.tagItems || !el.tagItems.length)) that.$message.success('批量同步完成，没有标签值的标签将不会被同步');
              else that.$message.success('批量同步完成');
            }
            that.getTableList();
          } else {
            errMsg.errorMsg(resData);
          }
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    // 关闭同步接口
    closeSync(row) {
      let that = this;
      let params = {
        wxEnterpriseId: 'ca66a01b79474c40b3e7c7f93daf1a3b',
        memberTagId: row.tagId,
        enterpriseId: 'ff8080815dacd3a2015dacd3ef5c0000'
        // enterpriseId: this.brandId,
        // memberTagId: id,
        // 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) {
      row.popoverFlag = false;
      if (!row.tagItems || !row.tagItems.length) return this.$message.warning('该标签没有标签值，无法同步');
      this.closeSync(row);
    },
    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(row) {
      this.isShake = true;
      this.tagIds = row;
      setTimeout(() => (this.isShake = false), 300);
    },
    rowCheckChange(row, column, event) {
      this.$refs.table.toggleRowSelection(row);
    },
    // 处理批量同步
    handlePartSync() {
      if (!this.tagIds.length) return this.$message.warning('请先选择需要同步的标签');
      this.tagIds = this.tagIds.filter(el => !el.syncFlag); // 过滤掉已经同步的标签
      if (!this.tagIds.length) return this.$message.warning('请选择未同步过的标签');
      let ids = this.tagIds.map(el => el.tagId);
      this.openSync('part', ids);
    }
  },
  watch: {
    // 仅第一次赋值brandId调用
    brandId: function(newData) {
      this.getTagCategoryList();
      this.getTableList();
    }
  }
};
</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;
  }
}
.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;
}
.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;
        border-bottom: 1px solid #e4e7ed;
      }
      .tag-content-bottom {
        padding: 20px 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;
          }
        }
      }
    }
  }
}
.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>
