<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">上传历史记录：120</p>
      <el-table
        :data="searchData.tableData"
        class="upload-table"
        style="width: 100%">
        <el-table-column
          align="left"
          prop="fileName"
          label="文件名"
          width="180">
        </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="address"
          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="[10, 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 { getSaasDomain } from '@/utils/index';
  import {
    getUploadHistory,
    uploadExcel,
  } from "@/utils/patients/patientsapi";

  export default {
    data() {
      return {
        // uploadUrl: `${getSaasDomain('web/patientManages/import')}`,
        searchData: {
          pageNo: 1,  // 第几页
          pageSize: 10,  // 每页条数
          tableData: [],
          totalCount: 0,
        },
        uploadHeaders: {
          token: localStorage.getItem('token')
        },
        files: [],
        postData: {},
        showUploadSuccess: false,
      }
    },
    created() {
      this.goToGetUploadHistory();
    },
    methods: {
      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) {
            self.$message('开始导入');
            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 = {
                // token: localStorage.getItem("token"),
                token: 'F868A5F84DD9433E93E00E3952A16364',
                fileArray: fileArray,
                import_type: 2,
            };
            self.postData = JSON.stringify(req);
            uploadExcel(self.postData).then(res => {
              console.log('%c res >> ','color: red;', res)
              if(typeof res.import_type != 'undefined' && res.importFlag == true){
                self.$message({
                  message: '上传成功!',
                  type: 'success'
                });
              }else{
                self.$message({
                  message: '上传失败，请重新上传!',
                  type: 'success'
                });
              }
            })
            
        };
        reader.readAsDataURL(file);
      },
      handleDownloadDemo(){
        window.location.href = 'https://file.yunqueyi.com/File/template/居民导入模板.xlsx';
      },
      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"){
            if(res.data.importRecordsModelList.length > 0){
              this.searchData.tableData = res.data.importRecordsModelList;
              this.searchData.totalCount = res.data.count;
            }
          }else{
            // 获取失败
            this.$message({
              message: '接口返回失败，请重新再试',
              type: 'warning'
            });
          }
        })
      },
      changeFile(file, fileList) {
        const name = file.name;
        const type = name.substring(name.lastIndexOf('.') + 1);

        if (type !== 'xls' && type !== 'xlsx') {
          this.$message({
            message: '上传文件只能是 xls、xlsx格式!',
            type: 'warning'
          });
          fileList.splice(0, 1);
          return false;
        }

        if (fileList.length > 1) {
          fileList.splice(0, 1);
        }

        this.files = [file];
      },
      uploadError(err, file, fileList){
        console.log('%c upload Error >>>>>>>>', 'color: red;')
      },
      uploadSuccess(response, file, fileList) {
        console.log('%c upload Success >>>>>>>>', 'color: red;')
        // this.loading = false;
        // this.visible = false;
        // this.tipShow = true;
        console.log('response: ', response);
        console.log('file: ', file);
        console.log('fileList: ', fileList)
        // console.log(response, file, fileList);
        const { code } = response;
        this.code = response.code;

        const codes = ['000000', '400002', '400004'];

        if (codes.indexOf(code) > -1) {
          this.error = response.data;
        } else {
          this.error = response.message;
        }
      },
      handleCurrentChange(val) {
        this.searchData.pageNo = val;
        this.goToGetUploadHistory();
      },
      handleSizeChange(val) {
        this.searchData.pageSize = val;
        this.goToGetUploadHistory();
      },
      handleCloseUploadSuccess() {
        this.showUploadSuccess = false;
      },

    },  
  }
</script>




