<template>
  <div class="height_100">
    <el-container v-if="showView">
      <el-header>
        <div id="step1">
          <mySearch style="width: 500px" :SearchFields="searchFiled" @search="search" :searchValue="searchOption">
          </mySearch>
        </div>
      </el-header>
      <el-main>
        <el-table v-loading="loading" :data="tableData" border header-row-class-name="custom-table-header"
          @sort-change="sortChange">
          <el-table-column 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-for="item in columnList.filter(item => !item.ifHidden)" :key="item.value" :label="item.name"
            :prop="item.value" :min-width="item.value == 'percentage' ? '200' : '100'" align="center" sortable="custom">
            <template slot-scope="scope">
              <div v-if="item.value == 'type'"
                v-html="$commonJS.getColumnData(scope.row, item, null, { data: importType })">
              </div>
              <div v-else-if="item.value == 'state'"
                v-html="$commonJS.getColumnData(scope.row, item, null, { data: state })">
              </div>
              <div v-else-if="item.value == 'percentage'" style="display:flex;">
                <div style="width:100%">
                  <el-progress :text-inside="true" :stroke-width="20"
                    :percentage="scope.row.percentage > 100 ? 100 : scope.row.percentage"
                    :color="customColors"></el-progress>
                </div>
                <div style="min-width: 50px;">{{ scope.row.doneNum }}/{{ scope.row.allNum }}</div>
              </div>
              <div v-else v-html="$commonJS.getColumnData(scope.row, item)"></div>
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center" width="150">
            <template slot-scope="scope">
              <div class="operate">
                <!-- <el-link type="primary" @click.native="details(scope.row)">
                        <el-tooltip class="item" effect="dark" content="下载" placement="top">
                        <i class="el-icon-document"></i>
                        </el-tooltip>  
                    </el-link> -->
                <el-link type="primary" @click.native="handleDownload(scope.row)"
                  v-if="(scope.row.fileGuid && (scope.row.state !== 0 || scope.row.state !== 1))">
                  <el-tooltip class="item" effect="dark" content="下载" placement="top">
                    <i class="iconfont icon-xiazai"></i>
                  </el-tooltip>
                </el-link>

                <el-link class="margin-left_10" type="primary" @click="updateImportTaskState(scope.row, 4)"
                  v-if="scope.row.state == 1 || scope.row.state == 0">
                  <el-tooltip class="item" effect="dark" content="暂停" placement="top">
                    <i class="iconfont icon-zanting1"></i>
                  </el-tooltip>
                </el-link>
                <el-link class="margin-left_10" type="primary" @click="updateImportTaskState(scope.row, 0)"
                  v-if="scope.row.state == 4">
                  <el-tooltip class="item" type="primary" effect="dark" content="继续" placement="top">
                    <i class="iconfont icon-zanting"></i>
                  </el-tooltip>
                </el-link>
                <el-link class="margin-left_10" type="primary" v-if="scope.row.taskType == 1"
                  @click="updateLog(scope.row)">
                  <el-tooltip class="item" effect="dark" content="更新记录" placement="top">
                    <i class="iconfont icon-banbengengxinjilu" style="font-size:18px"></i>
                  </el-tooltip>
                </el-link>
                <el-link class="margin-left_10" type="danger" @click.native="updateImportTaskState(scope.row, 5)"
                  v-if="(scope.row.state != 2 && scope.row.state != 5) || scope.row.taskType == 1">
                  <el-tooltip class="item" effect="dark" content="取消" placement="top">
                    <i class="iconfont icon-quxiaorenwu1"></i>
                  </el-tooltip>
                </el-link>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-main>
      <el-footer 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>
      </el-footer>
    </el-container>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { downLoad2 } from '@/utils'
