<!--
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2019-03-20 14:36:37
 * @LastEditors: Drama
 * @LastEditTime: 2022-10-13 16:08:46
 -->

<!--
  我的客户应用：
  <app-detail ></app-detail>
 -->
<template>
  <div class="app-detail-pane border-box p-lbr-20">
    <div class="condition-wrap flex flex-space-between">
      <div>
        <el-input placeholder="请输入分组名称" maxlength="50" 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-if="$getButtonLimit($buttonCode.groupExpire)" :limit-code="$buttonCode.groupExpire" v-model="overTimeSeeFlag" @change="saveGroupSet" :disabled="$store.state.wxEnterpriseType">
          <el-tooltip class="item" effect="dark" content="勾选后，失效的分组不在好办小程序端展示" placement="top-start"> <span style="cursor: pointer; padding-bottom: 2px; border-bottom: 1px dashed #2f54eb; margin-left: -4px" class="font-14 color-606266 m-r-20">会员分组失效后不展示</span></el-tooltip>
        </el-checkbox>
        <el-button v-if="$getButtonLimit($buttonCode.syncGroup)" :limit-code="$buttonCode.syncGroup" type="primary" :loading="loadingBtn" @click="toSync" :disabled="$store.state.wxEnterpriseType">立即同步</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.curingFlag == 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> -->
            <div v-if="scope.row.isRealTime == 1">
              <div class="line-18">--</div>
              <div class="line-18">--</div>
            </div>
            <div v-else>
              <div class="line-18">{{ scope.row.effectiveDate | timeStampToYmd }}</div>
              <div class="line-18">{{ scope.row.effectiveDate | timeStampToHms }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="{ row }">
            <dm-delete tips="确定置顶？" @confirm="isTopping(row, 1)" v-if="row.topFlag == 0">
              <el-button type="text" style="padding: 0 14px" :disabled="toppingNum >= 5">置顶</el-button>
            </dm-delete>
            <dm-delete tips="确定取消置顶？" @confirm="isTopping(row, 0)" v-if="row.topFlag == 1">
              <el-button type="text">取消置顶</el-button>
            </dm-delete>
            <el-button type="text" @click="sortNumBtn(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>
    <el-dialog title="设置排序值" :visible.sync="setSortShow" width="450px" @close="customCancel">
      <el-form :model="sortForm" ref="sortForm" class="sortClass" label-width="80px">
        <el-form-item label="排序值" prop="sortNum" :rules="[{ required: true, message: '请输入排序值', trigger: 'blur' }]">
          <el-input-number v-model="sortForm.sortNum" placeholder="请设置大于0的数字" :controls="false" min="1"></el-input-number>
          <span class="tips">/*排序值越小越靠前*/</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="sortLoading" @click="customCancel">取消</el-button>
        <el-button :loading="sortLoading" type="primary" @click="customConfirm">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import showMsg from '@/common/js/showmsg';
import errMsg from '@/common/js/error';
import { _debounce } from '@/common/js/public';
import { postRequest, getRequest } from '@/api/api';
export default {
  name: 'app-detail',
  props: {
    brandId: {
      type: String,
      default() {
        return '';
      }
    }
  },
  data() {
    return {
      wxEnterpriseRelatedId: sessionStorage.getItem('userInfos') ? JSON.parse(sessionStorage.getItem('userInfos')).wxEnterpriseId : '',
      overTimeSeeFlag: false,
      // 会员分组设置
      conditionObj: {
        searchInput: '',
        classifyName: '',
        effectiveStatus: ''
      },
      groupListData: [], // 列表数据
      classifyList: [], // 会员分组
      currentPage: 1,
      pageSize: 20,
      total: 0,
      loading: false,
      // 最近同步时间
      syncDate: '',
      loadingBtn: false,
      toppingNum: 0,
      currentGroupId: '',
      setSortShow: false,
      sortForm: {
        sortNum: undefined
      },
      sortLoading: false
    };
  },
  methods: {
    // 设置排序值
    sortNumBtn(item) {
      this.setSortShow = true;
      this.currentGroupId = item.memberTagGroupId;
      this.sortForm.sortNum = item.sortNum || undefined;
    },
    // 设置排序值取消按钮
    customCancel() {
      this.setSortShow = false;
      this.sortForm.sortNum = undefined;
      this.currentGroupId = '';
      this.$refs.sortForm.clearValidate();
    },
    // 设置排序值确认按钮
    customConfirm() {
      this.sortLoading = true;
      this.$refs.sortForm.validate(valid => {
        if (valid) {
          let para = {
            memberTagGroupId: this.currentGroupId,
            sortNum: this.sortForm.sortNum
          };
          getRequest('/haoban-app-customer-web/memberGroup/update-tag-group-sortnum', para)
            .then(res => {
              if (res.data.errorCode == 1) {
                this.$message.success('排序成功');
                this.customCancel();
                this.getGroupList(this.brandId);
              } else {
                this.$message.error('排序失败');
              }
            })
            .finally(() => {
              this.sortLoading = false;
            });
        }
      });
    },
    // 获取置顶数
    getToppingNum() {
      getRequest('/haoban-app-customer-web/memberGroup/get-tag-group-top-count', {}).then(res => {
        if (res.data.errorCode == 1) {
          this.toppingNum = res.data.result;
        }
      });
    },
    // 置顶事件
    isTopping(item, n) {
      let para = {
        memberTagGroupId: item.memberTagGroupId,
        topFlag: n
      };
      getRequest('/haoban-app-customer-web/memberGroup/update-tag-group-topflag', para).then(res => {
        if (res.data.errorCode == 1) {
          this.$message.success('操作成功！');
          this.getGroupList(this.brandId);
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    /**
     * 获取同步时间
     */
    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
          });
        });
    },

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

    /**
     * 分页---当前页变化
     *  @param {Number} val
     */
    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) {
            that.getToppingNum();
            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 ? resData.result.pageInfo.total : 0;
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.loading = false;
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    }
  },
  mounted() {
    const that = this;
    if (that.brandId) {
      that.getGroupClassify(that.brandId);
      that.getGroupList(that.brandId);
      that.getGroupClassSet(that.brandId);
      that.getSyncDate(that.brandId);
    }
  }
};
</script>
<style lang="less">
.sortClass {
  .el-input,
  .el-input-number .el-input__inner {
    text-align: left;
  }
}
</style>
<style lang="scss" scoped>
.tips {
  margin-left: 10px;
  font-size: 12px;
  color: #909399;
}
.w-500 {
  width: 500px;
}

.w-168 {
  width: 168px;
}

.w-195 {
  width: 195px;
}

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

.p-20 {
  padding: 20px;
}
.p-lbr-20 {
  padding: 0 20px 20px 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;
    >>> .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>
