<template>
  <div>
    <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="#"
              accept=".xlsx"
              :headers="uploadHeaders"
              :file-list="files"
              :before-upload="getPostData"
              :on-change="changeFile"
              :on-error="uploadError"
              :on-success="uploadSuccess"
              :show-file-list="false"
              :multiple="false">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <!-- <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</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>
  </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: {axx: 1},
      }
    },
    created() {
      this.goToGetUploadHistory();
    },
    methods: {
      getPostData(file) {
        let self = this;
        let arr = file.type.split('/');
        let ext = "." + arr[1];
        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
            }];

            // openLoading(self);
            let req = {
                // token: localStorage.getItem("token"),
                token: 'F868A5F84DD9433E93E00E3952A16364',
                fileArray: fileArray,
                import_type: 2,
            };
            //
            // console.log('req ', req);
            console.log('string req ', JSON.stringify(req))
            // self.postData = req;
            self.postData = JSON.stringify(req);
            uploadExcel(self.postData).then(res => {
              console.log('%c res >> ','color: red;', res)
            })
            // self.$axios.post(localStorage.getItem("Url") + 'importServiceImpl/importToQuestionPool'
            //     , JSON.stringify(req)
            // ).then(function (res) {
            //     closeLoading(self);
            //     let data = JSON.parse(JSON.stringify(res.data));//通过这个实现深拷贝
            //     if (data.flag) {
            //         self.$message('导入成功' + data.successNum + '条(重复的题目不会导入!)');
            //         self.getLabelList();
            //         self.search();
            //     } else {
            //         self.$message.error('导入题目失败');
            //         let errorList = data.errorList;
            //         let message = "";
            //         if (isNotEmptyUtils(errorList)) {
            //             for (let i = 0; i < errorList.length; i++) {
            //                 message += "第" + errorList[i].index + "行:" + errorList[i].name + '<br>';
            //             }
            //         }
            //         htmlMessageBox(self, "警告", message, "确定", function () {
            //         }, "", null, "warning");
            //     }
            // }).catch(function (error) {
            //     self.$message.error('导入题目失败');
            //     errorResponseCheck(error, self);
            // });
        };
        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();
      },


    },  
  }
</script>

