<template>
  <div id="logManage">
    <el-row>
      <el-col>
        <div style="text-align: right">
          <el-select size="mini" style="margin-left:20px;" v-model="queryProject" placeholder="选择采集引擎"
                     @focus="projectFocus" @change="projectChange">
            <el-option
                v-for="item in projectOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
          <el-select size="mini" v-model="querySpider" placeholder="选择执行单元">
            <el-option
                v-for="item in spiderOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
          <el-date-picker
              style="margin-left:20px"
              size="mini"
              v-model="queryDate"
              type="daterange"
              align="right"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="datePickerOptions">
          </el-date-picker>
          <el-button type="success" style="margin-left:20px" size="mini" @click="onQuery"><i class="el-icon-search"></i>
            搜索
          </el-button>
          <el-button type="info" size="mini" @click="refreshTable"><i class="el-icon-refresh"></i> 刷新
          </el-button>
        </div>
        <mytable :metaData="metadata" :tableData="tableData" :isLoading="isLoading"
                 @selection-change="handleSelectionChange">
          <template #default="{ index }">
            <el-button
                @click.native.prevent="viewProject(index, tableData)"
                size="mini"
                icon="el-icon-view"
                circle>
            </el-button>
            <el-button
                @click.native.prevent="jumpToScrapydLog(index, tableData)"
                size="mini"
                icon="el-icon-link"
                circle>
            </el-button>
          </template>
        </mytable>
        <el-pagination
            style="padding: 15px"
            background
            layout="total, prev, pager, next, jumper"
            :total="total"
            :current-page="pageIndex"
            @current-change="onPageChange">
        </el-pagination>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import Vue from 'vue'
import {Row, Col, Table, TableColumn, Button, Select, Option, DatePicker, Message, Dialog, Pagination} from 'element-ui'
import logApi from '../../js/api/logApi'
import projectApi from '../../js/api/projectApi'
import mytable from '../components/CustomTable'
import taskApi from '../../js/api/taskApi'

