<!--
 * @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">
      <el-alert type="info" show-icon :closable="false">
        <span class="alert-info">
          1. 标签同步是将GIC标签同步至企微，并且可以在企业微信-客户详情里打GIC标签；<br />
          2. GIC标签指的是导购手动标签维护，会员分组不包含在内；<br />
          3. 如果需要同步标签，请选择开启某个标签组同步；如果GIC标签未在好办显示，可能存在更新问题，请选择手动刷新；<br />
          4. 同步开启每个标签组每日最多两次。
        </span>
      </el-alert>
    </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">
          <el-input v-model="search" placeholder="请输入内容" style="width: 223px" prefix-icon="el-icon-search" />
          <div class="btn-group">
            <el-button @click="$router.push('/syncHistory')">同步历史</el-button>
            <el-button @click="handlePartSync">批量同步</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">
            <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 }">
                <span class="tag-val" v-for="item in row.tagItems.slice(0, 4)" :key="item.tagItemId">{{ item.tagItemName }}</span>
                <el-button class="expendBtn" type="text" v-if="row.tagItems.length > 4" @click="expendTag(row)">{{ row.expend ? '收起' : '展开' }}</el-button>
              </template>
            </el-table-column>
            <el-table-column label="对应企微标签" prop="qywxTagName">
              <template slot-scope="{ row }">
                <span>{{ row.qywxTagName || '--' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="同步" prop="syncFlag">
              <template slot-scope="{ row }">
                <el-popover placement="top" width="300" v-model="row.popoverFlag" v-if="row.syncStatus != 1">
                  <p style="color: #303133;line-height: 22px;">{{ !row.syncFlag ? '开启后，将同步GIC导购标签到企微。' : '关闭后，GIC标签将不会同步到企微。？' }}</p>
                  <p style="color: #909399;line-height: 22px;">{{ !row.syncFlag ? '注：随意更改设置将会影响同步标签的使用' : '历史标签库及企业微信所打的标签将会删除' }}</p>
                  <div style="margin: 15px 0 0;display:flex;align-items:center;justify-content: space-between;">
                    <span class="use-num">{{ !row.syncFlag ? '每日可同步次数：2 次' : '' }}</span>
                    <div>
                      <el-button @click="row.popoverFlag = false" class="popover-btn">取消</el-button>
                      <el-button type="primary" class="popover-btn" @click="changeSync(row)">确定</el-button>
                    </div>
                  </div>
                  <el-switch slot="reference" :value="row.syncFlag" :active-value="1" :inactive-value="0" />
                </el-popover>
                <p v-else>
                  <el-switch disabled :value="row.syncFlag" :active-value="1" :inactive-value="0" />
                  <span class="syncLoading">同步中...</span>
                </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>
        </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
    };
  },
  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 = res.data.result.result;
        this.tableData = this.tableData.map(el => {
          this.$set(el, 'popoverFlag', false);
          this.$set(el, 'expend', false);
          return el;
        });
      });
    },
    // 开启同步接口
    openSync(type, ids) {
      let id;
      let that = this;
      // 单个同步时，参数为row对象
      if (type == 'id') id = ids.tagId;
      else {
        id = ids.toString();
      }
      let params = {
        // enterpriseId: this.brandId,
        // tagIds: id,
        // wxEnterpriseId: this.wxEnterpriseId
        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('批量同步完成');
            } else {
              that.$message.success(`${ids.tagName}标签，开启同步`);
            }
            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('该标签没有标签值，无法同步');
      if (row.syncFlag == 0) this.openSync('id', row);
      else 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.tagIds = 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 {
    width: 70%;
    border-bottom: 1px solid #e4e7ed;
    /deep/ .el-alert__icon {
      font-size: 14px;
      width: auto !important;
      margin-top: -61px;
    }
    .alert-info {
      font-size: 13px;
      font-weight: 400;
      color: #303133;
      line-height: 22px;
    }
  }
  .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;
        .btn-group {
          /deep/ .el-button {
            color: #606266;
            &:hover span {
              color: #2f54eb;
            }
            span {
              font-family: Roboto-Regular, Roboto;
            }
          }
        }
      }
      .tag-content-bottom {
        padding: 20px 20px 14px;
        .tag-val {
          padding: 2px 12px;
          margin-right: 10px;
          background: #f7f8fa;
          border-radius: 2px;
          font-size: 12px;
          border: 1px solid #dcdfe6;
          text-align: center;
          line-height: 22px;
        }
        .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;
}
</style>
