<template>
  <div class="batch-box">
    <div class="batch-box-top tabs">
        <a :class="[tabsIndex===0?'active':'']" @click="handleChangeTabs(0)">批量上传</a>
        <a :class="[tabsIndex===1?'active':'']" @click="handleChangeTabs(1)">日志</a>
    </div>
    <div class="batch-box-center">
        <template v-if="tabsIndex===0">
            <div class="upload-box" v-if="!alreadyFile">
                <el-upload
                    class="upload-demo"
                    :accept="'.xls,.xlsx'"
                    :limit="1"
                    :on-progress="uploadVideoProcess"
                    :before-upload="handlebeforeUpload"
                    :on-success="handleSuccess"
                    drag
                    :action="url"
                    :show-file-list="false"
                    multiple>
                    <div class="el-upload__text">
                        点击或拖拽文件到此处上传
                        <span>只有 xlsx, xls 格式文件可以上传，文件大小不得超过 100MB</span>
                    </div>
                </el-upload>
            </div>
            <template v-else>
                <div class="file-top">
                    <div class="file-content">
                        <svg-icon icon-class="xlsx"></svg-icon>
                        <div class="file">
                            <p v-if="fileList[0]&&fileList[0].name">{{fileList[0].name}}</p>
                            <el-progress v-if="resultData" :percentage="percentage" :show-text="false"></el-progress>
                            <b v-if="fileList[0]&&fileList[0].fileSize&&!progressFlag&&!uploading&&!resultData">{{fileList[0].fileSize}}</b>
                            <!-- <div class="file-uploading" v-if="progressFlag">
                                <span class="progress" v-if="realFileSize">{{'上传文件 '+alreadyUpload+'/'+realFileSize}}</span>
                                <span>{{percentage}}%</span>
                            </div> -->
                            <div class="file-uploading" v-if="resultData">
                                <span class="progress">{{'导入数据 '+resultData.cur_count+'/'+resultData.total_count}}</span>
                                <span class="color-green" v-if="resultData.is_finish==='true'">完成</span>
                                <span class="color-red" v-if="resultData.is_finish==='false'&&resultData.is_end==='true'">网络链接已中断</span>
                            </div>
                        </div>
                    </div>
                    <i class="el-icon-error" @click="handleErmoveFile"></i>
                </div>
                <div class="file-bottom">
                    <p>批量上传内容与系统中有重复时</p>
                    <el-radio-group v-model="sameUser" :disabled="uploading||(resultData&&resultData.is_finish==='true')">
                        <el-radio label="false">跳过</el-radio>
                        <el-radio label="true">覆盖</el-radio>
                    </el-radio-group>
                    <el-checkbox-group v-model="coverUser" :disabled="uploading||(resultData&&resultData.is_finish==='true')">
                        <el-checkbox label="1">覆盖时忽略密码</el-checkbox>
                        <el-checkbox label="2">上传完成后自动导出密码文件</el-checkbox>
                    </el-checkbox-group>
                </div>
            </template>
        </template>
        <template v-else>
            <div class="log-box" v-if="resultData">
                <p>上传文件 {{fileList[0].name}}</p>
                <p>用时 {{realFormatSecond(uploadTime+resultData.execute_duration)}}</p>
                <p>成功上传 <span class="color-green">{{resultData.success_count}}</span> 条记录，失败 <span class="color-red">{{resultData.error_count}}</span> 条</p>
                <div class="border"></div>
                <p :class="[item.is_success==='true'?'color-green':'color-red']" v-for="(item,index) in execute_log_list" :key="index">
                    {{item.row_count + ' '+ (item.is_success==='false'?item.error_info:'上传成功')}}
                </p>
            </div>
        </template>
    </div>
    <div class="batch-box-bottom">
        <template v-if="tabsIndex===0">
            <a class="downLoad" target="_blank" :href="exportUrl">下载模板</a>
            <div class="btn-box">
                <el-button @click="closeDialog" size="small">取消</el-button>
                <el-button type="primary" :key="3" :disabled="!uploadFlag&&!file_id||(resultData&&resultData.is_finish==='true')" v-if="!uploading&&!isStop&&(resultData&&resultData.is_finish==='true'||!resultData)" @click="handleUpload" v-loading="loading"><svg-icon icon-class="upload"></svg-icon>开始上传</el-button>
                <el-button type="primary" v-if="uploading&&!isStop" v-loading="loading" @click="handleInterruptTask"><svg-icon icon-class="pause-fill"></svg-icon>暂停</el-button>
                <el-button type="warning" v-if="isStop" v-loading="loading" @click="handleUpload"><i class="el-icon-refresh-right"></i>重试</el-button>
            </div>
        </template>
        <template v-else>
            <div class="btn-box" style="flex:1">
                <el-button :key="1" type="primary" :disabled="!(resultData&&resultData.is_finish==='true')" @click="handleExportLog"><svg-icon icon-class="upload"></svg-icon>导出日志</el-button>
            </div>
        </template>
    </div>
  </div>
