<template>
  <div id="bulkIntegral">
      <div class="contentInfo">
        <div class="flex">
          <div>
            <el-date-picker
              v-model="pickDate"
              type="daterange"
              range-separator="—"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              style="width: 400px"
              @change="onDateChange">
            </el-date-picker>
            <el-select v-model="importType" placeholder="所有导入类型" style="width: 130px;margin-left: 8px;" @change="onImportTypeChange">
              <el-option label="积分增加" value="11"></el-option>
              <el-option label="积分扣除" value="12"></el-option>
              <el-option label="等级调整" value="13"></el-option>
              <el-option label="服务门店调整" value="14"></el-option>
              <el-option label="批量冻结会员" value="15"></el-option>
              <el-option label="批量解冻会员" value="16"></el-option>
            </el-select>
          </div>
          <el-button type="primary" @click="openDialogImport">新建导入</el-button>
        </div>
        <el-table
          :data="tableData">
          <el-table-column
            prop="createTime"
            label="导入时间">
            <template slot-scope="{ row }">
              <div>{{ row.createTime | formatYMD }}</div>
              <div>{{ row.createTime | formatHMS }}</div>
            </template>
          </el-table-column>
          <el-table-column
            prop="total"
            label="预计导入数量">
            <template slot-scope="{ row }">
              {{ row.total || '0' }}
            </template>
          </el-table-column>
          <el-table-column
            prop="succeedNum"
            label="成功数">
            <template slot-scope="{ row }">
              {{ row.succeedNum || '0' }}
            </template>
          </el-table-column>
          <el-table-column
            prop="errorNum"
            label="失败数">
            <template slot-scope="{ row }">
              {{ row.errorNum || '0' }}
            </template>
          </el-table-column>
          <el-table-column
            prop="batchType"
            label="导入类型">
            <template slot-scope="{ row }">
              {{ row.batchType | formatType }}
            </template>
          </el-table-column>
          <el-table-column
            prop="operaUerName"
            label="操作人员">
            <template slot-scope="{ row }">
              {{ row.operaUerName || '--' }}
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作">
            <template slot-scope="scope">
              <el-button v-if="scope.row.errorNum > 0" @click="logDetails(scope.row)" type="text">日志详情</el-button>
              <div v-else> -- </div>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <dm-pagination
          v-if="tableData.length > 0"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page.currentPage"
          :page-sizes="[20, 40, 60, 80]"
          :page-size="page.pageSize"
          layout="total, sizes, prev, pager, next"
          :total="page.totalCount">
        </dm-pagination>
      </div>
    <!-- <vue-gic-footer></vue-gic-footer> -->

    <!-- 新建导入 -->
    <el-dialog
      title="新建导入"
      :visible.sync="dialogImport"
      width="600px"
      @closed="onDialogImportClosed">
      <!-- <el-form ref="formByImport" :model="formByImport" label-width="90px" label-suffix=":" style="margin-bottom: 36px;"> -->
      <el-form ref="formByImport" :rules="rules" :model="formByImport" label-width="90px" label-suffix=":" style="margin-bottom: 36px;">
        <el-form-item
          label="导入类型"
          prop="importValue"
          >
          <el-select v-model="formByImport.importValue" placeholder="请选择导入类型" @change="handleChangeType">
            <el-option label="积分增加" value="11"></el-option>
            <el-option label="积分扣除" value="12"></el-option>
            <el-option label="等级调整" value="13"></el-option>
            <el-option label="服务门店调整" value="14"></el-option>
            <el-option label="批量冻结会员" value="15"></el-option>
            <el-option label="批量解冻会员" value="16"></el-option>
            <!-- <el-option
              v-for="item in typeList"
              :key="item"
              :label="item"
              :value="item"
            ></el-option> -->
          </el-select>
        </el-form-item>
        <el-form-item
          label="选择文件"
          prop="file"
          required>
          <el-upload
            ref="memberUpload"
            v-loading="load"
            class="upload-demo"
            :action="actionUrl"
            accept=".xlsx"
            :file-list="formByImport.fileList"
            :before-upload="beforeUpload"
            :limit="1"
            :data="expendParams"
            :with-credentials="true"
            :on-error="handleError"
            :on-exceed="handelExceed"
            :on-change="handleChange"
            :on-success="handleSuccess"
            :auto-upload="false">
            <div slot="trigger">
              <div class="importBox">
                <i class="iconfont icon-shangchuan"></i>
                点击上传
              </div>
            </div>
            <el-button
              type="text"
              style="font-size: 12px; margin-left: 12px;"
              v-if="formByImport.importValue"
              @click="downloadTemplate">
              点击下载{{ formByImport.importValue | formatType }}模板
            </el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <div class="dialogTips">
        <h3>导入规则</h3>
        <p>1. 通过导入Excel表格的形式变更GIC已存在会员的积分等级门店；不支持导入新会员数据 </p>
        <p>2. 仅支持.xlsx 文件的导入；每次导入数据量最多为10000条；文件大小不超过1M </p>
        <p>3. 导入类型不同，文件模板也不同，请严格按照模板内容填入会员数据，否则将会报错 </p>
        <p>4. 请仔细核对需要变更的会员数据是否准确，否则GIC校验不通过将无法执行成功</p>
        <p>5. 超管账号支持导入变更全部会员信息，已分权商户的子管理员账号仅可修改管辖范围内的会员信息</p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogImport = false">取 消</el-button>
        <el-button type="primary" @click="importTable" :disable="load">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 导入成功提示 -->
    <el-dialog
      title=""
      :visible.sync="dialogSuccess"
      width="420px"
      class="dialogSuccess"
      @closed="onDialogSuccessClosed">
      <div class="success_icon"><i class="el-icon-success"></i></div>
      <p class="successHeader">新建导入任务成功！</p>
      <p class="successCon">
        请前往客户列表点击 
        <el-button
          type="primary"
          class="member-wechat-timer"
          icon="el-icon-time"
        ></el-button> 
        查看进度，
      </p>
      <p class="successCon">导入完成后可点击批量导入记录查看结果</p>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogSuccess = false" :disable="load">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { doFetchqs } from "../../components/axios/api";
