<!--  -->
<template>
  <div class=''>
    <el-breadcrumb class="divi2" separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>数据集管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider class="divi"></el-divider>

    <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
      <el-form-item>
        <el-button v-if="isAuth('dataset:save')" type="primary" @click="addHandle()">新建数据集</el-button>
        <el-button v-if="isAuth('dataset:delete')" type="danger" @click="status==='1'?deleteHandle(dataListSelections):dy_deleteHandle(dy_dataListSelections)"
                   :disabled="dataListSelections.length <= 0 && dy_dataListSelections.length <= 0">批量删除</el-button>
        <!--        <el-button v-if="isAuth('sys:schedule:delete')" type="danger" @click="deleteHandle()" :disabled="dataListSelections.length <= 0">批量删除</el-button>-->
        <!--        <el-button v-if="isAuth('sys:schedule:pause')" type="danger" @click="" :disabled="dataListSelections.length <= 0">批量暂停</el-button>-->
        <!--        <el-button v-if="isAuth('sys:schedule:resume')" type="danger" @click="" :disabled="dataListSelections.length <= 0">批量恢复</el-button>-->
        <!--        <el-button v-if="isAuth('sys:schedule:run')" type="danger" @click="" :disabled="dataListSelections.length <= 0">批量立即执行</el-button>-->
        <!--        <el-button v-if="isAuth('sys:schedule:log')" type="success" @click="">日志列表</el-button>-->

      </el-form-item>
      <el-form-item>
        <el-input v-model="dataForm.datasetName" placeholder="请输入数据集名称" clearable
          @keyup.enter.native="pageIndex = 1;getDataList()"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="pageIndex = 1;getDataList()">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-tag>筛选:</el-tag>
        <el-select v-model="classificationtag" placeholder="类别" size="mini" style="width: 130px;"
          @change="pageIndex = 1;getDataList2()">
          <el-option v-for="data in classification" :key="data.categoryId" :label="data.categoryName" :value="data.categoryId">
          </el-option>
        </el-select>
        <el-select v-model=status placeholder="动静状态" size="mini" style="width: 130px;"
          @change="pageIndex = 1;getDataList2()">
          <el-option label='静态' value='1'>
          </el-option>
          <el-option label='动态' value='2'>
          </el-option>
        </el-select>
      </el-form-item>


    </el-form>

    <el-table v-show="(status ==='1') " :data="st_dataList" border v-loading="dataListLoading" @selection-change="selectionChangeHandle"
              style="width: 100%;">
      <el-table-column type="selection" header-align="center" align="center" width="50">
      </el-table-column>
<!--      <el-table-column prop="datasetId" header-align="center" align="center" width="80" label="数据集ID">-->
<!--      </el-table-column>-->

      <el-table-column label="序号" header-align="center" align="center" width="80" type="index" :index='(index)=>{return (index+1) + (this.pageIndex-1)*this.pageSize}'> </el-table-column>


      <el-table-column prop="datasetName" header-align="center" align="center" label="数据集名称">
      </el-table-column>
      <el-table-column prop="categoryName" header-align="center" align="center" label="分类">
      </el-table-column>
      <el-table-column prop="username" header-align="center" align="center" label="创建人">
      </el-table-column>
      <el-table-column prop="datasetStatus" header-align="center" align="center" label="状态" :formatter="stateFormat">
      </el-table-column>
      <el-table-column prop="createTime" header-align="center" align="center" width="180" label="创建时间">
      </el-table-column>
      <el-table-column prop="remark" header-align="center" align="center" label="备注">
      </el-table-column>
      <el-table-column fixed="right" header-align="center" align="center" width="200" label="操作">
        <template slot-scope="scope">
          <el-button v-if="isAuth('dataset:list')" type="text" size="small" @click="userwatch(scope.row)">查看
          </el-button>
          <el-button v-if="isAuth('dataset:update')" type="text" size="small"
            @click="addOrUpdateHandle(scope.row)">修改</el-button>
          <el-button v-if="isAuth('dataset:delete')" type="text" size="small"
            @click="deleteHandle(scope.row)">
            删除</el-button>
          <el-button type="text" size="small" @click="downloadDataset(scope.row.datasetName)">下载
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-table   v-show="status ==='2' "  :data="dy_dataList" border v-loading="dataListLoading" @selection-change="selectionChangeHandle"
              style="width: 100%;">
      <el-table-column type="selection" header-align="center" align="center" width="50">
      </el-table-column>
