<!--
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2019-06-20 14:36:37
 * @LastEditors: 无尘
 * @LastEditTime: 2020-06-29 16:53:24
 -->
<template>
  <div class="app-detail-wrap">
    <div class="app-detail-pane border-box p-20">
      <el-form :model="formData" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
        <el-form-item label="模板名称" prop="templateName">
          <limitInput :inputWidth="340" :inputValue.sync="formData.templateName" :getByType="'word'" :holder="'请输入模板名称'" :maxLength="20"> </limitInput>
        </el-form-item>
        <el-form-item label="选择分组" prop="groupIds">
          <div class="flex flex-space-between">
            <el-button type="primary" @click="showGroup">选择分组</el-button>
            <el-button type="danger" @click="multDel">批量移除</el-button>
          </div>
          <div class="m-t-20">
            <el-table ref="multipleTable" v-loading="loading" max-height="400" :data="tableData" tooltip-effect="dark" style="width: 100%" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55"> </el-table-column>
              <el-table-column label="分组名称">
                <template slot-scope="scope">
                  {{ scope.row.groupName || '--' }}
                </template>
              </el-table-column>
              <el-table-column 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 prop="" label="操作">
                <template slot-scope="scope">
                  <el-button type="text" @click="delRow(scope.$index, scope.row)">移除</el-button>
                  <dm-delete tips="确定置顶？" @confirm="isTopping(scope.$index, scope.row, 1)" v-if="isEdit && scope.row.topFlag == 0">
                    <el-button type="text" style="padding: 0 14px" :disabled="toppingNum >= 5">置顶</el-button>
                  </dm-delete>
                  <dm-delete tips="确定取消置顶？" @confirm="isTopping(scope.$index, scope.row, 0)" v-if="isEdit && scope.row.topFlag == 1">
                    <el-button type="text">取消置顶</el-button>
                  </dm-delete>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loadingBtn" @click="submitForm('ruleForm')">保存</el-button>
        </el-form-item>
      </el-form>
    </div>
    <select-group v-if="groupShow" :brandId="brandId" @closeGroup="closeGroup" @submitGroup="submitGroup"></select-group>
  </div>