import NavPath from "@/common/navbar/navbar.vue";
import url from "../../components/axios/url";
import {
  checkFalse,
  checkStatus,
  checkSuccess
} from "../../../static/js/checkStatus";

export default {
  components: {
    NavPath
  },
  filters: {
    // 时间过滤
    formatYMD(val) {
      val = new Date(val);
      let y = val.getFullYear();
      let m = (val.getMonth() + 1).toString().padStart(2, '0');
      let d = val.getDate().toString().padStart(2, '0');
      return y + '-' + m + '-' + d;
    },
    formatHMS(val) {
      val = new Date(val);
      let h = val.getHours().toString().padStart(2, '0');
      let m = val.getMinutes().toString().padStart(2, '0');
      let s = val.getSeconds().toString().padStart(2, '0');
      return h + ':' + m + ':' + s;
    },
    // 模板下载文字过滤
    formatType(val) {
      val = +val;
      switch (val) {
        case 11:
          return '积分增加';
        case 12:
          return '积分扣除';
        case 13:
          return '等级调整';
        case 14:
          return '服务门店调整';
        case 15:
          return '批量冻结会员';
        case 16:
          return '批量解冻会员';
      }
    }
  },
  data() {
    return {
      actionUrl: url.uploadExecl,
      navpath: [{ name: "首页", path: "" }, { name: "客户列表", path: "/allCustomers" }, { name: "批量导入", path: "" }],
      tableData: [],
      // 日期
      pickDate: [],
      // 搜索选项值
      importType: '',
      // 新建dialog
      dialogImport: false,
      // 表单
      formByImport: {
        importValue: '',
        fileList: [],
      },
      // 请求数据
      expendParams: {
        requestProject: 'member',
        batchType: ''
      },
      rules: {
        importValue: [{required: true, message: '请选择导入类型', trigger: 'change'}]
      },
      // 文件列表
      typeList: ['积分增加', '积分扣除'],
      rows: 0, // excel数据数量
      // 上传验证加载
      load: false,
      // 成功上传后的dialog
      dialogSuccess: false,

      // 换页
      page: {
        currentPage: 1,
        pageSize: 20,
        totalCount: 0
      }
    }
  },
  methods: {
    handleChangeType(val) {
      console.log(val);
      this.expendParams.batchType = val;
    },
    // 获取批量数据
    getIntegral() {
      let date;
      if(!this.pickDate) {
        date = ['',''];
      } else {
        date = this.pickDate
      }

      let type;
      if(this.importType) {
        type = Number(this.importType)
      } else {
        type = ''
      }
      doFetchqs(url.getBatchRecord, {
        beginTime: date[0],
        endTime: date[1],
        batchType: type,
        currentPage: this.page.currentPage,
        pageSize: this.page.pageSize
      }).then(res => {
        if (res.data.errorCode == 0) {
          let value = res.data.result;
          this.page.totalCount = value.totalCount;
          this.tableData = value.result;
          console.log(this.tableData)
        } else {
          checkFalse(res.data.message);
        }
      }).catch(err => {
        checkStatus(err);
      })
    },
    handleSizeChange(val) {
      this.page.pageSize = val;
      this.getIntegral();
    },
    handleCurrentChange(val) {
      this.page.currentPage = val;
      this.getIntegral();
    },
    // 搜索
    onImportTypeChange(val) {
      // this.importType = val;
      this.page.currentPage = 1;
      this.getIntegral();
    },
    onDateChange(val) {
      console.log(val)
      this.page.currentPage = 1;
      this.getIntegral();
    },
    // 跳转详情
    logDetails(data) {
      data = JSON.stringify(data);
      sessionStorage.setItem('bulkLogsDetail', data);
      this.$router.push({ path: '/bulkLogsDetail' });
    },
    // 打开dialog
    openDialogImport() {
      this.formByImport.importValue = '';
      this.dialogImport = true;
    },
    // 表单清除
    onDialogImportClosed() {
      this.$refs.formByImport.resetFields();
    },
    // 下载模板
    downloadTemplate() {
      window.location.href = url.downLoadExcelTemplate + '?requestProject=member&batchType=' + this.formByImport.importValue;
    },
    // 确认导入
    importTable() {
      this.$refs.formByImport.validateField('importValue' , err => {
        if(!err) {
          // console.log(this.formByImport.fileList);
          if(this.formByImport.fileList.length) {
            this.load = true;
            this.$refs.memberUpload.submit();
            // this.getIntegral();
          } else {
            checkFalse('请上传积分数据');
          }
        }
      })
    },
    // 上传验证
    beforeUpload(file) {
      // let _this = this;
      const isLt2M = file.size / 1024 / 1024 < 1;
      const types = file.name.split(".");
      const type = types[types.length - 1];
      const fileType = ["xlsx", "xlc", "xlm", "xls", "xlt", "xlw", "csv"].some(item => item === type);
      if (!fileType) {
        this.$message.warning("请上传excel表格");
        return false;
      }
      if(!isLt2M){
        this.$message.error('上传模板大小不能超过 1MB')
        return false;
      }
      // console.log(file)
      // var reader = new FileReader();
      // console.log(fileReader)
      // var fromTo;
      // FileReader.prototype.readAsBinaryString = (file) => {
      //   var binary = "";
      //   var wb; //读取完成的数据
      //   var reader = new FileReader();
      //   reader.onload = function(e) {
      //     var bytes = new Uint8Array(reader.result);
      //     var length = bytes.byteLength;
      //     for(var i = 0; i < length; i++) {
      //         binary += String.fromCharCode(bytes[i]);
      //     }
      //     wb = XLSX.read(binary, {
      //         type: 'binary'
      //     });
      //     // 遍历每张表读取
      //     for (var sheet in wb.Sheets) {
      //       if (wb.Sheets.hasOwnProperty(sheet)) {  
      //         fromTo = wb.Sheets[sheet]['!ref']; //表有几行数据
      //       }
      //     }
      //     console.log(fromTo)
      //     _this.rows = Number(fromTo.replace(/^[A-Z]+1:[A-Z]/, ''));
      //     console.log(_this.rows)
      //     this.load = false;
      //     // 接下来的操作
      //     return;
      //   }
      //   reader.readAsArrayBuffer(file);
      // }
      // reader.readAsBinaryString(file);
      // console.log(rows, fromTo)
      // var workbook;
      // fileReader.readAsBinaryString(file)
      // console.log(fileReader)
      // fileReader.onload = function(ev) {
      //   var data = ev.target.result
      //   workbook = XLSX.read(data, {  
      //       type: 'binary'  
      //   })
      // }
      // console.log(workbook)
      // var fromTo = '';
      // // 遍历每张表读取
      // for (var sheet in workbook.Sheets) {  
      //   if (workbook.Sheets.hasOwnProperty(sheet)) {  
      //     fromTo = workbook.Sheets[sheet]['!ref'];  
      //     console.log(fromTo); //表有几行数据
      //   }
      // }
    },
    handleChange(file, fileList) {
      // if(this.rows > 10000) {
      //   console.log(1)
      //   this.$message.warning('数据超过10000，请重新上传');
      //   this.formByImport.fileList.pop()
      // }
      this.formByImport.fileList = fileList;
      // console.log(fileList, this.formByImport.fileList)
    },
    handelExceed() {
      this.$message.warning('超出最大上传数');
    },
    handleError() {
      checkFalse('上传失败');
      this.$refs.memberUpload.clearFiles();
      this.load = false;
    },
    onDialogSuccessClosed() {
      // 更新表单
      this.getIntegral();
    },
    handleSuccess(response, file, fileList) {
      // console.log(response)
      if(response.errorCode == 0) {
        checkSuccess('上传成功');
        this.dialogImport = false;
        this.load = false;
        this.dialogSuccess = true;
        this.$refs.memberUpload.clearFiles();
        this.getIntegral();
      } else {
        this.$refs.memberUpload.clearFiles();
        this.load = false;
        checkFalse(response.message)
      }
    }
  },
  created() {
    this.getIntegral();
  },
}
</script>
<style lang="scss" scoped>
#bulkIntegral {
  padding:20px;
  .el-table{
    width: 99.9%;
  }

  .contentInfo {
    background-color:#fff;
    .flex {
      padding-bottom: 20px;
    }
    /deep/ .el-table th>.cell {
      font-weight: 700;
      color: #303133;
    }
  }
  /deep/ .el-dialog__footer {
    border: none;
  }
  .importBox {
    width: 174px;
    border: 1px dashed #C0C4CC;
    border-radius: 6px;
  }
  .dialogTips {
    padding-bottom: 8px;
    padding-top: 22px;
    border-top: 1px solid #E4E7ED;
    color: #909399;
    h3 {
      font-weight: normal;
      font-size: 14px;
      margin-bottom: 10px;
    }
    p {
      font-size: 12px;
    }
  }
  .success_icon {
    text-align: center;
    color: #52C41A;
    font-size: 47px;
  }
  .successHeader {
    text-align: center;
    color: #303133;
    font-size: 16px;
    line-height: 39px;
  }
  .successCon {
    text-align: center;
    color: #606266;
    font-size: 12px;
  }
  .member-wechat-timer {
    width: 20px;
    height: 20px;
    font-size: 10px;
    line-height: 20px;
    padding: 0;
  }
  .dialogSuccess /deep/ .el-dialog__footer {
    text-align: center;
    padding-bottom: 22px;
  }
  /deep/ .dm-pagination {
    text-align: right;
    margin-top: 20px;
  }
}
.flex {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