<!--      <el-table-column prop="datasetId" header-align="center" align="center" width="80" label="数据集ID">-->
<!--      </el-table-column>-->

<!--      设置序号 -->
      <el-table-column label="序号" header-align="center" align="center" width="80" type="index" :index='(index)=>{return (index+1) + (this.pageIndex-1)*this.pageSize}'> </el-table-column>

      <el-table-column prop="datasetName" header-align="center" align="center" label="数据集名称">
      </el-table-column>
      <el-table-column prop="categoryName" header-align="center" align="center" label="分类">
      </el-table-column>
      <el-table-column prop="username" header-align="center" align="center" label="创建人">
      </el-table-column>
      <el-table-column prop="status" header-align="center" align="center" label="状态">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 0" size="small">正常</el-tag>
          <el-tag v-else size="small" type="danger">暂停</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="cronExpression" header-align="center" align="center" label="抽取周期">
      </el-table-column>
      <el-table-column prop="createTime" header-align="center" align="center" width="180" label="创建时间">
      </el-table-column>
      <el-table-column prop="remark" header-align="center" align="center" label="备注">
      </el-table-column>
      <el-table-column fixed="right" header-align="center" align="center" width="350" label="操作">
        <template slot-scope="scope">
          <el-button v-if="isAuth('sys:schedule:update')" type="text" size="small" @click="dy_UpdateHandle(scope.row)">修改</el-button>
          <el-button v-if="isAuth('sys:schedule:delete')" type="text" size="small" @click="dy_deleteHandle(scope.row)">删除</el-button>
          <el-button v-if="isAuth('sys:schedule:pause')" type="text" size="small" @click="dy_pauseHandle(scope.row)">暂停</el-button>
          <el-button v-if="isAuth('sys:schedule:resume')" type="text" size="small" @click="dy_resumeHandle(scope.row)">恢复</el-button>
          <el-button v-if="isAuth('sys:schedule:run')" type="text" size="small" @click="dy_runHandle(scope.row)">执行</el-button>
          <el-button v-if="isAuth('sys:schedule:log')" type="text" size="small" @click="dy_logHandle(scope.row)">日志</el-button>

          <el-button type="text" size="small" @click="downloadDataset(scope.row.datasetName)">下载</el-button>
          <!-- <el-button type="text" size="small" @click="openDataPreProcessDialog(scope.row.datasetName)">预处理</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
<!--    <AddOrUpdate v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></AddOrUpdate>-->
<!--    <Watch v-if="newWatchVisible" ref="newWatch" @refreshDataList="getDataList"></Watch>-->
    <Add v-if="addVisible" ref="addS" @refreshDataList="getDataList"></Add>
    <stdataset-updata v-if="addOrUpdateVisible" ref="staddOrUpdate" @refreshDataList="getDataList"></stdataset-updata>
<!--    动态数据集 弹窗 修改-->
    <dydataset-updata v-if="dyUpdateVisible" ref="dyUpdate" @refreshDataList="getDataList"></dydataset-updata>
    <dylog v-if="logVisible" ref="log"></dylog>

    <!-- 数据预处理弹出框 -->
    <DataPreProcess v-if="dataPreProcessVisible" ref="dataPreProcess"></DataPreProcess>

  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';
