<template>
  <div class="batch-import-wrap">
    <div class="step-guide">
      <ul class="guide-list">
        <li class="first">
          <div class="procedure">
            <i class="icon">1</i>
            <p class="text">下载模板</p>
            <p class="border"></p>
          </div>
          <div class="under-info">
            <p class="step-tips">点击下方“下载模板”</p>
            <el-button type="primary" size="small" @click="handleDownloadDemo">下载模板</el-button>
          </div>
        </li>
        <li class="first second">
          <div class="procedure">
            <i class="icon">2</i>
            <p class="text">填写居民信息</p>
            <p class="border"></p>
          </div>
          <div class="under-info">
            <p class="step-tips">按照模板编辑居民信息</p>
            <ul class="fill-tips">
              <li>
                <i class="tips-title notice">填写要求：</i>
              </li>
              <li>
                <i class="tips-title">居民姓名：</i>
                <p>当前支持2~15个字符</p>
              </li>
              <li>
                <i class="tips-title">出生年月：</i>
                <p>"年-月-日"，我们将优先识别身份证信息中的出生年月信息，若身份证未填，将识别此处信息。</p>
              </li>
              <li>
                <i class="tips-title">居住地址：</i>
                <p>≤50字</p>
              </li>
              <li>
                <i class="tips-title">电话：</i>
                <p>请输入11为手机号码</p>
              </li>
              <li>
                <i class="tips-title">分组与诊断：</i>
                <p>多个分组之间，用中文逗号“，”分割</p>
              </li>
            </ul>
          </div>
        </li>
        <li class="first third">
          <div class="procedure">
            <i class="icon">3</i>
            <p class="text">上传文件</p>
          </div>
          <div class="under-info">
            <p class="step-tips">将填写好的居民信息文件在下方进行上传</p>
            <el-upload
              class="upload-file"
              drag
              action="#"
              :before-upload="getPostData"
              :http-request="notUseDefaultUpload">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            </el-upload>
          </div>
        </li>
      </ul>
    </div>
    <div class="component-content screenSet upload-history-wrap">
      <p class="septal-line"></p>
      <p class="upload-record">上传历史记录：{{searchData.totalCount}}</p>
        <!-- :cell-style="aaa" -->
      <el-table
        :data="searchData.tableData"
        class="upload-table"
        empty-text="该用户暂无历史记录"
        style="width: 100%">
        <el-table-column
          align="left"
          prop="fileName"
          label="文件名"
          width="250">
        </el-table-column>
        <el-table-column
          align="left"
          prop="uploadTime"
          label="上传时间"
          width="180">
        </el-table-column>
        <el-table-column
          align="left"
          prop="insertCount"
          label="新导入居民数">
        </el-table-column>
        <el-table-column
          align="left"
          prop="updateCount"
          label="更新居民资料数">
        </el-table-column>
        <el-table-column
          align="left"
          prop="status"
          label="处理状态">
        </el-table-column>
        <el-table-column
          align="left"
          prop="reason"
          label="关闭理由">
        </el-table-column>
      </el-table>
      <el-pagination
        class="pagination-style"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :total="searchData.totalCount"
        :current-page="1"
        :page-sizes="[15, 30, 50, 100]"
        :page-size="searchData.pageSize"
        layout="total, sizes, prev, pager, next, jumper">
      </el-pagination>
    </div>
    <!-- 上传成功弹窗 -->
    <el-dialog
      class="upload-success-modal"
      title="上传成功"
      :visible.sync="showUploadSuccess"
      width="400px"
      :show-close="false"
      :close-on-click-modal="false"
      center>
      <p class="tips">我们会在<i>3-5个工作日</i>内进行处理，届时您可以在上传历史记录列表查看处理结果</p>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleCloseUploadSuccess">我知道了</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import { mapGetters } from 'vuex';
  import { getSaasDomain } from '@/utils/index';
  import {
    getUploadHistory,
    uploadExcel,
  } from "@/utils/patients/patientsapi";

  export default {
    data() {
      return {
        searchData: {
          pageNo: 1,  // 第几页
          pageSize: 15,  // 每页条数
          tableData: [],
          totalCount: 0,
        },
        files: [],
        postData: {},
        showUploadSuccess: false,
      }
    },
    created() {
      this.goToGetUploadHistory();
    },
    computed: {
      ...mapGetters([
        '_token',
      ]),
    },
    methods: {
      // aaa(obj){
      //   console.log('%c cell-style obj>>>>>>', 'color: red;', obj);
      //   if(obj.column.property == 'reason'){
      //     return 'red>>>'
      //   }else{
      //     return 'pink'
      //   }
      // },
      notUseDefaultUpload(){
        // console.log('just console>>>>>>>>')
      },
      getPostData(file) {
        let self = this;
        let arr = file.type.split('/');
        let ext = "." + arr[1];
        let name = file.name;
        let type = name.substring(name.lastIndexOf('.') + 1);
        if (type !== 'xls' && type !== 'xlsx') {
          self.$message({
            message: '上传文件只能是 xls、xlsx格式!',
            type: 'warning'
          });
         return;
        }
        let reader = new FileReader();
        reader.onload = function (e) {
            let fileJson = {
                fileName: file.name,
                file: e.target.result.substr(e.target.result.indexOf("base64,") + 7),
                ext: ext
            };

            let fileArray = [{
                type: 'patient',
                base64: fileJson
            }];

            let req = {
                fileArray: fileArray,
                import_type: 2,
            };
            if( process.env.BUILD_ENV == "development" ){
              req.token = '77DDB524DE0742B19CEC759CA463F3A5'
            }else{
              // req.token = self._token;
              req.token = localStorage.getItem('storageToken');
            }
            self.postData = JSON.stringify(req);
            console.log('>>>>>> batch upload req', req)
            uploadExcel(self.postData).then(res => {
              if(typeof res.importFlag != 'undefined' && res.importFlag == true){
                self.showUploadSuccess = true;
                try{
                  self.goToGetUploadHistory();
                }catch(err){
                  console.log('reload history list error');
                }
              }else{
                self.$message({
                  message: '上传失败，请重新上传!',
                  type: 'success'
                });
              }
            })
        };
        reader.readAsDataURL(file);
      },
      handleDownloadDemo(){
        let src = 'https://file.yunqueyi.com/File/template/居民导入模板.xlsx';
        let newTab=window.open('about:blank');
        newTab.location = src;
      },
      goToGetUploadHistory(){
        // console.log('go get upload history>>>>>>')
        let params = {
          pageNo: this.searchData.pageNo,
          pageSize: this.searchData.pageSize,
        };
        getUploadHistory(params).then(res => {
          // console.log('获取上传历史记录：', res);
          if(res.code == "000000"){
            let data = res.data.importRecordsModelList;
            if(data && data.length > 0){
              data = data.map(item => {
                if(!item.reason) {
                  item.reason = '-'
                }
                return item;
              });
              this.searchData.tableData = data;
              this.searchData.totalCount = res.data.count;

            }
          }else{
            // 获取失败
            this.$message({
              message: '接口返回失败，请重新再试',
              type: 'warning'
            });
          }
        })
      },
      handleCurrentChange(val) {
        this.searchData.pageNo = val;
        this.goToGetUploadHistory();
      },
      handleSizeChange(val) {
        this.searchData.pageSize = val;
        this.goToGetUploadHistory();
      },
      handleCloseUploadSuccess() {
        this.showUploadSuccess = false;
      },

    },  
  }
</script>




