<template>
  <div class="app-container">

      <el-row :gutter="10" style="border:1px solid #dedede;border-radius: 5px;padding-top: 20px;margin-bottom: 10px;">

        <el-col :span="8">
          <el-form :model="downLoadForm" ref="downLoadForm" size="mini" :inline="true" label-width="110px" :rules="downloadRules">
            <el-form-item label="导入数据类型" prop="importType">
              <el-select v-model="downLoadForm.importType" clearable placeholder="请选择数据类型" @change="importTypeChange">
                <el-option
                  v-for="item in importTypeList"
                  :key="item.id"
                  :label="item.importName"
                  :value="item.id">
                </el-option>
              </el-select>
              <el-button type="text" class="ml10" @click="download()">下载导入模板</el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="4">
          <el-form :model="uploadForm" ref="uploadForm" size="mini" :inline="true" label-width="100px">
            <el-form-item label="上传本地文档" prop="code">
              <el-upload
                class="upload-demo"
                :action="uploadForm.url"
                :headers="uploadHeader"
                :multiple="false"
                :data="uploadData"
                :show-file-list="false"
                :on-success="uploadSuccessFn"
                :on-error="uploadError"
                :disabled="downLoadForm.importType==''||downLoadForm.importType==undefined">
                <el-button size="mini" type="primary" :disabled="downLoadForm.importType==''||downLoadForm.importType==undefined">点击上传</el-button>
<!--                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>-->
              </el-upload>
<!--              <el-button type="text" class="ml10">上传</el-button>-->
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="12" v-if="tipShow">
          <el-alert title="重要提醒：必须在当天的23：30分之前，在系统中排好拜访线路，否则第二天不生效。"
                    type="error"
                    :closable="false">
          </el-alert>
        </el-col>
      </el-row>

    <el-row :gutter="10" style="border:1px solid #dedede;border-radius: 5px;padding: 20px 0;margin-bottom: 10px;">
    <el-form :model="queryParams" ref="queryForm" size="mini" :inline="true" label-width="110px">
      <el-form-item label="上传人" prop="userId">
        <user :userId="queryParams.userId" @userIdFn="userIdFn"></user>
      </el-form-item>
      <el-form-item label="上传文件名" prop="fileName">
        <el-input
          v-model="queryParams.fileName"
          placeholder="请输入上传文件名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="起止时间" prop="code">
          <el-date-picker
            style="width: 300px;"
            v-model="datetimerange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            @change="datetimeRangeChange">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">上传信息查询</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置起止时间</el-button>
        </el-form-item>
    </el-form>
    <el-table v-loading="loading" :data="importList">
      <el-table-column label="上传文件名" align="center" prop="fileName" :show-overflow-tooltip="true" >
        <template slot-scope="scope">
          <el-button @click="fileNameClick(scope.row)" type="text" size="small">
            {{scope.row.fileName}}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="数据类型" align="center" prop="importName" width="200" :show-overflow-tooltip="true"/>
      <el-table-column label="上传人" align="center" prop="userName" width="90"/>
      <el-table-column label="上传时间" align="center" prop="importTime" width="110" />
      <el-table-column label="成功数量" align="center" prop="successNum" width="90" />
      <el-table-column label="失败数量" align="center" prop="errorNum" width="90" />
      <el-table-column label="状态" align="center" prop="state"  width="90">
        <template slot-scope="scope">
          <span v-if="scope.row.state == 0">待解析</span>
          <span v-else-if="scope.row.state == 1">解析中</span>
          <span v-else>解析完成</span>
        </template>
      </el-table-column>
      <el-table-column label="解析结果" align="center" prop="resultMsg"  >
        <template slot-scope="scope">
          <div class="ellipsis" @click="resultMsgClick(scope.row)">{{scope.row.resultMsg}}</div>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    </el-row>
    <!--  解析结果展示  -->
    <el-dialog title="解析结果" :visible.sync="dialogMsgVisible" width="500" append-to-body>
      <div v-html="dialogMsg"></div>
    </el-dialog>
  </div>
</template>

