<template>
  <section class="dm-form__wrap black-list">
    <div class="top">
      <div class="left">
        <el-input v-model="search.phone" placeholder="请输入手机号码" prefix-icon="el-icon-search" style="width: 260px" @change="getTableData" />
        <el-date-picker v-model="search.time" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" @change="getTableData"> </el-date-picker>
      </div>
      <div class="right">
        <el-button type="primary" @click="dialogData.visible = true">添加黑名单客户</el-button>
      </div>
    </div>
    <div class="content mt20">
      <el-table :data="tableData.data" element-loading-text="拼命加载中">
        <el-table-column v-for="(v, i) in tableData.tableHeader" :key="i" :prop="v.prop" :min-width="v.minWidth" :label="v.label" :formatter="v.formatter" :fixed="v.fixed" show-overflow-tooltip>
          <template slot-scope="scope">
            <span v-if="v.formatter" v-html="v.formatter(scope.row)"></span>
            <span v-else>{{ scope.row[v.prop] || '--' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="{ row }">
            <el-button type="text" @click="removeBlack(row.blackId)">移出黑名单</el-button>
          </template>
        </el-table-column>
      </el-table>
      <dm-pagination background class="dm-pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="tableData.currentPage" :page-sizes="tableData.pageSizeList" :page-size="tableData.pageSize" layout="total, sizes, prev, pager, next" :total="tableData.total" hide-on-single-page />
    </div>
    <el-dialog :visible.sync="dialogData.visible" :title="dialogTitle" width="600px" @close="resetDialog">
      <el-form v-if="!isExiteErrorPhone" ref="form" :model="dialogData.form" :rules="dialogData.form.rules" label-width="110px">
        <el-form-item label="黑名单内容：" prop="phoneList">
          <el-input type="textarea" v-model="dialogData.form.phoneList" placeholder="回车换行，一行输入一个手机号码，最多可以添加1000个号码" :rows="4" show-word-limit class="w410" resize="none" />
        </el-form-item>
        <el-form-item label="填写添加原因：" prop="reasonType">
          <el-radio-group v-model="dialogData.form.reasonType">
            <el-radio :label="0">用户向店员反馈</el-radio>
            <el-radio :label="1">其他</el-radio>
          </el-radio-group>
          <el-input v-if="dialogData.form.reasonType" type="textarea" v-model="dialogData.form.reason" placeholder="请输入原因内容" :maxlength="200" :rows="4" show-word-limit class="w410 mt8" resize="none" />
        </el-form-item>
        <div class="btn_group">
          <el-button @click="dialogData.visible = false">取消</el-button>
          <el-button type="primary" @click="submit">确认</el-button>
        </div>
      </el-form>
      <div v-else>
        <ul class="errorList">
          <li v-for="(item, index) in dialogData.form.errorPhoneList" :key="index">{{ item }}</li>
        </ul>
        <div class="btn_group" style="margin: 30px 0 10px">
          <span class="tips"><i class="iconfont icon-tishi"></i>异常名单将会自动过滤，请自行记录。</span>
          <el-button type="primary" @click="dialogData.visible = false">确认</el-button>
        </div>
      </div>
    </el-dialog>
  </section>
</template>

<script>
import { formatDateTimeByType } from '@/utils';
import { getBlackList, addBlackList, removeBlackList } from '@/service/api/messageApi';
export default {
  name: 'blackList',
  created() {
    this.getTableHeader();
    this.getTableData();
  },
  data() {
    const validateReason = (rules, value, cb) => {
      const { reasonType, reason } = this.dialogData.form;
      if (reasonType) {
        if (reason) cb();
        else cb(new Error('请填写添加黑名单原因'));
      } else cb();
    };
    const validateList = (rules, value, cb) => {
      const res = value.trim();
      if (!res) return cb(new Error('请填写内容'));
      else cb();
    };
    return {
      search: {
        phone: '',
        time: []
      },
      tableData: {
        data: [],
        currentPage: 1,
        pageSizeList: [20, 40, 60, 80],
        pageSize: 20,
        tableHeader: [],
        total: 0
      },
      dialogData: {
        title: '添加黑名单用户',
        visible: false,
        form: {
          rules: {
            phoneList: { validator: validateList, trigger: 'blur' },
            reasonType: { validator: validateReason, trigger: 'blur' }
          },
          phoneList: '',
          reasonType: 0,
          reason: '',
          errorPhoneList: []
        }
      }
    };
  },
  methods: {
    // table methods
    getTableHeader() {
      this.tableData.tableHeader = [
        { label: '手机号', prop: 'phoneNumber' },
        { label: '黑名单原因', prop: 'reason' },
        {
          label: '添加时间',
          prop: 'createTime',
          formatter(scope) {
            return `<span>${formatDateTimeByType(scope.createTime, 'yyyy-MM-dd-HH-mm-ss', true).y}<br />${formatDateTimeByType(scope.createTime, 'yyyy-MM-dd-HH-mm-ss', true).h}</span>`;
          }
        },
        { label: '操作人', prop: 'creatorName' }
      ];
    },
    async getTableData() {
      const { currentPage, pageSize } = this.tableData;
      const { phone, time } = this.search;
      const para = {
        currentPage,
        pageSize,
        phoneNumber: phone,
        startTime: Array.isArray(time) && time[0] ? formatDateTimeByType(time[0], 'yyyy-MM-dd-HH-mm-ss', true).y : '',
        endTime: Array.isArray(time) && time[1] ? formatDateTimeByType(time[1], 'yyyy-MM-dd-HH-mm-ss', true).y : ''
      };
      const result = await getBlackList(para);
      this.tableData.data = result.result.result || [];
      this.tableData.total = result.result.totalCount || 0;
    },
    handleSizeChange(val) {
      this.tableData.pageSize = val;
      this.tableData.currentPage = 1;
      this.getTableData();
    },
    handleCurrentChange(val) {
      this.tableData.currentPage = val;
      this.getTableData();
    },
    //  other
    submit() {
      this.$refs.form.validate(async value => {
        if (value) {
          const para = {};
          const { reason, reasonType } = this.dialogData.form;
          para.phoneNumber = this.validatePhoneList();
          para.reasonType = reasonType;
          para.reason = reasonType ? reason : '用户向店员反馈';
          if (para.phoneNumber) {
            await addBlackList(para);
            if (!this.isExiteErrorPhone) {
              this.$tips({ type: 'success', message: '添加成功' });
              this.dialogData.visible = false;
            } else {
              this.$tips({ type: 'warning', message: '部分添加成功' });
            }
            this.getTableData();
          } else {
            this.$tips({ type: 'error', message: '添加失败,无正确的手机号' });
          }
        }
      });
    },
    validatePhoneList() {
      // 返回正确手机号的Array
      const reg = /^1[0-9]{10}$/;
      const arr = this.dialogData.form.phoneList.split('\n');
      this.dialogData.form.errorPhoneList = arr.filter(el => el.trim() && !reg.test(el.trim()));
      const result = arr.filter(el => reg.test(el.trim())).map(el => el.trim());
      if (result.length > 1000) result.length = 1000;
      return result.toString();
    },
    resetDialog() {
      this.dialogData.form.reason = '';
      this.dialogData.form.reasonType = 0;
      this.dialogData.form.phoneList = '';
      this.dialogData.form.errorPhoneList = [];
    },
    removeBlack(v) {
      this.$confirm('确认将该手机号移出黑名单吗？', '提示', {
        confirmButtonText: '确认',
        cancelBUttonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          await removeBlackList({ blackId: v });
          this.$tips({ type: 'success', message: '移出成功' });
          this.getTableData();
        })
        .catch(() => {});
    }
  },
  computed: {
    isExiteErrorPhone() {
      return this.dialogData.form.errorPhoneList.length;
    },
    dialogTitle() {
      return this.isExiteErrorPhone ? '手机号码格式异常名单' : this.dialogData.title;
    }
  }
};
</script>

<style scoped lang="scss">
.top {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.w410 {
  width: 410px;
}
.btn_group {
  display: flex;
  justify-content: flex-end;
}
.mt8 {
  margin-top: 8px;
}
.errorList {
  li {
    display: inline-block;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    text-align: center;
    height: 22px;
    line-height: 22px;
    width: 130px;
    background: #fff1f0;
    border-radius: 2px;
    border: 1px solid #ffa39e;
    margin: 10px 10px 0 0;
    padding: 0 5px;
    box-sizing: border-box;
    color: #f5222d;
    &:nth-child(4n) {
      margin-right: 0;
    }
  }
}
.tips {
  display: inline-block;
  width: 300px;
  height: 32px;
  line-height: 32px;
  text-align: center;
  background: #f7f8fa;
  border-radius: 2px;
  margin-right: 16px;
  box-sizing: border-box;
  padding: 0 12px;
  i {
    color: #2f54eb;
    margin-right: 5px;
  }
}
</style>
<style lang="scss">
.el-tooltip__popper {
  max-width: 60% !important;
}
</style>
