<!--
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2019-03-20 14:36:37
 * @LastEditors: 无尘
 * @LastEditTime: 2020-06-24 16:43:48
 -->

<!--
  我的顾客应用：
  <app-detail ></app-detail>
 -->
<template>
  <div class="app-detail-wrap">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="会员分组列表" name="first">
        <div class="app-detail-pane border-box p-20">
          <div class="condition-wrap flex flex-space-between">
            <div>
              <el-input placeholder="请输入分组名称" v-model="conditionObj.searchInput" class="w-264" style="width: 217px;" prefix-icon="el-icon-search" @keyup.native="value => toInput(value, conditionObj.searchInput)" clearable @clear="clearInput"></el-input
              ><el-select class="w-168 m-l-10" v-model="conditionObj.classifyName" placeholder="全部分类" @change="changeCondition">
                <el-option label="全部分类" value=""></el-option>
                <el-option v-for="item in classifyList" :key="item" :label="item" :value="item"> </el-option> </el-select
              ><el-select class="w-168 m-l-10" v-model="conditionObj.effectiveStatus" placeholder="全部状态" @change="changeCondition">
                <el-option label="全部状态" value=""></el-option>
                <el-option label="有效" value="1"></el-option>
                <el-option label="失效" value="0"></el-option>
              </el-select>
            </div>
            <div>
              <el-checkbox v-model="overTimeSeeFlag" @change="saveGroupSet"></el-checkbox>
              <el-tooltip class="item" effect="dark" content="开启后，GIC中设置的好办端会员分组到期后，好办移动端将不再展示该条分组" placement="top-start"> <span style="cursor: pointer;padding-bottom: 2px; border-bottom: 1px dashed #2F54EB;" class="font-14 color-606266 m-r-20">会员分组到期后不展示</span></el-tooltip>
              <el-button type="primary" :loading="loadingBtn" @click="toSync">立即同步</el-button>
              <span v-if="syncDate" class="font-14 color-606266 p-r-10">最近一次同步时间：{{ syncDate | formatTimeStamp }}</span>
            </div>
          </div>
          <div class="m-t-20">
            <el-table class="select-table" ref="multipleTable" v-loading="loading" :data="groupListData" tooltip-effect="dark" :style="{ width: '100%' }">
              <el-table-column label="分组名称" width="120" show-overflow-tooltip>
                <template slot-scope="scope">{{ scope.row.groupName }}</template>
              </el-table-column>
              <el-table-column prop="" label="分类">
                <template slot-scope="scope">{{ scope.row.memberTagGroupClassifyName }}</template>
              </el-table-column>
              <el-table-column prop="" label="是否实时" show-overflow-tooltip>
                <template slot-scope="scope">{{ scope.row.isRealTime == 1 ? '是' : '否' }}</template>
              </el-table-column>
              <el-table-column prop="" label="更新频率" show-overflow-tooltip>
                <template slot-scope="scope"
                  >{{ scope.row.updateType == 1 ? '每日' : scope.row.updateType == 2 ? '每周' : scope.row.updateType == 3 ? '每月' : '-' }} {{ scope.row.updateType == 1 ? '一次' : scope.row.updateType == 2 ? '周' + scope.row.updateDay : scope.row.updateType == 3 ? scope.row.updateDay + '号' : '-' }}
                </template>
              </el-table-column>
              <el-table-column prop="" label="状态" show-overflow-tooltip>
                <template slot-scope="scope">{{ scope.row.effectiveStatus == '1' ? '有效' : '失效' }}</template>
              </el-table-column>
              <el-table-column prop="" label="覆盖人数" show-overflow-tooltip>
                <template slot-scope="scope"
                  >{{ scope.row.memberCount || 0 }}人</template
                >
              </el-table-column>
              <el-table-column prop="" label="到期时间" show-overflow-tooltip>
                <template slot-scope="scope">
                  <div class="line-18">{{ scope.row.effectiveDate | timeStampToYmd }}</div>
                  <div class="line-18">{{ scope.row.effectiveDate | timeStampToHms }}</div>
                </template>
              </el-table-column>
              <!-- <el-table-column>
                <template slot="header" slot-scope="scope">
                  <el-tooltip class="item" effect="dark" content="仅可编辑能在好办展示的分组" placement="right">
                    <span style="cursor: pointer;padding-bottom: 2px; border-bottom: 1px dashed #2F54EB;">操作</span>
                  </el-tooltip>
                </template>
                <template slot-scope="scope">
                  <el-button type="text" size="small" @click="toEditGroup(scope.$index, scope.row)">编辑分组可见范围</el-button>
                </template>
              </el-table-column> -->
            </el-table>
            <div class="block common-wrap__page text-right m-t-24" v-if="groupListData.length != 0">
              <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>
      </el-tab-pane>
      <el-tab-pane label="分组展示设置" name="second">
        <div class=" border-box p-20">
          <div class="flex flex-space-between">
            <div></div>
            <div><span class="font-12 color-909399">最多新建20个模板</span><el-button :disabled="templateList.length >= 20" class="m-l-20" type="primary" @click="addTemplate">新建模版</el-button></div>
          </div>
          <div class="m-t-20">
            <el-table class="select-table" ref="tempTable" v-loading="loading" :data="templateList" tooltip-effect="dark" :style="{ width: '100%' }">
              <el-table-column label="模板名称" show-overflow-tooltip>
                <template slot-scope="scope">{{ scope.row.templateName }}</template>
              </el-table-column>
              <el-table-column label="模板id" show-overflow-tooltip>
                <template slot-scope="scope">{{ scope.row.templateId }}</template>
              </el-table-column>
              <el-table-column label="编辑人" show-overflow-tooltip>
                <template slot-scope="scope">{{ scope.row.editPerson }}</template>
              </el-table-column>
              <el-table-column prop="" label="最近编辑时间" show-overflow-tooltip>
                <template slot-scope="scope">
                  <div class="line-18">{{ scope.row.editTIme | timeStampToYmd }}</div>
                  <div class="line-18">{{ scope.row.editTIme | timeStampToHms }}</div>
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button @click="toEdit(scope.$index, scope.row)" type="text">编辑</el-button>
                  <el-button @click="toStore(scope.$index, scope.row)" type="text">门店范围设置</el-button>
                  <el-button @click="toDel(scope.$index, scope.row)" type="text">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
