<template>
  <!-- 质量任务 -->
  <div id="tasks-wrap">
    <div class="left-tree">
      <div class="title">
        <h2>任务目录</h2>
        <div>
          <a-button type="add" @click="getTreeAdd">
            <a-icon type="plus-square" />
          </a-button>
          <a-button type="edit" :disabled="checkedKeys.length===0" @click="treeEdit">
            <a-icon type="edit" />
          </a-button>
          <a-button type="delete" :disabled="checkedKeys.length===0" @click="treeRemove">
            <a-icon type="delete" />
          </a-button>

          <a-modal
            width="800px"
            v-model="treeModalVisible"
            title="新增目录"
            :footer="null"
            :destroyOnClose="true"
            @ok="treeHandleOk">
            <TreeAdd ref="treeModel" :treeData="treeData" @treeHandleOk="treeHandleOk" />
          </a-modal>
          <a-modal title="删除目录" :visible="treeDelVisible" @ok="getTreeRemove" @cancel="handleCancel(0)">
            <p>确认删除所选中目录数据?</p>
          </a-modal>
        </div>
      </div>

      <div class="titleBar">
        <a-input-search placeholder="请输入类别名称/代码" style="width: 200px" @change="onSearch" />
        <div class="action">
          <div @click="onExpandClose">全部收起</div>
        </div>
      </div>
      <a-tree
        v-if="treeData.length>0"
        :replaceFields="{
          title:'catalog',
          key: 'id',
          children:'children',
          value:'id'
        }"
        show-line
        checkable
        :defaultExpandAll="true"
        :expandedKeys="expandedKeys"
        :auto-expand-parent="autoExpandParent"
        :tree-data="treeData"
        @check="onCheck"
        @expand="onExpand"
        @select="onClassSelect">
        <template slot="catalog" slot-scope="{ catalog }">
          <span v-if="catalog.indexOf(searchValue) > -1">
            {{ catalog.substr(0, catalog.indexOf(searchValue)) }}
            <span style="color: #f50">{{ searchValue }}</span>
            {{ catalog.substr(catalog.indexOf(searchValue) + searchValue.length) }}
          </span>
          <span v-else>{{ catalog }}</span>
        </template>
        <a-icon slot="switcherIcon" type="down" />
      </a-tree>
    </div>
    <div class="right-main">
      <h2>质量任务</h2>
      <div class="button-wrap">
        <a-button type="add" @click="addForm">新增</a-button>
        <a-button type="delete" :disabled="$refs.table&&$refs.table.selectedRows.length!==1" @click="getDelete()">删除</a-button>
        <a-button type="edit" @click="editForm" :disabled="$refs.table&&$refs.table.selectedRows.length!==1">编辑</a-button>
        <a-button type="add" :disabled="!isShowStart" @click="startTask()">启用</a-button>
        <a-button type="delete" :disabled="!isShowStop" @click="pauseTask()">暂停</a-button>
      </div>
      <a-modal title="删除" :visible="visible" @ok="delItem" @cancel="handleCancel(1)">
        <p>确认删除所选中数据?</p>
      </a-modal>
      <div class="table-content">
        <FilterTable
          ref="table"
          :columns="columns"
          :searchInput="searchInput"
          :dataSource="dataSource"
          :total="total"
          @changeParams="changeParams" />
      </div>
      <a-modal
        width="800px"
        v-model="modalVisible"
        title="质量任务配置"
        :footer="null"
        :destroyOnClose="true"
        @ok="handleOk">
        <FormModalAdd ref="model" @handleOk="handleOk" @changeModalVisible="changeModalVisible"/>
      </a-modal>

    </div>

  </div>
</template>

<script type="text/ecmascript-6">
import FilterTable from '@/components/filterTable'
import FormModalAdd from './components/FormModalAdd'
import TreeAdd from './components/TreeAdd'

