<template>
  <div class="system-task">
    <el-container>
      <el-header class="position_relative">
        <div class="header-tabs">
          <el-tabs v-model="activeName" type="card">
            <el-tab-pane label="实时进度" name="0"></el-tab-pane>
            <el-tab-pane label="任务列表" name="1"></el-tab-pane>
          </el-tabs>
        </div>
      </el-header>
      <el-main class="system-task-main">
        <div v-if="activeName === '0'" key="task1">
          <el-table :data="taskData" border header-row-class-name="custom-table-header" v-loading="loadingCancel" element-loading-text = "请耐心等待，数据正在加载中...">
            <el-table-column v-if="form === 1" label="文件名称" prop="oldName" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column label="任务数量" prop="total" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                <div>
                  <span>{{ scope.row.total?scope.row.total:scope.row.allNum }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="当前下标" prop="index" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                <div>
                  <span>{{ scope.row.index?scope.row.index:scope.row.successNum }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="实时进度" align="center" min-width="200px" show-overflow-tooltip>
              <template slot-scope="scope">
                <el-progress :text-inside="true" :stroke-width="20" :percentage="scope.row.percentage?scope.row.percentage:scope.row.taskProcess" :color="customColors"></el-progress>
              </template>
            </el-table-column>
            <el-table-column label="当前状态" align="center" v-if="form == 8" min-width="100px" show-overflow-tooltip>
              <template slot-scope="scope">
                <span>{{ statusObj[scope.row.taskDetailState] }}</span>
               <!-- <span v-if="scope.row.taskDetailState!=5">{{ scope.row.taskType?'进行中':'等待中' }}</span>
               <span v-else>已取消</span> -->
              </template>
            </el-table-column>
            <el-table-column v-if="form === 2" label="操作" align="center" width="120" show-overflow-tooltip>
              <template slot-scope="scope">
                <span v-if="!scope.row.url">等待中</span>
                <el-link v-else type="primary" @click.native="handleDownload(scope.row)">下载文件</el-link>
              </template>
            </el-table-column>
            <el-table-column v-if="form === 9 || form === 8" label="操作" align="center" width="150" show-overflow-tooltip>
              <template slot-scope="scope">
                <p v-if="scope.row.taskDetailState!=5">
                  <el-link class="margin-left_10" type="danger"  @click="cancel(scope.row)">取消</el-link>
                  <el-link class="margin-left_10" type="danger" @click="handleCancelZan(scope.row)" v-if="scope.row.taskDetailState==6">继续</el-link>
                  <span class="loadCss" type="danger" @click="handleCancelZan(scope.row)" v-else-if="scope.row.taskDetailState==8" >暂停中</span>
                  <el-link class="margin-left_10" type="danger" @click="handleCancelZan(scope.row)" v-else>暂停</el-link>
                </p>
                <p class="margin-left_10" type="danger" v-else>已取消</p>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div v-else key="task2">
          <el-form inline v-if="form!=9">
            <el-form-item  label="创建人">
              <el-input v-model="queryParams.createName" size="small" placeholder="请输入创建人名称"></el-input>
            </el-form-item>
            <!-- <el-form-item v-else label="任务类型">
                <el-input v-model.trim="queryParams.taskType" size="small" placeholder="请输入任务类型"></el-input>
                <el-select v-model="queryParams.taskType" size="small" clearable placeholder="请选择任务类型">
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
            </el-form-item> -->
            <el-form-item>
              <el-button  size="small" type="" @click="getList2">搜索</el-button>
            </el-form-item>
          </el-form>
          <el-table v-loading="loading" :data="tableData" border header-row-class-name="custom-table-header" @sort-change="sortChange">
            <el-table-column v-if="form === 1" label="文件名称" prop="oldName" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column v-else label="#" type="index" align="center" width="55">
              <template slot-scope="scope">
                <span>{{ (scope.$index + 1) + ((queryParams.current - 1) * queryParams.size) }}</span>
              </template>
            </el-table-column>
            <el-table-column v-if="form!=9 && form!=8" label="开始时间" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                <span >{{ $d(scope.row.startTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column v-if="form!=9 && form!=8" label="结束时间" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                <span>{{ $d(scope.row.endTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column v-else label="创建时间" prop="createTime" align="center" sortable="custom" show-overflow-tooltip>
              <template slot-scope="scope">
                <span>{{ scope.row.createTime }}</span>
              </template>
            </el-table-column>
            <el-table-column v-if="form==9 || form==8" label="任务类型" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                <span>{{ scope.row.taskType==1?'定时任务':'普通任务' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="任务状态" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                <span v-if="form!=9 && form!=8">{{ statusObj[scope.row.status] }}</span>
                <span v-else>{{ statusObj[scope.row.taskState] }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="createName" label="创建人" align="center" width="120" show-overflow-tooltip></el-table-column>
            <el-table-column v-if="form==9 || form==8" label="定时周期" prop="dateType" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
              <div>
               <span v-if="scope.row.taskType == 1">{{dateType.find(item=> item.value == getType(scope.row.crons)).label }}</span> 
               <span v-else></span> 
              </div>
            </template>
            </el-table-column>
            <!-- <el-table-column v-if="form==9 || form==8" label="定时时间" prop="dates" align="center" show-overflow-tooltip></el-table-column> -->
            <el-table-column v-if="form==9 || form==8" label="最近更新时间" prop="modifiedTime" align="center" sortable="custom" show-overflow-tooltip></el-table-column>
            <el-table-column v-if="form!=9 && form!=8" label="操作" align="center" width="120" show-overflow-tooltip>
              <template slot-scope="scope" v-if="scope.row.status !== 0">
                <el-link type="primary" @click.native="handleDownload(scope.row)" v-if="$permission('/workspace/common/taskDownload')">下载</el-link>
                <el-link class="margin-left_10" type="danger" @click.native="handleDelete(scope.row)" v-if="$permission('/workspace/common/delete')">删除</el-link>
              </template>
            </el-table-column>
            <el-table-column v-else label="操作" align="center" width="150" show-overflow-tooltip>
              <template slot-scope="scope">
                <div>
                  <el-dropdown v-if="scope.row.taskType == 1" split-button type="primary" size="small" @command="handleCommand($event,scope.row)" @click="handleClick(scope.row)">
                    <p>编辑</p>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item command="1">{{ pause==0?'暂停任务':'继续任务' }} </el-dropdown-item>
                      <!-- <el-dropdown-item command="1">暂停任务 </el-dropdown-item> -->
                      <el-dropdown-item command="2">删除任务</el-dropdown-item>
                      <!-- <el-dropdown-item command="3">取消</el-dropdown-item> -->
                      <el-dropdown-item command="4">更新记录</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                  <el-dropdown v-else split-button type="primary" size="small" @command="handleCommand($event,scope.row)" @click="deletes(scope.row)">
                    <p>删除</p>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item command="4">更新记录</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                  <!-- <el-link class="margin-left_10" type="danger" @click="deletes(scope.row)" v-if="scope.row.taskType!=1">删除</el-link> -->
                </div>
              </template>
                
            </el-table-column>
          </el-table>
          <div class="pagination">
            <el-pagination :current-page.sync="queryParams.current" :page-size="queryParams.size" :total="total" @current-change="handleCurrentChange" layout="total, prev, pager, next, jumper" background></el-pagination>
          </div>
        </div>
      </el-main>
    </el-container>
    <el-dialog title="编辑"
      :visible.sync="visible"
      width="600px"
      :before-close="close"
      append-to-body
      :close-on-click-modal="false">
        <el-form :model="forms" :rules="rules" ref="forms" label-width="100px">
          <el-form-item label="来源网站" prop="configId">
              <el-select v-model="forms.configId" placeholder="请选择网站" style="width: 100%;">
                  <el-option v-for="item in website"
                    :key="item.id"
                    :label="item.webName"
                    :value="item.id">
                  </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="下载内容" prop="configCells">
              <el-select v-model="forms.configCells"  multiple collapse-tags placeholder="请选择下载内容" style="width: 100%;">
                  <el-option v-for="item in download"
                    :key="item.id"
                    :label="item.cellName"
                    :value="item.id">
                  </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="是否更新" prop="taskType">
              <el-switch v-model="forms.taskType" @change="changeTaskType" :active-value="1" :inactive-value="0" active-color="#13ce66" inactive-color="#ff4949">  </el-switch>
            </el-form-item>
            <el-form-item label="更新间隔" v-if="forms.taskType==1" prop="dateType">
                <el-select v-model="forms.dateType" @change="getDateType" clearable placeholder="请选择更新时间间隔" style="margin-right: 20px;width: 100%;">
                  <el-option v-for="item in dateType"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            <el-form-item label="选择更新时间" v-show="forms.dateType">
                <timeChoose :type="forms.dateType" @value="handleData" :cron="forms.crons" style="width:100%"></timeChoose>
            </el-form-item>
            <el-form-item label="检索信息">
              <el-input v-model="forms.conditions" placeholder="请输入检索信息" type="textarea"></el-input>
            </el-form-item>
        </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="sure">确 定</el-button>
      </span>
    </el-dialog>

    <updateLog ref="updateLog"></updateLog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { downLoad2, getFileName } from "@/utils";
import { cron } from "@/views/workspace/components/common/mixins";
import timeChoose from "@/views/workspace/components/common/timeChoose.vue";
import updateLog from "@/views/task/components/updateLog.vue";

export default {
  mixins:[cron],
  props: {
    form: Number,
    downloadId:String,
    isGetList:Boolean,
  },
  components: {
    timeChoose,
    updateLog,
  },
  data() {
    const dateTypeRule = (rule, value, callback) => {
      if (this.forms.taskType == 1) {
        if (value) {
          callback()
        } else {
          callback(new Error('请选择更新周期'))
        }
      } else {
        callback()
      }
    }
    return {
      activeName: '0',
      taskData: [],
      loading: false,
      total: 0,
      tableData: [],
      queryParams: {
        status: null,
        size: 10,
        current: 1,
        projectName: '',
        type: 0,
        order: 'desc',
        createName: '',
        projectId: 0
      },
      statusObj: {
        0: '等待中',
        1: '进行中',
        2: '成功',
        3: '失败',
        4: '等待下一次执行',
        5: '已取消',
        6: '暂停',
        7: '待取消',
        8: '待暂停'
      },
      customColors: [
        {color: '#f56c6c', percentage: 20},
        {color: '#e6a23c', percentage: 40},
        {color: '#5cb87a', percentage: 60},
        {color: '#1989fa', percentage: 80},
        {color: '#6f7ad3', percentage: 100}
      ],
      taskType: {
        1: '专利导入',
        2: '专利导出',
        3: '说明书导入',
      },
      visible:false,
      loadingCancel:false,
      options: [
        {label:'普通任务',value:0},
        {label:'定时任务',value:1},
      ],
      dateType: [
        {label:'每天',value:'day'},
        {label:'每周',value:'week'},
        {label:'每月',value:'month'},
        {label:'每年',value:'year'},
      ],
      website:[],
      download:[],
      forms:{},
      pause:0,
      rules: {
        configId: [{ required: true, message: '请选择来源网站', trigger: 'change' },],
        configCells: [{ required: true, message: '请选择下载内容', trigger: 'change' },],
        taskType: [{ required: true, message: '请选择', trigger: 'change' },],
        dateType: [{ required: true,  validator:dateTypeRule, trigger: 'change' },],
      },
      webSocket1: '',
    }
  },
  computed: {
    ...mapGetters(['webSocket', 'userinfo'])
  },
  watch: {
    isGetList(val) {
      this.getList2()
    },
  },
  mounted() {
    this.queryParams.type = this.form
    this.queryParams.projectId = this.$route.query.id
    // this.getList()
    // console.log(this.downloadId);
    
   
    if (this.form != 9) {
      this.initTask()
      this.getList()
      this.getQueueList()
    } else {
      this.connectWebSocket(this.userinfo.id)
      this.getTasks()//网站导入查询
      this.getTaskDetails()//传入状态查询实时进度
      this.getAllConfig()//请求全部网站
    }
    
    
  },
  methods: {
    connectWebSocket(userId) {
      this.webSocket1 = new WebSocket(`ws://${this.$c.hostname}:8111/api/quartz/ws/` + userId)
      // this.webSocket1 = new WebSocket(`ws://192.168.1.24:8111/api/quartz/ws/` + userId)

      // Store.commit('SET_WEB_SOCKET', webSocket)
      this.webSocket1.onopen = () => {
        console.log('WebSocket连接成功') 
        this.initTask()
        return true
      }
      
      // webSocket.onmessage = async (e) => {
      //   console.log(e)
      // }
      this.webSocket1.onerror = () => {
        console.log('WebSocket连接失败')
        // var timer = setTimeout(() => {
        //   for (var i = 0; i < 3; i++){
        //     var state = this.connectWebSocket(this.userinfo.id)
        //     if (state) {
        //       clearTimeout(timer)
        //     }
        //     if (i == 2) {
        //       clearTimeout(timer)
        //     }
        //   }
        // },1000)
      }
      this.webSocket1.onclose = () => {
        console.log('WebSocket连接关闭')
        // var timer = setTimeout(() => {
        //   for (var i = 0; i < 3; i++){
        //     var state = this.connectWebSocket(this.userinfo.id)
        //     if (state) {
        //       clearTimeout(timer)
        //     }
        //     if (i == 2) {
        //       clearTimeout(timer)
        //     }
        //   }
        // },1000)
      }
    },
    initTask(webSocket1) {
      var webSocket = this.webSocket1?this.webSocket1:this.webSocket
      webSocket.onmessage = (e) => {
        const { code, data, message } = JSON.parse(e.data)
        // console.log({ code, data, message });
        if (code === 903 || code === 904) {
          const index = this.taskData.findIndex(item=>{return item.id == data.id || item.taskId==data.taskId})
          // const index = this.taskData.findIndex(item=>{return item.id == data.id})
          if (index === -1) {
            // this.taskData.push(data)
          } else {
            this.$set(this.taskData, index, data)
          }
          if (data.complete) {
            if(this.form==1){
              this.$message.success(`导入任务完成`)
               for(var i = 0;i<this.taskData.length;i++){
                if(this.taskData[i].complete==true){
                  this.taskData.splice(i,1)
                }
              }
            }else if (this.form==9) {
             switch (data.taskDetailState) {
              case '3':
                this.$message.error(`导入任务失败`)
                break;
              case '2':
                this.$message.success(`导入任务完成`)
                break;
              default:
                break;
             }
            }else{
              this.$message.success(`导出任务完成`)
            }
            
            // console.log(this.form)
           
            this.getList2()
          }
        } else if (code === 803 || code === 804) {
          this.$message.error(message)
          this.getList2()
        }
      }
    },
    getQueueList() {
      this.taskData = []
      this.$api.getQueueList({ type: this.form, projectId: this.queryParams.projectId }).then(response => {
        // console.log(response.data)
        response.data.map(item => {
          this.taskData.push({
            projectId: item.projectId,
            total: item.total,
            index: 0,
            taskId: item.id,
            oldName: item.oldName,
            complete: false,
            url: '',
            fileName: '',
            taskType: item.type,
            percentage: 0
          })
        })
      })
    },
    handleDownload(row) {
      downLoad2(row.url)
    },
    handleDelete(row) {
      this.$confirm('确认删除本条数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        this.$api.deleteTask({ id: row.id }).then(response => {
          this.$message.success('删除成功')
          this.loading = false
          this.getList()
        }).catch(error => {
          this.loading = false
        })
      })
    },
    handleCurrentChange(val) {
      this.queryParams.current = val;
      this.getList2();
    },
    getList() {
      this.loading = true
      this.$api.getTaskList(this.queryParams).then(response => {
        this.tableData = response.data.records
        this.total = response.data.total
        this.loading = false
      }).catch(error => {
        this.loading = false
      })
    },
    getList2() {
      if (this.form!=9) {
        this.getList()
      } else {
        // 网站导入查询按钮（当form为9网站导入，8为专利号导入）
        this.getTasks()
        this.getTaskDetails()//传入状态查询实时进度
      }
    },
    // 网站导入暂停，继续任务操作
    async handleSuspend(row) {
      // console.log(this.pause);
      if (this.pause==0) {//暂停pauseJobTask
       await this.$api.pauseJobTask({taskId: row.id}).then(res => {
          if (res.code == 200) {
            this.pause=1
            this.$message.success('已成功暂停该任务')
            // console.log(this.pause);
          }
        })
      } else {//继续
       await this.$api.resumeJobTask({taskId: row.id}).then(res => {
          if (res.code == 200) {
            this.pause=0
            this.$message.success('继续执行该任务')
          }
        })
      }
      this.$nextTick(() => {
        this.getList2()
      })
      
    },
    // 网站导入表格操作编辑按钮
    handleClick(row) {
      this.forms = JSON.parse(JSON.stringify(row))
      this.forms.dateType = this.getType(JSON.parse(JSON.stringify(row.crons)))
      this.forms.configCells=this.forms.configCells.split(',').map(Number)
      // console.log(this.forms);
      this.downloads()
      this.visible=true
    },
    // 网站导入表格操作按钮组
    handleCommand(command,row) {
      switch (command) {
        case '1'://暂停/继续
          this.handleSuspend(row)
          break;
        case '2'://删除
          this.deletes(row)
          break;
        case '3'://取消定时
          // this.handleTime(row)
          break;
        case '4'://更新日志
          this.$refs.updateLog.open(row,this.userinfo.id,this.webSocket1)
          break;
        default:
          break;
      }
    },
    deletes(row) {
      this.$confirm('确认删除本条数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
         this.$api.deleteTasks([row.id]).then(res => {
          if (res.code == 200) {
            if(res.data.length>0){
              this.$message.error(`${res.data.length}条任务删除失败`)
            }else{
              this.$message.success('成功删除该任务')
            }
            
            this.getList2()
          }
        })
      }).catch(err => {
        this.$message.info('取消删除该任务')
      })
     
    },
     // 请求全部网站
     getAllConfig() {
      this.$api.getAllConfig({}).then(res => {
        if (res.code==200) {
          this.website = res.data
        }
      })
    },
    // 请求当前网站可下载项
    async downloads() {
      let a= this.website.filter(item => {
        return item.id==this.forms.configId
      })
      this.forms.configType = a[0].webType
      await this.$api.getConfigCell({type:this.forms.configType}).then(res => {
        if (res.code==200) {
          this.download = res.data
          this.forms.configCells=this.download.map(item=>{ return item.id })
        }
      })
    },
    // 实时进度取消
    cancel(row) {
      // console.log(row);
      let task = {
        taskId: row.id,
        state:7,//7为待取消
      }
      // this.loadingCancel=true
      this.$api.setDetailState(task).then(res => {
        if (res.code==200) {
          this.$message.success('任务已取消')
          this.getList2()
        }
      }).catch(error => {
        this.$message.error(error.message)
        this.loadingCancel=false
      })
    },
    // 实时进度暂停继续
    handleCancelZan(row) {
      // console.log(row);
      // this.loadingCancel=true
      let task = {
        taskId: row.id,
        // state:0
      }
      if (row.taskDetailState==6) {
         task.state = 0
         this.$api.setDetailState(task).then(res => {
          if (res.code==200) {
            this.$message.success('继续执行')
              this.getList2()
            }
         }).catch(error => {
            this.$message.error(error.message)
            this.loadingCancel=false
         })
      } else {
        task.state = 8
        this.$api.setDetailState(task).then(res => {
          if (res.code==200) {
            this.$message.success('已暂停')
            this.getList2()
            }
        }).catch(error => {
          this.$message.error(error.message)
          this.loadingCancel=false
        })
      }
      // this.$nextTick(() => {
      //   this.getList2()
      // })
    },
    changeTaskType(val) {
        this.forms.dateType=''
        this.forms.conditions=''
    },
    //网站下载任务查询
    getTasks() {
      // this.tableData = []
      this.loading=true
      this.$api.getTasks(this.queryParams).then(response => {
        // console.log(response.data)
        this.tableData = response.data.records
        this.total = response.data.total
        this.loading=false
      }).catch(error => {
        this.loading = false
      })
    },
    getTaskDetails() {
      let queryParams = {
        current: 1,
        size: 10,
        taskDetailStates: [0,1,6,8]//等待，进行，取消，暂停
      }
      this.$api.getTaskDetails(queryParams).then(res => { 
        if (res.code==200) {
          this.taskData=res.data.records
          // this.total=res.data.total
        }
      })
    },
   
    // 获取时间
    handleData(val) {
      if (this.forms.dateType=='') {
        this.$message.error('请先选择更新周期')
        return false
      }
      this.forms.crons=val
    },
    // 排序
    sortChange({ column, prop, order }) {
      if (!order) {
        return false
      }
      const o = {
        'descending': 'desc',
        'ascending': 'asc',
      }
      this.queryParams.orderBy = prop
      this.queryParams.orderType = o[order]
      this.getList2()
    },
    sure() {
      this.$refs.forms.validate((valid) => { 
        let a= this.website.filter(item => {
            return item.webType==this.forms.configType
        })
        this.forms.configId = a[0].id
        if (valid) {
          this.$api.updateTasks(this.forms).then(response => { 
            if (response.code==200) {
              this.$message.success('已成功编辑该任务')
              this.getList2()
              this.close()
            }
          })
        }
      })
      
     
    },
    close() {
      this.visible=false
    },
    getDateType(val) {
      // console.log(val)
      this.forms.crons = ''
    },
  }
}
</script>

<style lang="scss">
.loadCss::after{
  content:'暂停中';
  color: #F56C6C;
  position: absolute;
  left: 0;
  top: 0;
  overflow: hidden;
  animation: loadName 1s linear infinite;
}
// .loadCss::before{
//   content: '   ';
//   position: absolute;
//   left: 0;
//   top: 0;
//   overflow: hidden;
// }
.loadCss{
  color: #ebeef5;
  margin-left: 10px;
  position: relative;
}
@keyframes loadName {
  0%{
    width: 0;
  };
  100%{
    width: 100%;
  }
}
.system-task {
  height: 100%;
  .system-task-main {
    background: #fff;
    padding: 5px 20px;
    margin-top: 20px;
  }
  .header-tabs {
    position: absolute;
    bottom: 0;
    height: 100%;
    padding-right: 9px;
    left: 12px;
    .el-tabs {
      margin-top: 19px;
    }
    .el-tabs__header {
      margin-bottom: 0 !important;
    }
  }
  .pagination {
    text-align: center;
    margin: 20px 0;
  }
}
</style>