<script>
import { getImportList,getListImportRecord } from "@/api/system/import";
import { getToken } from '@/utils/auth'
import user from "@/views/components/sfa/user";
export default {
  name: "Import",
    components: { user },
  data() {
    return {
        importTypeList:[],
        importList:[],
        loading:false,
      tipShow:false,
      // 查询参数
      queryParams: {
          pageNum:1,
          pageSize:10,
      },
        downLoadForm:{},
        uploadForm:{
            url:process.env.VUE_APP_BASE_API + '/sfa/importRole/importFile',
        },
        uploadData:{},
        uploadHeader:{
            Authorization:"Bearer " + getToken()
        },
        total:0,
        datetimerange:[],
        downloadRules:{
            importType:[ { required: true, message: '请选择导入数据类型', trigger: 'change' }],
        },
        dialogMsg:'',
        dialogMsgVisible:false,
    };
  },
  created() {
    this.getImportListFn();
  },
  methods: {
      datetimeRangeChange(val){
          if(val !=null && val != undefined){
              var  startDate = Date.parse(val[0]);
              var  endDate = Date.parse(val[1]);
              var days=(endDate - startDate)/(1*24*60*60*1000);
              if(days > 7){
                  this.datetimerange = [];
                  this.$modal.msgWarning('起止时间间隔不能超过7天，请重新选择！')
              }
          }
      },
      getImportListFn(){
          getImportList().then(response => {
                  console.log(response);
                  this.importTypeList = response.data;
              }
          );
      },
      getList(){
          let that = this;
          // this.$refs["downLoadForm"].validate(valid => {
          //     if (valid) {
                  that.loading = true;
                  let obj = {};
                  // that.importTypeList.forEach((item)=>{
                  //     if(item.templateUrl == that.downLoadForm.importType){
                  //       obj.importId = item.id
                  //     }
                  // })
                  obj.importId = that.downLoadForm.importType;
                  if(that.datetimerange==null || that.datetimerange == undefined){
                      obj.startTime ='';
                      obj.endTime = '';
                  }else{
                      obj.startTime = that.datetimerange[0];
                      obj.endTime = that.datetimerange[1];
                  }

                  obj.pageNum = that.queryParams.pageNum;
                  obj.pageSize = that.queryParams.pageSize;
                  obj.userId = that.queryParams.userId;
                  obj.fileName = that.queryParams.fileName;
                  getListImportRecord(obj).then(response => {
                          console.log(response);
                          that.importList = response.rows;
                          that.total = response.total;
                          that.loading = false;
                      }
                  );
          //     }
          // })

      },
      handleQuery(){
        this.queryParams.pageNum = 1;
        this.getList();
      },
      resetQuery(){

      },
      // 下载导入模板
      download(){
          this.$refs["downLoadForm"].validate(valid => {
              if (valid) {
                  let url = '';
                  this.importTypeList.forEach((item)=>{
                      if(item.id ==this.downLoadForm.importType ){
                          url = item.templateUrl;
                          window.open(url,'_blank')
                      }
                  })
              }
          });
      },
      importTypeChange(val){
          this.uploadData = {
              id:this.downLoadForm.importType
          }
          if(val==1){
            this.tipShow=true;
          }else{
            this.tipShow=false;
          }
      },
      resultMsgClick(msg){
          this.dialogMsg = msg.resultMsg.replace(/\n/g,'<br>')
          this.dialogMsgVisible = true;
      },
      userIdFn(val){
          console.log(val)
          this.queryParams.userId = val;
      },
      uploadSuccessFn(response, file, fileList){
          console.log(response)
          if(response.code == 200){
              this.$modal.msgSuccess("上传成功");
          }else{
              this.$modal.msgError(response.msg);
          }

      },
      uploadError(err, file, fileList){
          this.$modal.msgError("上传失败");
      },
      fileNameClick(row){
          window.location.href = row.fileUrl;
      },
  }
};
</script>
<style scoped>
  .ml10{
    margin-left: 10px;
  }
  .ellipsis{
    color: #46a6ff;
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
  }
</style>