import { getClassTreeApi, getTreeRemove, getList, getRemove, runTask, startTask, pauseTask } from '@/api/quality/tasks'
const getParentKey = (key, tree) => {
  let parentKey
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i]
    if (node.children) {
      if (node.children.some((item) => item.catalogCode === key)) {
        parentKey = node.catalogCode
      } else if (getParentKey(key, node.children)) {
        parentKey = getParentKey(key, node.children)
      }
    }
  }
  return parentKey
}
const dataList = []
const generateList = (data) => {
  for (let i = 0; i < data.length; i++) {
    const node = data[i]
    const id = node.id
    const catalog = node.catalog
    dataList.push({ id, catalog: catalog })
    if (node.children) {
      generateList(node.children)
    }
  }
}

export default {
  components: {
    FilterTable,
    FormModalAdd,
    TreeAdd
  },
  data() {
    var vm = this
    return {
      treeData: [],
      initState: true,
      expandedKeys: [],
      autoExpandParent: true,
      searchValue: '',
      columns: [
        {
          title: '序号',
          dataIndex: 'orderNum',
          key: 'orderNum',
          width: 120,
          align: 'center',
          scopedSlots: { customRender: 'orderNum' }
        },
        {
          title: '任务名称',
          dataIndex: 'taskName',
          key: 'taskName',
          align: 'center',
          scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'customRender'
          },
          ellipsis: true
        },
        {
          title: '任务状态',
          dataIndex: 'taskState',
          key: 'taskState',
          align: 'center',

          customRender: (text, record, index) => {
            if (text === 1) {
              return <span style="color:#2d60d6">已开启</span>
            } else if (text === 0) {
              return <span style="color:red">已暂停</span>
            }
          }
        },
        {
          title: '任务执行周期',
          dataIndex: 'executionMode',
          key: 'executionMode',
          align: 'center',
          customRender: (text, record, index) => {
            if (text === 0) {
              return <span>单次执行</span>
            } else if (text === 1) {
              return <span>周期执行</span>
            }
          }
        },
        {
          title: '最近运行时间',
          dataIndex: 'lastRunTime',
          key: 'lastRunTime',
          align: 'center'
        },
        {
          title: '操作',
          dataIndex: 'operate',
          key: 'operate',
          align: 'center',
          width: 100,
          customRender: (text, record, index) => {
            var child = vm.$createElement('button', {
              domProps: {
                innerHTML: '执行一次'
              },
              on: {
                click: function() {
                  vm.executeOnce(record)
                }
              },
              style: {
                cursor: 'pointer'
              }
            })
            var obj = {
              children: child,
              attrs: {}
            }
            return obj
          }
        }
      ],
      dataSource: [],
      treeId: '',
      taskName: '',
      total: 0,
      searchInput: null,
      modalVisible: false,
      selectedRowsId: [],
      params: {
        pageSize: 10,
        pageNum: 1
      },
      visible: false,
      treeModalVisible: false,
      checkedKeys: [], // 选中目录
      treeDelVisible: false
    }
  },

  mounted() {
    this.initState = false
    this.getClassTree()
  },
  methods: {
    // 任务目录搜索
    onSearch(e) {
      const value = e.target.value
      const expandedKeys = dataList
        .map((item) => {
          if (item.catalog.indexOf(value) > -1) {
            return getParentKey(item.catalog, this.treeData)
          }
          return null
        })
        .filter((item, i, self) => item && self.indexOf(item) === i)
      Object.assign(this, {
        expandedKeys,
        searchValue: value,
        autoExpandParent: true
      })
    },
    // 全部收起
    onExpandClose() {
      this.expandedKeys = []
    },
    onExpand(selectedKeys) {
      this.expandedKeys = selectedKeys
    },
    onClassSelect(selectedKeys, info) {
      this.treeId = selectedKeys[0]
      selectedKeys[0] && this.getTableList('')
      info.node.onExpand()
      // console.log('selected', info.selectedNodes[0].data.props.catalog)
    },
    // 目录选择
    onCheck(checkedKeys, e) {
      this.checkedKeys = checkedKeys
    },
    addAttr(data) {
      data.map((item) => {
        item.scopedSlots = { title: 'catalog' }
        if (item.children) this.addAttr(item.children)
      })
      return data
    },
    // 获取目录
    getClassTree() {
      getClassTreeApi().then((res) => {
        if (res.code === 200) {
          this.treeData = this.addAttr(res.data.rows)
          generateList(this.treeData)
          // console.log('获取目录:', this.treeData)
        }
      })
    },
    // 获取右侧表格
    getTableList() {
      const { treeId, taskName } = this
      getList({ treeId, taskName, ...this.params }).then((res) => {
        if (res.code === 200) {
          this.dataSource = res.rows
          this.dataSource.forEach((item, index) => {
            item.orderNum = index + 1
          })
          this.$refs.table.selectedRows = []
          this.$refs.table.selectedRowKeys = []
        }
      })
      // console.log('获取右侧表格')
    },

    addForm() {
      this.modalVisible = true
      setTimeout(() => {
        this.$refs.model.submitType = 'add'
        this.$refs.model.basicForm = {}
      }, 0)
    },
    editForm() {
      const id = this.$refs.table.selectedRows[0].id
      this.modalVisible = true
      setTimeout(() => {
        this.$refs.model.submitType = 'edit'
        this.$refs.model.getDetailArr(id)
      }, 0)
    },
    changeModalVisible(e) {
      this.modalVisible = e
    },
    // // 批量更改状态
    // getUpdateStatus(status) {
    //   const _selectedRowsId = this.$refs.table.selectedRows
    //   _selectedRowsId.forEach((item) => {
    //     this.selectedRowsId.push(item.id)
    //   })
    //   // const ids = this.selectedRowsId
    //   status === '0' ? (status = '0') : (status = '1')
    //   // updateStatus({ ids: ids.join(','), status }).then((res) => {
    //   //   if (res.code === 200) {
    //   //     this.getListArr()
    //   //     if (ids.length === 1) {
    //   //       this.selectedStateWork = !this.selectedStateWork
    //   //       this.selectedStateStop = !this.selectedStateStop
    //   //     }
    //   //   }
    //   // })
    // },

    /* 启动 */
    startTask(index) {
      var that = this
      this.$refs.table.selectedRows.forEach((item) => {
        const idc = item.id
        startTask(idc)
          .then(() => {
            that.getTableList('')
            that.$message.success(
              '启动成功',
              3
            )
          }).catch(function() {
          that.$message.error(
            '发生异常',
            3
          )
        })
      })
    },

    /* 暂停 */
    pauseTask(index) {
      var that = this
      this.$refs.table.selectedRows.forEach((item) => {
        const idc = item.id
        pauseTask(idc)
          .then(() => {
            that.getTableList('')
            that.$message.success(
              '暂停成功',
              3
            )
          }).catch(function() {
          that.$message.error(
            '发生异常',
            3
          )
        })
      })
    },

    // 删除
    getDelete() {
      this.visible = true
    },

    // 确认删除所选中数据
    handleCancel(i) {
      if (i === 0) {
        this.treeDelVisible = false
      } else if (i === 1) {
        this.visible = false
      }
    },
    delItem() {
      var that = this
      this.$refs.table.selectedRows.forEach((item) => {
        const idc = item.id

        getRemove({ id: idc }).then((res) => {
          that.clearSelectedRows()
          that.getTableList('')
          that.$message.success('删除成功', 3)
          that.visible = false
        })
      })
    },

    clearSelectedRows() {
      this.$refs.table.selectedRows = []
      this.$refs.table.selectedRowKeys = []
      // console.log('清空啦！！！！！')
    },

    changeParams(key, value) {
      this.$set(this.params, key, value)
    },
    // 执行一次
    // executeOnce(index) {
    //   // this.modalVisible = true
    //   // this.sendParams = index.sendParams
    //   // this.status = '执行一次'
    //   this.$message.info('执行一次')
    //   console.log('zhingxinyici ', index)
    // },

    /* 立即执行一次 */
    executeOnce(index) {
      var that = this
      runTask(index.id)
        .then(() => {
          that.getTableList('')
          that.$message.success(
            '执行成功',
            3
          )
        }).catch(function() {
        that.$message.error(
          '发生异常',
          3
        )
      })
    },

    handleOk() {
      this.getTableList('')
      this.modalVisible = false
    },

    // 树节点新增
    getTreeAdd() {
      this.treeModalVisible = true
      setTimeout(() => {
        this.$refs.treeModel.submitType = 'add'
      }, 0)
    },
    treeHandleOk() {
      this.treeModalVisible = false
      this.getClassTree('')
    },
    // 树节点编辑
    treeEdit() {
      this.treeModalVisible = true
      const id = this.checkedKeys[0]
      setTimeout(() => {
        this.$refs.treeModel.submitType = 'edit'
        this.$refs.treeModel.getTreeDetail(id)
      }, 0)
    },
    // 树节点删除
    treeRemove() {
      this.treeDelVisible = true
    },
    getTreeRemove() {
      var that = this
      this.checkedKeys.forEach((item) => {
        getTreeRemove({ id: item }).then((res) => {
          if (res.code === 200) {
            this.getClassTree('')
            this.treeDelVisible = false
            that.$message.success('删除成功', 3)
          }
        })
      })
    }
  },
  computed: {
    isShowStart() {
      if (this.initState) {
        return false
      } else {
        return this.$refs.table.selectedRows.length === 1 && this.$refs.table.selectedRows[0].taskState !== 1
      }
    },
    isShowStop() {
      if (this.initState) {
        return false
      } else {
        return this.$refs.table.selectedRows.length === 1 && this.$refs.table.selectedRows[0].taskState !== 0
      }
    }
  },
  watch: {
    params: {
      deep: true,
      immediate: true,
      handler(val) {
        this.getTableList('')
      }
    }
  }
}
</script>

