<!--
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2019-06-20 14:36:37
 * @LastEditors: 无尘
 * @LastEditTime: 2020-06-23 14:05:58
 -->
<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" 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 class="block common-wrap__page text-right" v-if="tableData.length != 0">
              <dm-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-size="pageSize" layout="total, prev, pager, next" :total="total"> </dm-pagination>
            </div>
          </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: {
        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/cardCoupon/add-card-coup', 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);
        })
        .catch(() => {});
    },
    /**
     * 批量删除
     */
    multDel() {
      const that = this;
      if (!that.multipleSelection.length) {
        that.$message.error({
          duration: 1000,
          message: '请选择删除项'
        });
        return false;
      }
      that.postMultDel();
    },
    postMultDel() {
      const that = this;
      let para = {
        search: that.conditionObj.searchInput || '', // 搜索字段
        storeIds: that.multipleSelection.map(ele => ele.storeId).join(',') || '' // 门店分组,数组
      };
      postRequest('/haoban-app-tel-task-three-web/task/batch-del-store-task-list', 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
          });
        });
    },
    /**
     * 多选分组
     */
    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;
      that.tableData = arr;
      that.formData.groupIds = that.tableData.map(ele => ele.memberTagGroupId);
    },
    /**
     * 分页---页码变化
     */
    handleSizeChange(val) {
      const that = this;
      that.pageSize = val;
    },

    /**
     * 分页---当前页变化
     */
    handleCurrentChange(val) {
      const that = this;
      that.currentPage = val;
    },
    /**
     * 保存
     */
    submit: _debounce(function(type) {
      const that = this;
      that.loading = true;
      that.setData(type);
    }, 500),

    /**
     * 保存-API
     */
    setData(type) {
      const that = this;
      let para = {
        enterpriseId: that.brandId,
        wxEnterpriseRelatedId: that.wxEnterpriseRelatedId
        // enterpriseId: JSON.parse(localStorage.getItem('userInfos')).enterpriseId
      };
      let url;
      if (type != 'showFlag') {
        para[type] = !!that.myCustomData[type] ? 1 : 0;
        url = '/haoban-app-customer-web/customer/save-online-chat-setting';
        if (type === 'searchFlag') {
          url = '/haoban-app-customer-web/customer/save-customer-setting';
        }
      }

      postRequest(url, para)
        .then(res => {
          let resData = res.data;
          that.loading = false;
          if (resData.errorCode == 1) {
            showMsg.showmsg('保存成功', 'success');
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.loading = false;
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    /**
     * 获取全品牌搜索设置数据
     */
    getCustomerSet(brandId) {
      const that = this;
      let para = {
        enterpriseId: that.brandId,
        wxEnterpriseRelatedId: that.wxEnterpriseRelatedId
      };
      postRequest('/haoban-app-customer-web/customer/find-customer-setting', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            if (!!resData.result) {
              that.myCustomData.searchFlag = !!resData.result.searchFlag ? true : false;
            }
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    }
  },
  watch: {
    brandId: function(newData, oldData) {
      const that = this;
      that.getCustomerSet(that.brandId);
    }
  },
  mounted() {
    const that = this;
    that.$emit('showTab', '12');
    that.getCustomerSet(that.brandId);
  },
  components: { selectGroup, limitInput }
};
</script>
<style lang="less" 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;
    /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>