</template>
<script>
import selectGroup from '@/components/app/customer/select-group.vue';
import limitInput from '@/components/limit-input.vue';
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';
      }
    }
  },
  data() {
    return {
      projectName: '', // 当前项目名
      wxEnterpriseRelatedId: sessionStorage.getItem('userInfos') ? JSON.parse(sessionStorage.getItem('userInfos')).wxEnterpriseId : '',
      editPerson: sessionStorage.getItem('userInfos') ? JSON.parse(sessionStorage.getItem('userInfos')).staffName : '',
      formData: {
        templateId: '',
        templateName: '',
        groupIds: [],
        topFlags: []
      },
      rules: {
        templateName: [{ required: true, message: '请输入模板名称', trigger: 'blur' }],
        groupIds: [{ type: 'array', required: true, message: '请选择门店分组', trigger: 'change' }]
      },
      tableData: [],
      activeId: '1',
      loading: false,
      multipleSelection: [],

      // 分页参数
      currentPage: 1,
      pageSize: 20,
      total: 0,
      groupShow: false,
      loadingBtn: false,
      toppingNum: 0,
      isEdit: false
    };
  },
  methods: {
    // 获取置顶数
    getToppingNum(val) {
      // getRequest('/haoban-app-customer-web/get-template-top-count', { templateId: this.$route.query.templateId }).then(res => {
      //   if (res.data.errorCode == 1) {
      //     this.toppingNum = res.data.result;
      //   }
      // });
      let sortList = val.filter(item => item.topFlag == 1);
      this.toppingNum = sortList.length;
    },
    // 置顶事件
    isTopping(itemIndex, item, n) {
      // let para = {
      //   memberTagGroupId: item.memberTagGroupId,
      //   templateId: this.$route.query.templateId,
      //   topFlag: n
      // };
      this.loading = true;
      // getRequest('/haoban-app-customer-web/update-template-group-topflag', para)
      //   .then(res => {
      //     if (res.data.errorCode == 1) {
      this.tableData[itemIndex].topFlag = n;
      let setItem = this.tableData[itemIndex];
      this.tableData.splice(itemIndex, 1);
      if (n == 1) {
        this.tableData.splice(0, 0, setItem);
      } else if (n == 0) {
        this.tableData.splice(this.toppingNum - 1, 0, setItem);
      }
      setTimeout(() => {
        this.loading = false;
        this.$message.success('操作成功！');
      }, 500);
      // this.getTemplateSet(this.brandId);
      // } else {
      //   this.$message.error(res.data.message);
      // }
      // })
      // .finally(() => {
      //   this.loading = false;
      // });
    },
    /**
     * 确认新建
     */
    submitForm: _debounce(function(formName) {
      const that = this;
      that.loadingBtn = true;
      if (that.tableData.length) {
        that.formData.groupIds = that.tableData.map(ele => ele.memberTagGroupId);
        that.formData.topFlags = that.tableData.map(ele => ele.topFlag);
      }

      that.$refs[formName].validate(valid => {
        if (valid) {
          that.postSave();
        } else {
          that.loadingBtn = false;
        }
      });
    }, 300),
    postSave() {
      const that = this;
      let para = {
        templateId: that.formData.templateId,
        templateName: that.formData.templateName,
        groupIds: that.tableData.map(ele => ele.memberTagGroupId).join(','),
        // topFlags: that.tableData.map(ele => ele.topFlag).join(','),
        topFlags: that.tableData.map(ele => ele.topFlag),
        editPerson: that.editPerson,
        enterpriseId: that.brandId
      };
      postRequest('/haoban-app-customer-web/save-group-template', para)
        .then(res => {
          let resData = res.data;
          that.loadingBtn = false;
          if (resData.errorCode == 1) {
            showMsg.showmsg('操作成功', 'success');
            that.$router.push(`/memberGroupSet?tabName=second`);
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.loadingBtn = false;
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    /**
     * 移除
     */
    delRow(index, row) {
      const that = this;
      that
        .$confirm(`确认要删除吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          this.loading = true;
          that.tableData.splice(index, 1);
          if (that.tableData.length) {
            that.formData.groupIds = that.tableData.map(ele => ele.memberTagGroupId);
          }
          setTimeout(() => {
            this.loading = false;
          }, 500);
        })
        .catch(() => {});
    },
    /**
     * 批量删除
     */
    multDel() {
      const that = this;
      if (!that.multipleSelection.length) {
        that.$message.error({
          duration: 1000,
          message: '请选择删除项'
        });
        return false;
      }
      const ids = that.multipleSelection.map(ele => ele.memberTagGroupId);
      let arr = [];
      that.tableData.forEach(ele => {
        if (ids.indexOf(ele.memberTagGroupId) == -1) {
          arr.push(ele);
        }
      });
      that.tableData = arr;
      if (that.tableData.length) {
        that.formData.groupIds = that.tableData.map(ele => ele.memberTagGroupId);
      }
    },

    /**
     * 多选分组
     */
    handleSelectionChange(val) {
      const that = this;
      that.multipleSelection = val;
    },
    /**
     * 显示分组
     */
    showGroup() {
      const that = this;
      that.groupShow = true;
    },
    closeGroup() {
      const that = this;
      that.groupShow = false;
    },
    submitGroup(arr) {
      const that = this;
      that.groupShow = false;
      const ids = that.tableData.map(ele => ele.memberTagGroupId);
      arr.forEach(ele => {
        if (ids.indexOf(ele.memberTagGroupId) == -1) {
          that.tableData.push(ele);
        }
      });
      that.formData.groupIds = that.tableData.map(ele => ele.memberTagGroupId);
      that.$refs['ruleForm'].validate(valid => {
        if (valid) {
          return;
        }
      });
    },

    /**
     * 获取数据
     */
    getTemplateSet(brandId) {
      const that = this;
      let para = {
        templateId: that.$route.query.templateId,
        enterpriseId: that.brandId
        // wxEnterpriseRelatedId: that.wxEnterpriseRelatedId
      };
      postRequest('/haoban-app-customer-web/get-template-detail', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            if (resData.result) {
              resData.result.template.groupIds = resData.result.groupList.map(ele => ele.memberTagGroupId) || [];
              that.formData = resData.result.template;
              that.tableData = resData.result.groupList || [];
              if (resData.result.template.enterpriseId != that.brandId) {
                that.formData = {
                  templateId: '',
                  templateName: '',
                  groupIds: [],
                  topFlags: []
                };
                that.tableData = [];
              }
            }
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    }
  },
  watch: {
    brandId: function(newData, oldData) {
      const that = this;
      if (newData && !!that.$route.query.templateId) {
        that.getTemplateSet(that.brandId);
      }
    },
    tableData: {
      handler: function(val) {
        const that = this;
        if (val) {
          if (that.isEdit) {
            that.getToppingNum(val);
          }
        }
      },
      deep: true
    }
  },
  mounted() {
    const that = this;
    that.isEdit = that.$route.query.templateId ? true : false;
    that.$emit('showTab', '12');
    if (that.brandId && !!that.$route.query.templateId) {
      that.getTemplateSet(that.brandId);
    }
  },
  components: { selectGroup, limitInput }
};
</script>
<style lang="scss" scoped>
.w-500 {
  width: 500px;
}

.w-195 {
  width: 195px;
}

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

.p-20 {
  padding: 20px;
}

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

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

.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>