import Add from './dataset-add'
import dydatasetUpdata from './dydataset-updata'
import stdatasetUpdata from './stdataset-updata'
import dylog from './dy-schedule-log'
import DataPreProcess from './datapreprocess'
import { MessageBox } from 'element-ui'
import { Message } from "element-ui"
export default {
  // import引入的组件需要注入到对象中才能使用
  data () {
    return {
      dataForm: {
        datasetName: ''
      },
      logVisible: false,
      dyUpdateVisible: false,
      dataPreProcessVisible: false,
      st_dataList: [],
      dy_dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      dy_dataListSelections: [],
      addOrUpdateVisible: false,
      newWatchVisible: false,
      addVisible: false,
      classificationtag: '',
      classification: [],
      status: '1'
    }
  },
  components: {
    Add,
    dydatasetUpdata,
    dylog,
    stdatasetUpdata,
    DataPreProcess
  },

  activated () {
    if (this.$route.query.status) {
      this.status = this.$route.query.status
    }
    this.getDataList()
  },
  methods: {
    // 获取数据列表
    getDataList () {
      this.dataListLoading = true
      this.classificationtag = null
      // this.status = null
      this.$http({
        url: this.$http.adornUrl('/category/select'),
        method: 'get'
      }).then(({ data }) => {
        this.classification = this.unique(data.list)
      })

      if (this.status === '1') {
        this.$http({
          url: this.$http.adornUrl('/dataset/list'),
          method: 'get',
          params: this.$http.adornParams({
            page: this.pageIndex,
            limit: this.pageSize,
            datasetName: this.dataForm.datasetName
          })
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.st_dataList = data.page.list.reverse()
            this.totalPage = data.page.totalCount
            this.statusunique = this.unique(data.page.list)
          } else {
            this.st_dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
        })
      } else {
        this.$http({
          url: this.$http.adornUrl('/datasetdy/list'),
          method: 'get',
          params: this.$http.adornParams({
            page: this.pageIndex,
            limit: this.pageSize,
            datasetName: this.dataForm.datasetName
          })
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.dy_dataList = data.page.list.reverse()
            this.totalPage = data.page.totalCount
            this.statusunique = this.unique(data.page.list)
          } else {
            this.dy_dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
        })
      }
    },

    // 筛选查询
    getDataList2 () {
      this.dataListLoading = true

      if (this.status === '1') {
        // 获取静态数据集
        this.st_dataList = []
        this.$http({
          url: this.$http.adornUrl('/dataset/list'),
          method: 'get',
          params: this.$http.adornParams({
            page: this.pageIndex,
            limit: this.pageSize,
            modelName: this.dataForm.modelName,
            // 增加status参数用于筛选查询
            classificationtag: this.classificationtag,
            status: this.status
          })
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.st_dataList = data.page.list.reverse()
            this.totalPage = data.page.totalCount
          } else {
            this.st_dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
        })
      } else {
        this.dy_dataList = []
        // 获取动态数据集
        this.$http({
          url: this.$http.adornUrl('/datasetdy/list'),
          method: 'get',
          params: this.$http.adornParams({
            page: this.pageIndex,
            limit: this.pageSize,
            modelName: this.dataForm.modelName,
            // 增加status参数用于筛选查询
            classificationtag: this.classificationtag,
            status: this.status
          })
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.dy_dataList = data.page.list.reverse()
            this.totalPage = data.page.totalCount
          } else {
            this.dy_dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
        })
        this.dataListLoading = false
      }
    },
    stateFormat (row, column) {
      if (row.datasetStatus === 1) {
        return '静态数据集'
      }
    },
    // 去重
    unique (arr) {
      var ss = []
      for (var i = 0; i < arr.length; i++) {
        // ss[i] = arr[i].categoryName
        ss[i] = arr[i]
      }
      return Array.from(new Set(ss))
    },
    // 每页数
    sizeChangeHandle (val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle (val) {
      this.pageIndex = val
      this.getDataList()
    },
    // 多选
    selectionChangeHandle (val) {
      if (this.status === '1') {
        this.dataListSelections = val
      } else if (this.status === '2') {
        this.dy_dataListSelections = val
      }
    },
    // 查看
    userwatch (info) {
      this.addOrUpdateVisible = true
      info.readOnly = true
      this.$set(info, 'classification', this.classification)
      this.$nextTick(() => {
        this.$refs.staddOrUpdate.init(info)
      })
    },
    addOrUpdateHandle (info) {
      this.addOrUpdateVisible = true
      // this.$nextTick(() => {
      //   this.$refs.addOrUpdate.init(info)
      // // })
      info.readOnly = false
      this.$set(info, 'classification', this.classification)
      this.$nextTick(() => {
        this.$refs.staddOrUpdate.init(info)
      })
    },
    // 这里处理新建
    addHandle () {
      this.addVisible = true
      this.$nextTick(() => {
        this.$refs.addS.init()
      })
    },
    // 删除
    deleteHandle (info) {
      var datasetId = info.datasetId
        ? [info.datasetId] : this.dataListSelections.map((item) => {
          return item.datasetId
        })
      var datasetName = info.datasetName ? [info.datasetName] : this.dataListSelections.map(item => {
        return item.datasetName
      })

      MessageBox.confirm(
        `确定对[数据集=${datasetName.join(' , ')}]进行[${info.datasetId ? '删除' : '批量删除'}]操作?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          this.dataListLoading = true
          this.$http({
            url: this.$http.adornUrl('/dataset/delete'),
            method: 'post',
            data: this.$http.adornData(datasetId, false)
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.dataListLoading = false
              Message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataList()
                }
              })
              this.pageIndex = 1
            } else {
              Message.error(data.msg)
            }
          })
        })
        .catch(() => {})
    },
    // 日志列表
    dy_logHandle (info) {
      this.logVisible = true

      this.$nextTick(() => {
        this.$refs.log.init(info)
      })
    },
    //  修改
    dy_UpdateHandle (info) {
      // 将算法分类 添加到数据info 中 传递给子组件
      this.$set(info, 'classification', this.classification)
      this.dyUpdateVisible = true

      this.$nextTick(() => {
        this.$refs.dyUpdate.init(info)
      })
    },
    // 暂停
    dy_pauseHandle (info) {
      var ids = info.jobId ? [info.jobId] : this.dy_dataListSelections.map(item => {
        return item.jobId
      })
      MessageBox.confirm(`确定对 [数据集 =${info.datasetName}]进行[${ids ? '暂停' : '批量暂停'}]操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.dataListLoading = true
        this.$http({
          url: this.$http.adornUrl('/sys/schedule/pause'),
          method: 'post',
          data: this.$http.adornData(ids, false)
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.dataListLoading = false
            Message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getDataList()
              }
            })
          } else {
            Message.error(data.msg)
          }
        })
      }).catch(() => {})
    },
    // 恢复
    dy_resumeHandle (info) {
      var ids = info.jobId ? [info.jobId] : this.dy_dataListSelections.map(item => {
        return item.jobId
      })
      MessageBox.confirm(`确定对 [数据集 =${info.datasetName}]进行[${ids ? '恢复' : '批量恢复'}]操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.dataListLoading = true
        this.$http({
          url: this.$http.adornUrl('/sys/schedule/resume'),
          method: 'post',
          data: this.$http.adornData(ids, false)
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.dataListLoading = false
            Message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getDataList()
              }
            })
          } else {
            Message.error(data.msg)
          }
        })
      }).catch(() => {})
    },
    // 删除
    dy_deleteHandle (info) {
      var ids = info.datasetId ? [info.datasetId] : this.dy_dataListSelections.map(item => {
        return item.datasetId
      })
      var datasetName = info.datasetName ? [info.datasetName] : this.dy_dataListSelections.map(item => {
        return item.datasetName
      })
      MessageBox.confirm(`确定对 [数据集 =${datasetName.join(' , ')}]进行[${ids ? '删除' : '批量删除'}]操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.dataListLoading = true
        this.$http({
          url: this.$http.adornUrl('/sys/schedule/delete'),
          method: 'post',
          data: this.$http.adornData(ids, false)
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.dataListLoading = false
            Message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getDataList()
              }
            })
          } else {
            Message.error(data.msg)
          }
        })
      }).catch(() => {})
    },
    // 立即执行
    dy_runHandle (info) {
      var ids = info.jobId ? [info.jobId] : this.dy_dataListSelections.map(item => {
        return item.jobId
      })
      MessageBox.confirm(`确定对 [数据集 =${info.datasetName}]进行[${info.jobId ? '立即执行' : '批量立即执行'}]操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/sys/schedule/run'),
          method: 'post',
          data: this.$http.adornData(ids, false)
        }).then(({data}) => {
          if (data && data.code === 0) {
            Message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getDataList()
              }
            })
          } else {
            Message.error(data.msg)
          }
        })
      }).catch(() => {})
    },
    // 下载数据集
    downloadDataset (filename) {
      
      MessageBox.confirm(`是否下载该数据集?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/dataset/downloadDataset'),
          method: 'get',
          params: this.$http.adornParams({
            datasetName: filename + '.csv'
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            window.location.href = data.downloadUrl
          } else {
            Message.error('下载失败')
          }
        })
      }).catch(() => {})
    },
    // 弹出数据集预处理框
    openDataPreProcessDialog (filename) {
      this.dataPreProcessVisible = true
      this.$nextTick(() => {
        this.$refs.dataPreProcess.init(filename)
      })
    }
  }

}
</script>

<style scoped>
.divi {
  display: block;
  height: 1px;
  width: 100%;
  margin: 24px 0;
  background-color: #dcdfe6;
  position: relative;
}
.divi2 {
  display: block;
  height: 1px;
  width: 100%;
  position: relative;
}
.sele {
  border: 1px solid #409eff;
  border-radius: 5px;
  box-sizing: border-box;
  padding: 5px 0px;
  margin: 10px;
}
</style>