</template>

<script>
import { getToken } from "../../utils/auth";
import { getLogin } from "@/api/ajax";
export default {
  components: {},
  name: "batchImport",
  props: ["exportUrl"],
  data() {
    return {
      tabsIndex: 0,
      alreadyFile: false, // 上传了需要解析的文件
      file_id: '',
      uploadFlag: false, // 是否可以点击开始上传按钮
      uploading: false, // 上传中
      isStop: false, // 暂停
      fileList: [],
      sameUser: 'false', // 存在相同的用户是否覆盖， true 覆盖，false 跳过。
      coverUser: [], // 覆盖用户时是否更新用户密码， true 更新，false 不更新。
      progressFlag:false,
      percentage:0,
      alreadyUpload:'', // 已经上传的大小
      realFileSize: '', // 文件真实大小
      loading: false,
      timer: null,
      resultData: null, // 上传结果数据
      execute_log_list: [], // 日志列表
      uploadTime: 0,
      uploadTimer: null,
      id:this.$route.query.id?this.$route.query.id:''
    };
  },
  watch: {},
  computed: {
    url() {
      let userInfor = getToken();
      let access_token = "";
      if (userInfor) {
        let user = JSON.parse(getToken());
        access_token = user.access_token;
      }
      return (
        process.env.VUE_APP_BASE_API +
        "/FileServer/WebFileUpload?AccessToken=" +
        access_token +
        "&SecurityLevel=High"
      );
    },
  },
  methods: {
    handleChangeTabs(value){
        this.tabsIndex = value
    },
    closeDialog(){
        this.$emit("closeDialog")
    },
    handlebeforeUpload(file) {
      if (file.size > 100 * 1024 * 1024) {
        this.$message.warning('上传文件大小不能超过100M');
        return false; // 必须返回false
      }
      this.alreadyFile = true
      this.uploadTimer = setInterval(() => {
        this.uploadTime++    
      }, 1000);
    },
    handleSuccess(response, file, fileList) {
      if (response.status == 1) {
        this.progressFlag = false
        clearInterval(this.uploadTimer);
        this.file_id = response.file_info_list[0].file_id
        this.uploadFlag = true
        this.fileList = fileList
        this.fileList.forEach((item) => {
            if (item.size > 1000 * 1000) {
              if (item.size / 1000 / 1000 / 1000 > 1) {
                item.fileSize =
                  (item.size / 1000 / 1000 / 1000).toFixed(2) + "GB";
              } else {
                item.fileSize =
                  (item.size / 1000 / 1000).toFixed(2) + "MB";
              }
            } else {
              item.fileSize = (item.size / 1000).toFixed(2) + "KB";
            }
        });
      } else {
        this.fileList = [];
        this.file_id = ''
        this.uploadFlag = false
        this.$message.warning(response.msg);
        this.alreadyFile = false
        this.progressFlag = false
        this.percentage = 0
        this.alreadyUpload = ''
        this.uploadTime = 0
        clearInterval(this.uploadTimer);
      }
    },
    handleErmoveFile(){
        if(this.progressFlag){
            this.$message.warning('文件还未上传成功，不可删除');
            return false
        }
        this.file_id = ''
        this.uploadFlag = false
        this.fileList = []
        this.alreadyFile = false
        this.progressFlag = false
        this.isStop = false
        this.percentage = 0
        this.alreadyUpload = ''
        this.resultData = null
        this.sameUser = 'false'
        this.coverUser = []
        this.uploadTime = 0
    },
    uploadVideoProcess(event, file, fileList) {
        this.fileList = fileList
        this.progressFlag = true; // 显示进度条
        this.percentage = parseInt(event.percent); // 动态获取文件上传进度
        if (file.size > 1000 * 1000) {
            if (file.size / 1000 / 1000 / 1000 > 1) {
            this.alreadyUpload =
                (file.size / 1000 / 1000 / 1000 / 100*this.percentage).toFixed(2) + "GB";
            this.realFileSize = (file.size / 1000 / 1000 / 1000).toFixed(2) + "GB";
            } else {
            this.alreadyUpload =
                (file.size / 1000 / 1000 / 100*this.percentage).toFixed(2) + "MB";
            this.realFileSize =
                (file.size / 1000 / 1000).toFixed(2) + "MB";
            }
        } else {
            this.alreadyUpload = (file.size / 1000 / 100*this.percentage).toFixed(2) + "KB";
            this.realFileSize = (file.size / 1000).toFixed(2) + "KB";
        }
        if (this.percentage >= 100) {
            this.percentage = 100
        }
    },
    // 开始上传
    handleUpload(){
        if(this.resultData&&this.resultData.is_finish==='true'){
            this.$message.warning('已经解析过该文件');
            return false
        }
        if(!this.file_id){
            this.$message.warning('请先上传文件');
            return false
        }
        this.percentage = 0
        this.loading = true
        this.progressFlag = false
        this.uploadFlag = false
        let MethodName = "/OrgServer/Manager/DataImport/CreatePersonImportTask";
        let data = {
            file_id: this.file_id,
            org_id: this.id,
            is_cover_while_exit_same_user: this.sameUser,
            is_update_password_while_cover_user: this.coverUser.indexOf('1')>-1?'true':'false'
        }
        getLogin(MethodName, data)
        .then((res) => {
            if(res.status===1){
                this.loading = false
                this.uploading = true
                this.isStop = false
                this.timer = setInterval(() => {
                    if (this.resultData&&this.resultData.is_finish==='true') {
                        clearInterval(this.timer);
                        this.timer = null;
                        this.uploading = false
                        this.percentage = parseInt(this.resultData.cur_count/this.resultData.total_count)*100
                        if(this.coverUser.indexOf('2')>-1){
                            window.open(this.resultData.archive_file_url, "_blank");
                        }
                    }else{
                        this.handleTaskStatus()
                    }
                }, 1000);
            }else{
                this.loading = false
                this.uploading = false
                this.uploadFlag = true
                this.isStop = true
                clearInterval(this.timer);
            }
        })
        .catch(() => {
            clearInterval(this.timer);
            this.uploading = false
            this.uploadFlag = true
            this.isStop = true
            this.loading = false
        });
    },
    // 导入任务执行状态
    handleTaskStatus(){
        let MethodName = "/OrgServer/Manager/DataImport/GetPersonImportTaskExecuteStatus";
        let data = {
            is_query_execute_log: 'true',
            execute_log_query_top_n: 9999999
        }
        getLogin(MethodName, data)
        .then((res) => {
            if(res.status===1){
                this.resultData = res
                this.execute_log_list = JSON.parse(JSON.stringify(this.resultData.execute_log_list)).reverse()
            }
        })
        .catch(() => {
            this.uploading = false
            this.loading = false
        });    
    },
    // 中断任务
    handleInterruptTask(){
        this.loading = true
        let MethodName = "/OrgServer/Manager/DataImport/InterruptPersonImportTask";
        getLogin(MethodName, {})
        .then((res) => {
            if(res.status===1){
                this.isStop = true
                this.loading = false
            }
        })
        .catch(() => {
            this.loading = false
        });    
    },
    // 导出日志
    handleExportLog(){
        let href = this.resultData.execute_report_file_url
        window.open(href, "_blank");
    },
    // 将整数转换成 时：分：秒的格式
    realFormatSecond(value) {
      let theTime = parseInt(value); // 秒
      let theTime1 = 0; // 分
      let theTime2 = 0; // 小时
      if (theTime > 60) {
        theTime1 = parseInt(theTime / 60);
        theTime = parseInt(theTime % 60);
        if (theTime1 > 60) {
          theTime2 = parseInt(theTime1 / 60);
          theTime1 = parseInt(theTime1 % 60);
        }
      }
      let result = String(parseInt(theTime));
      if (result < 10) {
        result = "0" + result;
      }
      if (theTime1 > 0) {
        result = String(parseInt(theTime1)) + ":" + result;
        if (theTime1 < 10) {
          result = "0" + result;
        }
      } else {
        result = "00:" + result;
      }
      if (theTime2 > 0) {
        result = String(parseInt(theTime2)) + ":" + result;
        if (theTime2 < 10) {
          result = "0" + result;
        }
      } else {
        result = "00:" + result;
      }
      return result;
    },
  },
  created() {
  },
  mounted() {
  },
  beforeDestroy() {
  },
};
</script>

