<template>
  <div>
    <search-layout :needBox="true">
      <template slot="searchItem1">
        <span class="label">任务名称</span>
        <el-input
          v-model="searchParams.name"
          size="small"
          clearable
          placeholder="请输入"
          maxlength="60"
          @keyup.enter.native="doSearch(false)"
        >
        </el-input>
      </template>
      <template slot="searchItem2">
        <span class="label">上传时间</span>
        <!-- <el-date-picker
                    v-model="uploadDate"
                    type="daterange"
                    format="yyyy-MM-dd"
                    value-format="yyyy-MM-dd"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                >
                </el-date-picker> -->
        <el-date-picker
          v-model="searchParams.timeBegin"
          type="date"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          placeholder="开始日期"
          class="dateRangeInput"
        >
        </el-date-picker>
        <span class="dateSeparator">至</span>
        <el-date-picker
          v-model="searchParams.timeEnd"
          type="date"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          placeholder="结束日期"
          class="dateRangeInput"
        >
        </el-date-picker>
      </template>

      <template slot="searchBtn1">
        <el-button type="primary" @click="doSearch(false)">查询</el-button>
      </template>
      <template slot="searchBtn2">
        <el-button type="primary" @click="doReset">重置</el-button>
      </template>
    </search-layout>

    <div class="btnsPanel">
      <el-button
        type="primary"
        icon="el-icon-circle-plus-outline"
        @click="addOne"
        >新增</el-button
      >
    </div>

    <tableList
      ref="table"
      style="margin: 0 30px"
      :columns="columns"
      :getDataWay="getDataWay"
      :pagination="pagination"
      index
    >
      <el-table-column label="操作" slot="cgInfos" align="center">
        <template v-slot="scope">
          <!-- <span
                        v-if="scope.row.errorMessage"
                        @click="viewRow(scope.row.errorMessage)"
                        class="errRecord tdBtn"
                        >错误记录</span
                    > -->
          <i
            v-if="scope.row.errorMessage"
            @click="viewRow(scope.row.errorMessage)"
            class="el-icon-document elIcon tdBtn"
            title="错误记录"
          ></i>
          <i
            @click="delRow(scope.row.id)"
            class="el-icon-delete elIcon tdBtn"
            title="删除"
          ></i>
        </template>
      </el-table-column>
    </tableList>

    <el-dialog
      title="场景上传"
      :visible.sync="dialogVisible"
      width="690px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="uploadCancel"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="128px">
        <el-form-item label="任务名称:" prop="name">
          <el-input
            placeholder="请输入"
            maxlength="60"
            v-autoTrim="{ obj: form, key: 'name' }"
            v-model="form.name"
          >
          </el-input>
        </el-form-item>

        <el-form-item label="场景分类:" prop="sceneType">
          <el-select v-model="form.sceneType" @change="sceneTypeChange">
            <el-option
              v-for="item in sceneTypeList"
              :label="item.caption"
              :value="item.code"
              :key="item.code"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- 三个真实场景时展示 -->
        <el-form-item
          v-if="form.sceneType != '4'"
          label="场景路径:"
          prop="dataDirectory"
        >
          <el-input
            placeholder="请输入"
            maxlength="300"
            v-autoTrim="{ obj: form, key: 'dataDirectory' }"
            v-model="form.dataDirectory"
          >
          </el-input>
        </el-form-item>
        <el-form-item
          v-if="form.sceneType != '4'"
          label="复杂度评价脚本:"
          prop="sceneEvaluationRuleId"
        >
          <el-select placeholder="暂不评价" v-model="form.sceneEvaluationRuleId" >
            <el-option
              v-for="item in scriptOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <!-- 泛化时展示 -->
        <el-form-item
          v-if="form.sceneType === '4'"
          label="文件上传:"
          prop="fileName"
        >
          <el-input
            placeholder="请输入"
            maxlength="600"
            v-autoTrim="{ obj: form, key: 'fileName' }"
            v-model="form.fileName"
            disabled
          >
          </el-input>
          <upload
            ref="upload"
            class="upload"
            @handleChange="handleChange"
          ></upload>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button type="primary" @click="uploadConfirm">确 定</el-button>
        <el-button @click="uploadCancel">取 消</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="错误记录"
      :visible.sync="errRocordVisible"
      width="690px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="errClose"
    >
      <div>{{ errorMessage }}</div>
      <span slot="footer">
        <el-button type="primary" @click="errClose">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import searchLayout from '@/components/grid/searchLayout'