Vue.use(Row)
Vue.use(Col)
Vue.use(Table)
Vue.use(TableColumn)
Vue.use(Button)
Vue.use(Select)
Vue.use(Option)
Vue.use(DatePicker)
Vue.use(Dialog)
Vue.use(Pagination)
export default {
  name: 'LogManage',
  props: ['taskid'],
  data() {
    return {
      isLoading: false,
      tableData: [],
      total: 0,
      pageIndex: 1,
      multipleSelection: [],
      queryObject: {},
      queryProject: '',
      querySpider: '',
      queryDate: '',
      projects: [],
      clearDialogVisible: false,
      projectOptions: [
        {
          label: "全部",
          value: "0"
        },
      ],
      spiderOptions: [
        {
          label: "全部",
          value: "0"
        },
      ],
      datePickerOptions: {
        shortcuts: [
          {
            text: '今日',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setFullYear(end.getFullYear());
              start.setMonth(end.getMonth());
              start.setDate(end.getDate())
              start.setHours(0);
              start.setMinutes(0);
              start.setSeconds(0);
              start.setMilliseconds(0);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '昨日',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setFullYear(end.getFullYear());
              start.setMonth(end.getMonth());
              start.setDate(end.getDate() - 1)
              start.setHours(0);
              start.setMinutes(0);
              start.setSeconds(0);
              start.setMilliseconds(0);
              end.setTime(start.getTime() + 3600 * 1000 * 24)
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
      }
    }
  },
  components: {
    'mytable': mytable
  },
  computed: {
    metadata: function () {
      let temp = [];
      this.$store.state.metadata.metadata.forEach(element => {
        if (element.tableName === 'log' && element.visible !== '0') {
          let tempElement = {...element};
          tempElement.minWidth = tempElement.columnWidth + "%";
          tempElement.columnWidth = 0;
          temp.push(tempElement);
        }
      });
      return temp;
    }
  },
  mounted: function () {
    this.refreshTable();
  },
  methods: {
    refreshTable() {
      this.queryProject = '';
      this.querySpider = '';
      this.queryDate = [];
      this.pageIndex = 1;
      this.buildQueryObject();
      this.query();
      projectApi.getAllProject((response) => {
        if (response.data.code === 200) {
          this.projects = response.data.content;
        }
      })
    },
    updateTaskNameToTableData() {
      let ids = []
      for (let j = 0; j < this.tableData.length; j++) {
        ids.push(this.tableData[j].taskId)
      }
      this.isLoading = true;
      taskApi.queryTaskByIds(ids, res => {
        if (res.data.code === 200) {
          let param = res.data.content
          for (let i = 0; i < this.tableData.length; i++) {
            let obj = this.tableData[i]
            let taskId = this.tableData[i].taskId
            if (Object.prototype.hasOwnProperty.call(param, taskId)) {
              obj.taskId = param[taskId]
              this.$set(this.tableData, i, obj)
            }
          }
          this.isLoading = false;
        } else {
          this.isLoading = false;
        }
      })
    },
    onPageChange(index) {
      this.isLoading = true;
      this.pageIndex = index;
      logApi.queryLogPageable(this.pageIndex - 1, 10, this.queryObject, (response) => {
        if (response.data.code === 200) {
          this.tableData = response.data.content;
          this.total = parseInt(response.data.message);
          this.updateTaskNameToTableData()
          this.isLoading = false;
        } else {
          Message("查询失败");
          this.isLoading = false;
        }
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    viewProject(index, table) {
      this.$router.push('/oscm/log/detail/' + table[index].id);
    },
    jumpToScrapydLog(index, table) {
      logApi.getScrapydLogURL(table[index], (response) => {
        if (response.data.code === 200) {
          const scrapydLogURL = response.data.content;
          window.open(scrapydLogURL);
        } else {
          Message("查询日志失败");
          this.isLoading = false;
        }
      })
    },
    onQuery() {
      this.buildQueryObject();
      this.query();
    },
    buildQueryObject() {
      this.queryObject = {
        project: this.projectOptions[this.queryProject === '' ? 0 : this.queryProject].label,
        spider: this.spiderOptions[this.querySpider === '' ? 0 : this.querySpider].label,
        startDate: this.queryDate.length > 0 ? this.queryDate[0].getTime() : 0,
        endDate: this.queryDate.length > 0 ? this.queryDate[1].getTime() : new Date().getTime()
      }
    },
    query() {
      this.isLoading = true;
      logApi.queryLogPageable(0, 10, this.queryObject, (response) => {
        if (response.data.code === 200) {
          this.tableData = response.data.content;
          this.total = parseInt(response.data.message);
          this.updateTaskNameToTableData()
          this.isLoading = false;
        } else {
          Message("查询失败");
          this.isLoading = false;
        }
      })
    },
    projectFocus() {
      if (this.projectOptions.length === 1) {
        for (let i = 0; i < this.projects.length; i++) {
          this.projectOptions.push({label: this.projects[i].projectName, value: i + 1})
        }
      }
    },
    projectChange(selectVal) {
      if (this.querySpider !== '') {
        this.querySpider = 0;
      }
      if (selectVal === 0) {
        this.spiderOptions = [];
        this.spiderOptions.push({label: "全部", value: 0});
        return;
      }
      projectApi.getSpidersOfProject(
          this.projects[selectVal - 1].ipPort,
          this.projects[selectVal - 1].projectName,
          (response) => {
            this.spiderOptions = [];
            this.spiderOptions.push({label: "全部", value: 0});
            let spiders = response.data.content;
            for (let i = 0; i < spiders.length; i++) {
              this.spiderOptions.push({label: spiders[i], value: i + 1});
            }
          }
      );
    }
  }
}
</script>

<style scoped>
.el-table .cell, .el-table th > .cell {
  text-align: center;
}

.el-pagination {
  display: flex;
  justify-content: center;
}

.el-select, .el-date-editor {
  margin-left: 20px;
  margin-bottom: 10px;
}
</style>

<style>
#logManage .el-dialog {
  margin-top: 25vh !important;
}
</style>