<!--
 * @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>
                </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';
      }
    },
    activeGroupId: {
      type: String,
      default() {
        return '';
      }
    }
  },
  data() {
    return {
      projectName: '', // 当前项目名
      wxEnterpriseRelatedId: localStorage.getItem('userInfos') ? JSON.parse(localStorage.getItem('userInfos')).wxEnterpriseId : '',
      editPerson: localStorage.getItem('userInfos') && JSON.parse(localStorage.getItem('userInfos')).staffDTO ? JSON.parse(localStorage.getItem('userInfos')).staffDTO.staffName : '',
      formData: {
        templateId: '',
        templateName: '',
        groupIds: []
      },
      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
    };
  },
  methods: {
    /**
     * 确认新建
     */
    submitForm: _debounce(function(formName) {
      const that = this;
      that.loadingBtn = true;
      if (that.tableData.length) {
        that.formData.groupIds = that.tableData.map(ele => ele.memberTagGroupId);
      }

      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(','),
        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(() => {
          that.tableData.splice(index, 1);
          if (that.tableData.length) {
            that.formData.groupIds = that.tableData.map(ele => ele.memberTagGroupId);
          }
        })
        .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: []
                };
                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);
      }
    }
  },
  mounted() {
    const that = this;
    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>