export default {
  components: {},
  props: {
    importToId: ''
  },
  data() {
    return {
      //固定检索字段
      searchFiled2: {
        projectId: this.importToId
      },
      //检索字段
      searchFiled: [],
      //检索条件
      searchOption: {},
      //加载中
      loading: false,
      //任务的数据集合
      tableData: [],
      //分页信息
      queryParams: {
        current: 1,
        size: 10
      },
      //总条数
      total: 0,
      //排序
      sort: [
        {
          "orderBy": "createTime",
          "orderType": 1
        }
      ],
      columnList: [],//搜索的栏位
      showView: false,

      customColors: [
        { color: '#f56c6c', percentage: 20 },
        { color: '#e6a23c', percentage: 40 },
        { color: '#5cb87a', percentage: 60 },
        { color: '#1989fa', percentage: 80 },
        { color: '#6f7ad3', percentage: 100 }
      ],
    };
  },
  watch: {},
  computed: {
    ...mapGetters(['webSocket', 'userinfo']),
    importType() {
      var a = this.$store.state.dictMessage.dictMessage.IMPORT_TASK_TYPE || []
      if (a.length > 0) {
        var obj = this.searchFiled.find(item => {
          return item.value == 'type'
        })
        if (obj) {
          obj.options = a
        }
      }
      return this.$store.state.dictMessage.dictMessage.IMPORT_TASK_TYPE || []
    },
    state() {
      var a = this.$store.state.dictMessage.dictMessage.IMPORT_TASK_TYPE || []
      if (a.length > 0) {
        var obj = this.searchFiled.find(item => {
          return item.value == 'state'
        })
        if (obj) {
          obj.options = a
        }
      }
      return this.$store.state.dictMessage.dictMessage.IMPORT_TASk_STATE
    }
  },
  created() { },
  async mounted() {
    this.initTask()
    this.columnList = await this.$commonJS.getCustomField('importTask')
    //获取table栏位及分组字段
    await this.getColumn()
    this.getList()
  },
  methods: {
    initTask() {

      //   var webSocket = this.webSocket
      //   console.log(webSocket)
      this.webSocket.onmessage = (e) => {
        if (e.data.indexOf('{') == -1) {
          return false
        }
        const { code, data, message } = JSON.parse(e.data)
        console.log({ code, data, message });
        //         var a = {
        //     "code": 903,
        //     "data": {
        //         "total": 9,
        //         "index": 0,
        //         "taskId": 117,
        //         "taskStatus": 1,
        //         "complete": false,
        //         "url": "",
        //         "fileName": "cd30d6d6285d49229be2a73c6812f457",
        //         "taskType": 1,
        //         "percentage": 0,
        //         "oldName": ""
        //     },
        //     "message": "WebSocket请求成功"
        // }
        if (code === 900 || code === 602 || code === 604) {
          if (data.doneType == -1 || code === 602 || code === 604) {
            const index = this.tableData.findIndex(item => { return item.id == data.taskId })
            if (index === -1) {

            } else {
              this.$set(this.tableData[index], 'doneNum', data.index)
              this.$set(this.tableData[index], 'percentage', data.percentage)
              this.$set(this.tableData[index], 'state', data.taskStatus)
            }
          }
        }
        if (code === 903 || code === 603 || code === 605) {
          // const index = this.tableData.findIndex(item => { return item.id == data.taskId })
          // if (index === -1) {

          // } else {
          //   this.$set(this.tableData[index], 'doneNum', data.index)
          //   this.$set(this.tableData[index], 'percentage', data.percentage)
          //   this.$set(this.tableData[index], 'state', data.taskStatus)
          // }
          if (data.complete) {
            this.getList()
          }
        }
       
      }
    },
    //显示视图?
    showViews() {
      this.showView = false
      this.$nextTick(() => {
        this.showView = true
      })
    },
    //获取table栏位及分组字段、检索字段
    async getColumn() {
      let params = ['importTask']
      await this.$api.getParamsCommon(params).then(res => {
        if (res.code == 200) {
          let conditionDTOList = JSON.parse(JSON.stringify(res.data[0].conditionDTOList))
          // 搜索字段
          this.searchFiled = this.$commonJS.getField(conditionDTOList, (u) => u.ifSearch == true, {
            label: 'name',
            value: 'value',
            type: 'type',
          })
          var options = ['type', 'state']
          options.forEach(item => {
            this.getOption(item)
          })

        }
      })
      this.showViews()
    },
    getOption(type) {
      var obj = this.searchFiled.find(item => {
        return item.value == type
      })
      if (!obj) {
        return false
      }
      switch (type) {
        case 'type':
          obj.options = this.importType
          break;
        case 'state':
          obj.options = this.state
          break;
      }
    },
    //获取检索条件检索
    search(val) {
      let params = {}
      val.forEach(item => {
        if (item.type == 3) {
          params[item.value] = item.searchValue.map(itemValue => {
            return itemValue.value
          })
        } else {
          params[item.value] = item.searchValue.label
        }
      })
      // 返回条件对象
      this.searchOption = this.$commonJS.ArrayToArray(val)
      // 调用查询接口
      this.queryParams.current = 1
      this.getList()
    },
    //获取任务
    getList() {
      // var params = {
      //     ...this.searchFiled2,
      //     ...this.searchOption
      // }
      var searchFiled2 = this.$commonJS.objectToArray(this.searchFiled2)
      var searchOption1 = this.searchOption
      if (this.searchOption.constructor == Object) {
        searchOption1 = this.$commonJS.objectToArray(this.searchOption)
      }
      let searchOption = [
        ...searchFiled2,//固有检索字段
        ...searchOption1
      ]
      var params = {
        ...this.queryParams,
        searchQuery: this.$commonJS.objectToString(searchOption),
        orderDTOList: this.sort
      }
      this.$api.queryImportTask(params).then(res => {
        if (res.code == 200) {
          this.tableData = res.data.data
          this.total = res.data.total
        }
      }).catch(err => {
        this.tableData = []
        this.total = 0
      })
    },
    //分页
    handleCurrentChange(val) {
      this.queryParams.current = val
      this.getList()
    },
    //排序
    sortChange({ column, prop, order }) {
      //如需要多个字段排序，则不需要清空
      var params = {
        sort: this.sort,
        column,
        prop,
        order,
      }
      this.sort = this.$commonJS.getSortData(params)
      this.queryParams.current = 0
      this.disabled = false
      this.tableData = []
      this.getList()
    },
    // 网站导入暂停，继续任务操作
    async updateImportTaskState(row, state) {
      this.$api.updateImportTaskState({ taskId: row.id, state: state }).then(response => {
        if (response.code == 200) {
          this.$set(row, 'state', state)
          this.$message.success('操作成功')
        }
      })
    },
    //任务详情
    details() {

    },
    //下载附件
    handleDownload(row) {
      downLoad2(row.fileGuid)
    }
  },
};
</script>
<style lang="scss" scoped></style>