<style lang='less' scoped>
#tasks-wrap {
  padding: 0 40px;
  padding: 20px;
  display: grid;
  grid-template-columns: 1fr 3fr;
  grid-gap: 0 20px;

  .left-tree {
    background: #fff;
    padding: 20px;
    border-radius: 12px;
    box-sizing: border-box;
    min-height: calc(100vh - 210px);
    box-shadow: 0 0 10px 0 rgba(17, 32, 65, 0.08);
    .title {
      position: relative;
      color: #000;
      font-weight: 700;
      font-size: 20px;
      margin-bottom: 20px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      h2 {
        color: #000;
        font-weight: 700;
        font-size: 20px;
        height: 100%;
        margin: 0;
      }
      button {
        background: none;
        padding: 0;
        width: auto;
        min-width: 0;
        height: auto;
        margin: 0 5px;
        border: none;
        color: #333;
        &:hover {
          color: #3b75f5;
          cursor: pointer;
        }
      }
      .ant-btn-disabled, .ant-btn.disabled, .ant-btn[disabled], .ant-btn-disabled:hover, .ant-btn.disabled:hover, .ant-btn[disabled]:hover, .ant-btn-disabled:focus, .ant-btn.disabled:focus, .ant-btn[disabled]:focus, .ant-btn-disabled:active, .ant-btn.disabled:active, .ant-btn[disabled]:active, .ant-btn-disabled.active, .ant-btn.disabled.active, .ant-btn[disabled].active {
        color: rgba(0, 0, 0, 0.25);
      }
      &::before {
        content: '';
        width: 4px;
        height: 26px;
        background-color: #3b75f5;
        position: absolute;
        left: -18px;
        top: 50%;
        transform: translateY(-50%);
      }
    }
    .titleBar {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .action {
      display: flex;
      justify-content: space-around;
      > div {
        margin-left: 20px;
        cursor: pointer;

        &:hover {
          color: rgb(0, 101, 189);
        }
      }
    }
  }

  .right-main {
    background: #ffffff;
    border-radius: 12px;
    box-sizing: border-box;
    padding: 25px;
    box-shadow: 0 0 10px 0 rgba(17, 32, 65, 0.08);
    .button-wrap {
      margin: 20px 0 15px;
    }
    .table-content {
      button {
        background: none;
        border: none;
        display: inline-block;
        margin: 0 5px;
        padding: 0;
        -webkit-box-shadow: none;
        box-shadow: none;
        color: #2f54eb;
      }
    }
  }
}
</style>