<script>
import showMsg from '@/common/js/showmsg';
import errMsg from '@/common/js/error';
import { _debounce } from '@/common/js/public';
import { postRequest } from '@/api/api';
export default {
  name: 'app-detail',
  props: {
    brandId: {
      type: String,
      default() {
        return '';
      }
    },
    tabType: {
      type: String,
      default() {
        return '1';
      }
    },
    activeGroupId: {
      type: String,
      default() {
        return '';
      }
    }
  },
  data() {
    return {
      projectName: '', // 当前项目名
      activeName: 'first',
      activeGroup: this.activeGroupId, // 商户(品牌) groupId
      wxEnterpriseRelatedId: localStorage.getItem('userInfos') ? JSON.parse(localStorage.getItem('userInfos')).wxEnterpriseId : '',
      myCustomData: {
        searchFlag: false,
        chatFlag: false,
        mainStoreFlag: false, // 服务门店显示，1显示0不现实
        minorStoreFlag: false, // 协管门店显示，1显示0不显示
        openCardStoreFlag: false, // 开卡门店显示，1显示0不显示
        clerkSeeOtherFlag: false, // 导购查看其他导购，1显示0不显示
        isSeeAuthMember: false,
        allowGuideContact: false,
        allowGuideMobile: false,
        allowGuideMessage: false,
        allowGuideOnlineChat: false
      },
      overTimeSeeFlag: false,
      // 会员分组设置
      conditionObj: {
        searchInput: '',
        classifyName: '',
        effectiveStatus: ''
      },
      groupListData: [], // 列表数据
      classifyList: [], // 会员分组
      currentPage: 1,
      pageSize: 20,
      total: 0,
      loading: false,
      // 最近同步时间
      syncDate: '',
      loadingBtn: false,
      // 模板
      templateList: []
    };
  },
  beforeMount() {
    let that = this;
    let host = window.location.origin;
    if (host.indexOf('localhost') != -1) {
      that.baseUrl = 'http://www.gicdev.com';
    } else {
      that.baseUrl = host;
    }
  },
  methods: {
    /**
     * 删除
     */
    toDel(index, row) {
      const that = this;
      that
        .$confirm('是否要删除选中的模板?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          that.delTempList(row.templateId);
        })
        .catch(() => {});
    },
    /**
     * 删除卡券
     */
    delTempList(templateId) {
      const that = this;
      let para = {
        templateId: templateId
      };
      postRequest('/haoban-app-customer-web/del-group-template', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            showMsg.showmsg('删除成功', 'success');
            that.getTableList();
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    /**
     * 编辑
     */
    toEdit(index, row) {
      const that = this;
      that.$router.push(`/addGroupTemplate?templateId=${row.templateId}`);
    },
    /**
     * 编辑
     */
    toStore(index, row) {
      const that = this;
      that.$router.push(`/storeRangeSet?templateId=${row.templateId}`);
    },
    /**
     * 新增模板
     */
    addTemplate() {
      const that = this;
      that.$router.push('/addGroupTemplate');
    },
    /**
     * 获取模板
     */
    getTableList() {
      const that = this;
      let para = {
        enterpriseId: that.brandId,
        wxEnterpriseRelatedId: that.wxEnterpriseRelatedId
      };
      postRequest('/haoban-app-customer-web/get-template-list', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            that.templateList = resData.result || [];
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    /**
     * 切换tab
     */
    handleClick(tab, event) {
      const that = this;
      that.currentPage = 1;
      that.pageSize = 20;
      that.total = 0;
      if (tab.name == 'first') {
        that.getGroupClassify();
        that.getGroupList();
        that.getGroupClassSet();
        that.getSyncDate();
      } else {
        that.getTableList();
      }
    },
    /**
     * 获取同步时间
     */
    getSyncDate(brandId) {
      const that = this;
      let para = {
        enterpriseId: that.brandId,
        wxEnterpriseRelatedId: that.wxEnterpriseRelatedId
      };
      postRequest('/haoban-app-customer-web/memberGroup/get-group_last_syn_time', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            that.syncDate = resData.result;
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    /**
     * 立即同步
     */
    toSync: _debounce(function() {
      const that = this;
      that.loadingBtn = true;
      let para = {
        enterpriseId: that.brandId,
        wxEnterpriseRelatedId: that.wxEnterpriseRelatedId
      };
      postRequest('/haoban-app-customer-web/memberGroup/syn-group', para)
        .then(res => {
          let resData = res.data;
          that.loadingBtn = false;
          if (resData.errorCode == 1) {
            showMsg.showmsg('同步成功', 'success');
            that.getSyncDate();
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.loadingBtn = false;
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    }, 500),

    /**
     * 获取分组设置
     */
    getGroupClassSet(brandId) {
      const that = this;
      let para = {
        enterpriseId: that.brandId,
        wxEnterpriseRelatedId: that.wxEnterpriseRelatedId
      };
      postRequest('/haoban-app-customer-web/memberGroup/get-member-group-setting', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            that.overTimeSeeFlag = resData.result == 0 ? false : true;
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    /**
     * 保存分组设置
     */
    saveGroupSet() {
      const that = this;
      let para = {
        enterpriseId: that.brandId,
        wxEnterpriseRelatedId: that.wxEnterpriseRelatedId,
        overTimeSeeFlag: that.overTimeSeeFlag == true ? 1 : 0
      };
      postRequest('/haoban-app-customer-web/memberGroup/save-member-group-setting', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            showMsg.showmsg('设置成功', 'success');
            return false;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    /**
     * 输入
     */
    toInput: _debounce(function(e, value) {
      const that = this;
      that.currentPage = 1;
      that.getGroupList(that.brandId);
    }, 500),
    // 搜索清除
    clearInput() {
      const that = this;
      that.currentPage = 1;
      that.getGroupList(that.brandId);
    },
    changeCondition() {
      const that = this;
      that.currentPage = 1;
      that.getGroupList(that.brandId);
    },
    /**
     * 获取会员分组分类
     */
    getGroupClassify(brandId) {
      const that = this;
      let para = {
        enterpriseId: that.brandId,
        wxEnterpriseRelatedId: that.wxEnterpriseRelatedId
      };
      postRequest('/haoban-app-customer-web/memberGroup/get-member-class-list', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            that.classifyList = resData.result.list || [];
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },

    /**
     *  模板消息设置
     */
    toChangeTemp(e, index, row) {
      const that = this;
      console.log(e, index, row);
      let para = {
        enterpriseId: that.brandId,
        wxEnterpriseRelatedId: that.wxEnterpriseRelatedId,
        memberTagGroupId: row.memberTagGroupId,
        isSendTemplate: row.isSendTemplate == true ? 1 : 0
      };
      postRequest('/haoban-app-customer-web/memberGroup/save-member-group-is-template-message', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            showMsg.showmsg('操作成功', 'success');
            that.pageNum = 1;
            that.getGroupList(that.brandId);
            return;
          } else {
            row.isSendTemplate = false;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },

    /**
     * 分页---页码变化
     */
    handleSizeChange(val) {
      const that = this;
      that.pageSize = val;
      that.getGroupList(that.brandId);
    },

    /**
     * 分页---当前页变化
     */
    handleCurrentChange(val) {
      const that = this;
      that.currentPage = val;
      that.getGroupList(that.brandId);
    },

    /**
     * 获取会员分组列表
     */
    getGroupList(brandId) {
      const that = this;
      that.loading = true;
      let para = {
        enterpriseId: that.brandId,
        wxEnterpriseRelatedId: that.wxEnterpriseRelatedId,
        memberGroupName: that.conditionObj.searchInput,
        classifyName: that.conditionObj.classifyName,
        effectiveStatus: that.conditionObj.effectiveStatus,
        pageNum: that.currentPage,
        pageSize: that.pageSize
      };
      postRequest('/haoban-app-customer-web/memberGroup/member-tag-group-list', para)
        .then(res => {
          let resData = res.data;
          that.loading = false;
          if (resData.errorCode == 1) {
            if (resData.result.list && resData.result.list.length) {
              resData.result.list.forEach(ele => {
                ele.isSendTemplate = ele.isSendTemplate == 1 ? true : false;
              });
            }
            that.groupListData = resData.result.list || [];
            that.total = resData.result.pageInfo.total;
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.loading = false;
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    }
  },
  watch: {
    brandId: function(newData, oldData) {
      const that = this;
      if (newData) {
        that.getGroupClassify(that.brandId);
        that.getGroupList(that.brandId);
        that.getGroupClassSet(that.brandId);
        that.getSyncDate(that.brandId);
      }
    }
  },
  mounted() {
    const that = this;
    that.$emit('showTab', '12');
    if (that.brandId) {
      that.getGroupClassify(that.brandId);
      that.getGroupList(that.brandId);
      that.getGroupClassSet(that.brandId);
      that.getSyncDate(that.brandId);
    }
    if (!!that.$route.query.tabName && that.brandId) {
      that.activeName = 'second';
      that.getTableList();
    }
  },
  components: {}
};
</script>
<style lang="less" scoped>
.w-500 {
  width: 500px;
}

.w-168 {
  width: 168px;
}

.w-195 {
  width: 195px;
}

.color-1890ff {
  color: #2f54eb;
}

.p-20 {
  padding: 20px;
}

.p-l-38 {
  padding-left: 38px;
}

.p-l-199 {
  padding-left: 199px;
}

.m-l-20 {
  margin-left: 20px;
}

.app-detail-wrap {
  height: 100%;
  background: #fff;
  .el-tabs {
    background: #fff;
    /deep/ .el-tabs__nav-wrap {
      /* height: 48px;
    line-height: 48px; */
      &::after {
        height: 1px;
      }
      /* .el-tabs__nav-scroll {
      padding-left: 20px;
    } */
    }
  }
  .condition-tip {
    width: 740px;
    .el-alert--info {
      background: #e6f7ff;
      border: 1px solid rgba(145, 213, 255, 1);
      .el-alert__icon {
        font-size: 12px;
      }
    }
  }
}
</style>