import tableList from '@/components/grid/TableList'
import upload from './components/upload'

export default {
  name: 'sceneUploadList', // 场景上传
  components: { searchLayout, tableList, upload },

  data() {
    let formatSeconds = function formatSeconds(value) {
      var theTime = parseInt(value) // 秒
      var theTime1 = 0 // 分
      var theTime2 = 0 // 小时
      if (theTime > 60) {
        theTime1 = parseInt(theTime / 60)
        theTime = parseInt(theTime % 60)
        if (theTime1 > 60) {
          theTime2 = parseInt(theTime1 / 60)
          theTime1 = parseInt(theTime1 % 60)
        }
      }
      var result = '' + parseInt(theTime) + '秒'
      if (theTime1 > 0) {
        result = '' + parseInt(theTime1) + '分' + result
      }
      if (theTime2 > 0) {
        result = '' + parseInt(theTime2) + '小时' + result
      }
      return result
    }

    return {
      searchParams: {
        //搜索参数
        name: '', // 任务名称
        timeBegin: '', // 上传时间起
        timeEnd: '', // 上传时间止
      },
      uploadDate: '',
      columns: [
        {
          label: '任务名称',
          prop: 'name',
        },
        {
          label: '场景分类',
          prop: 'sceneType',
        },
        {
          label: '上传时间',
          prop: 'createTime',
        },
        {
          label: '上传状态',
          prop: 'status',
        },
        {
          label: '总用时长',
          prop: 'totalTime',
          formatter: (row) => {
            if (row.totalTime)
              if (row.totalTime && !isNaN(row.totalTime)) {
                return formatSeconds(row.totalTime)
              }
          },
        },
        {
          label: '操作',
          prop: 'cgInfos',
          template: true,
        },
      ],
      pagination: {
        //分页使用
        currentPage: 1,
        pageSize: 10,
        position: 'right',
        pageSizes: [10, 30, 50, 100, 200],
        layout: 'sizes, total, prev, pager, next, jumper',
      },
      getDataWay: {
        //加载表格数据
        dataType: 'url',
        type: 'post',
        // firstRequest: false,
        data: this.$api.systemManagement.getSceneImporPagetList,
        param: {},
      },
      form: {
        name: '', // 任务名称
        sceneType: '', // 场景分类
        dataDirectory: '', // 场景路径
        fileName: '', // 文件名称
        sceneEvaluationRuleId: '', // 复杂度评价脚本
      },
      rules: {
        name: [{ required: true, message: '请输入', trigger: 'blur' }],
        sceneType: [{ required: true, message: '请选择', trigger: 'change' }],
        dataDirectory: [{ required: true, message: '请输入', trigger: 'blur' }],
        fileName: [{ required: true, message: '请上传', trigger: 'change' }],
      },
      sceneTypeList: [],
      dialogVisible: false,
      file: null,
      errRocordVisible: false,
      errorMessage: '',
      timer: null,
      //   测试mock数据
      scriptOptions: [],
    }
  },

  methods: {
    doSearch(isTimer = false) {
      // if (this.uploadDate) {
      //     this.searchParams.timeBegin = `${this.uploadDate[0]}`;
      //     this.searchParams.timeEnd = `${this.uploadDate[1]}`;
      // } else {
      //     this.searchParams.timeBegin = "";
      //     this.searchParams.timeEnd = "";
      // }

      let timeBegin = ''
      if (this.searchParams.timeBegin) {
        timeBegin = `${this.searchParams.timeBegin} 00:00:00`
      }

      let timeEnd = ''
      if (this.searchParams.timeEnd) {
        timeEnd = `${this.searchParams.timeEnd} 23:59:59`
      }

      if (timeBegin && timeEnd && timeBegin > timeEnd) {
        this.$message.error('结束时间不能早于开始时间')
        return
      }

      let pageMap = {
        name: this.searchParams.name,
        timeBegin,
        timeEnd,
        resetPageNum: !isTimer ? false : this.pagination.currentPage || 1,
      }

      if (!isTimer) this.pagination.currentPage = 1

      this.refreshList(pageMap)

      if (this.timer) clearInterval(this.timer)

      this.timer = setInterval(() => {
        if (this.$refs['table']) this.doSearch(true)
      }, 1000 * 60)
    },
    //刷新table
    refreshList(param) {
      param
        ? this.$refs['table'].loadData(param)
        : this.$refs['table'].loadData()
    },
    doReset() {
      this.searchParams = {
        name: '',
        timeBegin: '',
        timeEnd: '',
      }
      // this.uploadDate = "";
      this.doSearch(false)
    },
    addOne() {
      this.form = {
        name: '', // 任务名称
        sceneType: '', // 场景类型
        dataDirectory: '', // 场景路径
        fileName: '', // 文件上传
        sceneEvaluationRuleId: '', // 复杂度评价脚本
      }
      this.file = null

      this.dialogVisible = true

      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
      this.getScriptList()
    },
    // 获取脚本列表
    getScriptList(){
     this.$axios({
        method: 'post',
        url: this.$api.sceneLibrary.getScriptListByType,
        data: {
          sceneEvaluationType: ["1"]},
      }).then(res=>{
        const arr = (res.info[1] || []).map(item=>{
          item.label = item.scriptName
          item.value = item.ruleId
          return item
        })
        this.scriptOptions = [...arr]
      })
    },

    viewRow(errorMessage) {
      this.errorMessage = errorMessage
      this.errRocordVisible = true
    },
    delRow(id) {
      this.$confirm(
        '确认是否删除？（温馨提示：文件较大，删除时间较长请您耐心等待）',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(() => {
        this.$axios({
          method: 'post',
          url: this.$api.systemManagement.deleteTask,
          timeout: 1000 * 60 * 30,
          data: {
            id,
          },
        }).then((res) => {
          if (res.code == 200) {
            this.$message.success('删除成功')
          } else {
            this.$message.error(res.message || '删除失败')
          }
          this.doSearch()
        })
      })
    },
    errClose() {
      this.errRocordVisible = false
      this.errorMessage = ''
    },
    uploadConfirm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          if (this.form.sceneType === '4') {
            let formData = new FormData()
            await formData.append('taskName', this.form.name)
            await formData.append('name', this.file.name)
            await formData.append('file', this.file.raw)

            await this.$axios({
              method: 'post',
              url: this.$api.systemManagement.saveSceneGeneralTemplateAll,
              data: formData,
              withCredentials: true,
              headers: {
                'Content-type': 'multipart/form-data',
              },
            }).then((res) => {
              if (res.code == 200) {
                this.$message.success('保存成功')
                this.uploadCancel()
                this.doSearch()
              } else {
                this.$message.error(res.message || '保存失败')
              }
            })
          } else {
            this.$axios({
              method: 'post',
              url: this.$api.systemManagement.saveTask,
              data: { ...this.form },
            }).then((res) => {
              if (res.code == 200) {
                this.$message.success('保存成功')
                this.uploadCancel()
                this.doSearch()
              } else {
                this.$message.error(res.message || '保存失败')
              }
            })
          }
        }
      })
    },
    uploadCancel() {
      this.dialogVisible = false
    },
    attachmentChange(obj) {
      this.attachmentList = obj
    },
    handleChange(file) {
      this.file = file
      this.form.fileName = file.name
    },
    sceneTypeChange(v) {
      if (v === '4') {
        this.$refs.form.clearValidate('dataDirectory')
      } else {
        this.file = null
        this.form.fileName = ''
        this.$refs.form.clearValidate('fileName')
      }
    },
  },

  async mounted() {
    if (this.timer) clearInterval(this.timer)

    this.timer = setInterval(() => {
      if (this.$refs['table']) this.doSearch(true)
    }, 1000 * 60)

    await this.$dicsListsInit({
      sceneTypeList: 'sceneType',
    })
  },

  beforeDestroy() {
    clearInterval(this.timer)
  },
}
</script>

<style lang='less' scoped>
.btnsPanel {
  margin: 45px 40px 15px;
  text-align: right;
}

.errRecord {
  color: @themeColor;
  cursor: pointer;
}

.tdBtn {
  margin-right: 10px;

  &:last-child {
    margin-right: 0;
  }
}

.upload {
  margin-top: 15px;
}
</style>