<style lang="scss" scoped>
.batch-box{
    height: 358px;
    background: #FFFFFF;
    &-top{
        height: 56px;
        border-bottom: 1px solid rgba(0,0,0,0.08);
    }
    &-center{
        height: 233px;
        overflow: auto;
    }
    &-bottom{
        height: 64px;
        border-top: 1px solid rgba(0,0,0,0.08);
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 16px 24px;
        .btn-box{
            display: flex;
            align-items: center;
            justify-content: center;
            .el-button{
                font-size: 14px;
                padding: 5px 16px;
                height: 32px;
                .svg-icon,.el-icon-refresh-right{
                    margin-right: 8px;
                }
                &.el-button--warning{
                    background: #FF802B;
                    border: none;
                }
            }
        }
    }
    .tabs{
        display: flex;
        padding: 12px 0;
        justify-content: center;
        a{
            font-size: 14px;
            line-height: 22px;
            color: #4E5969;
            border-radius: 100px;
            padding: 5px 16px;
            margin-right: 12px;
            &:hover{
                background: #F2F3F5;
            }
            &.active{
                background: #F2F3F5;
                font-weight: 500;
                color: #165DFF;
            }
        }
    }
    .downLoad{
        color: #000;
        font-size: 14px;
        line-height: 22px;
        &:hover{
            color: #165DFF;
        }
    }
    .upload-box{
        background: #F5F5F5;
        padding: 24px;
        height: 233px;
    }
    .file-top{
        height: 88px;
        padding: 24px 24px 0 24px;
        background: #F5F5F5;
        display: flex;
        .file-content{
            flex: 1;
            display: flex;
            .file{
                margin-left: 16px;
                flex: 1;
                b{
                    font-size: 12px;
                    font-style: normal;
                    font-weight: 600;
                    line-height: 14px;
                    color: #242634;
                }
            }
            p{
                margin: 0 0 8px 0;
                font-size: 14px;
                font-weight: 500;
                line-height: 16px;
                color: #242634;
            }
        }
        .el-icon-error{
            width: 16px;
            height: 16px;
            color: #CCCCCC;
            cursor: pointer;
            margin: 11px 0 0 14px;
        }
    }
    .file-bottom{
        padding: 24px 24px 0 24px;
        p{
            margin: 0 0 8px 0;
            font-size: 14px;
            line-height: 22px;
            color: #4E5969;
        }
        .el-radio-group,.el-checkbox-group{
            padding: 5px 0;
            margin-bottom: 8px;
        }
        .el-radio{
            margin-right: 24px;
        }
        .el-checkbox{
            margin-right: 16px;
        }
        .el-checkbox:last-of-type{
            margin-right: 0;
        }
    }
    .el-progress{
        margin-bottom: 8px;
    }
    .file-uploading{
        display: flex;
        justify-content: space-between;
        font-size: 12px;
        line-height: 14px;
        color: #242634;
        .progress{
            font-weight: 600;
        }
    }
    .log-box{
        background: #F5F5F5;
        padding: 8px 16px;
        min-height: 233px;
        p{
            font-size: 14px;
            font-weight: 400;
            line-height: 22px;
            margin: 0;
            color: #000;
        }
        .border{
            border-bottom: 1px dashed #000;
            margin: 16px 0;
        }
    }
}
</style>
<style lang="scss">
.upload-box{
    .el-upload,.el-upload-dragger{
        width: 100%;
    }
    .el-upload-dragger{
        background: #F5F5F5;
        border-radius: 24px;
        padding: 24px;
        border: 2px dashed var(--grey-03, #E2E6EA);
        display: flex;
        align-items: center;
        font-weight: 400;
        line-height: 22px;
        font-size: 14px;
        color: #000;
        span{
            display: block;
            font-size: 12px;
            color: #86909C;
            font-size: 12px;
            line-height: 20px;
            word-break: break-word;
        }
    }
}
</style>