<template>
  <div class="layout-no-cols right-list-toolbar right-list-panel-card">
    <div v-show="showDataList">
      <el-toolbar>
        <el-button @click="addClick" priv="Admin.Workflow.Add">
          <i class="fa fa-plus"></i>新建
        </el-button>
        <el-button @click="importClick" priv="Admin.Workflow.Import">
          <i class="fa fa-arrow-up"></i>导入
        </el-button>
      </el-toolbar>

        <el-list-view ref="workflowList" data-read-url="/ui/workflows" :pageSize="10" @selection-change="onSelectionChange" :selectable="true" :multiOperates="multiOperates">
          <template slot-scope="row">
            <div class="panel-card">
              <el-row> <a class="list-card-title" href="javascript:void(0)" @click.stop="editClick(row)">{{row.name}}</a> <span class="gray">ID：{{row.ID}}</span> </el-row>
              <el-row>
                <el-col :span="8"><span>类型：</span> <em>{{row.typeName || '无'}}</em> </el-col>
                <el-col :span="8"><span>添加时间：</span> <em>{{row.addTime | fixDateTime}}</em> </el-col>
                <el-col :span="8"><span>最后修改时间：</span> <em>{{row.modifyTime | fixDateTime }}</em> </el-col>
              </el-row>
              <el-col :span="24"><span>备注：</span> <em>{{row.memo || '无'}}</em> </el-col>
              <el-row>
                <el-col :span="24" class="tar" >
                  <el-button @click.stop="exportClick([row])" priv="Admin.Workflow.Export" type="text" title="导出">
                    <i class="fa fa-arrow-down"></i>导出
                  </el-button>
                  <el-button @click.stop="similarAddClick(row)" priv="Admin.Workflow.Add" type="text" title="类似创建">
                    <i class="fa fa-copy"></i>类似创建
                  </el-button>
                  <el-button @click.stop="editClick(row)" priv="Admin.Workflow.Edit" type="text" title="编辑">
                    <i class="fa fa-edit"></i>编辑
                  </el-button>
                  <el-button @click.stop="deleteClick([row])" priv="Admin.Workflow.Delete" type="text" title="删除">
                    <i class="fa fa-times"></i>删除
                  </el-button>
                </el-col>
              </el-row>
            </div>
          </template>
        </el-list-view>
    </div>

    <div v-show="showAddForm">
      <el-toolbar>
        <el-button @click="$router.back()" type="primary" size="medium" round class="shadow-primary">
          <i class="fa fa-chevron-left"></i> 返回上页
        </el-button>
        <span class="button-separator"></span>
        <el-button @click="addClickHandler">
          <i class="fa fa-save"></i>保 存
        </el-button>
      </el-toolbar>
      <div>
        <div class="detail-panel form-panel">
          <el-form :model="tmpAddWorkflow" ref="addWorkflowForm" label-width="100px">
            <el-form-item label="工作流名称" prop="name" :verify="['NotNull','Length<30']">
              <el-input v-model="tmpAddWorkflow.name"></el-input>
            </el-form-item>
            <el-form-item label="工作流类型" prop="type" :verify="['NotNull']">
              <el-select v-model="tmpAddWorkflow.type" placeholder="请选择" style="width:100%">
                <el-option v-for="item in workflowTypes" :key="item.ID" :label="item.name" :value="item.ID">
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>

    <div v-show="showImportForm">
      <el-toolbar>
        <el-button @click="$router.back()" type="primary" size="medium" round class="shadow-primary">
          <i class="fa fa-chevron-left"></i> 返回上页
        </el-button>
        <span class="button-separator"></span>
        <el-button @click="importClickHandler">
          <i class="fa fa-save"></i>确 定
        </el-button>
      </el-toolbar>
      <div>
        <div class="detail-panel form-panel">
          <el-form :model="tmpImportWorkflow" ref="importWorkflowForm" label-width="100px">
            <el-form-item label="工作流名称" prop="name" :verify="['NotNull','Length<30']">
              <el-input v-model="tmpImportWorkflow.name"></el-input>
            </el-form-item>
            <el-form-item label="工作流类型" prop="type" :verify="['NotNull']">
              <el-select v-model="tmpImportWorkflow.type" placeholder="请选择" style="width:100%">
                <el-option v-for="item in workflowTypes" :key="item.ID" :label="item.name" :value="item.ID">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="选择文件">
              <el-upload class="upload-demo" ref="upload" :limit="1" :on-exceed="filesExceed" action="" :auto-upload="false" :multiple="false"
                :on-change="selectFileChangeHandler" :http-request="requestHandler" :before-upload="beforeFileUpload" :on-remove="handleRemove"
                accept=".txt">
                <el-button type="primary">浏览</el-button>
                <div slot="tip" class="el-upload__tip">只能上传 .txt文件</div>
              </el-upload>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>

  </div>
</template>

<script>
import util from '@src/common/util.js'
import _ from 'lodash'
export default {
  props: {
    ID: {
      type: [String, Number],
      default: 0
    }
  },
  filters: {
    fixDateTime: function(val) {
      if (!val) {
        return ''
      }
      return util.formatDate(val, 'yyyy-MM-dd HH:mm')
    }
  },
  data() {
    let self = this
    return {
      showDataList: true,
      showAddForm: false,
      showImportForm: false,
      workflows: [],
      total: 0,
      selectedRows: [],
      workflowTypes: [],
      tmpWorkflow: {},
      exportWorkflow: {
        isShowModal: false,
        percentage: 0,
        text: '准备中...'
      },
      tmpImportWorkflow: {
        name: '',
        type: ''
      },
      fileList: [],
      importWorkflowDialog: false,
      addWorkflowDialog: false,
      tmpAddWorkflow: {
        name: '',
        type: ''
      },
      intervalid: '',
      multiOperates: [{
        label: '删除',
        value: 'delete',
        fn: function(value) {
          let namesStr = _.map(value, 'name').join(',')
          self.$confirm("确认删除选择的工作流：<span class='icon-danger'>" + namesStr + '</span>？', {
            title: '提示',
            dangerouslyUseHTMLString: true,
            type: 'warning'
          }).then((res) => {
            // 执行删除操作
            // let IDStrs = _.map(value, 'ID').join(',')
            // TODO: 完善批量方法
            //  console.log('待删除的ID值:' IDStrs)
          }).catch((err) => {
            console.error(err)
          })
        }
      }, {
        label: '导出',
        value: 'export',
        fn: function(value) {
          // TODO 完善批量导出方法
          console.log('export', value)
        }
      }]
    }
  },
  beforeRouteUpdate(to, from, next) {
    if (!to.params.ID) {
      this.showAddForm = false
      this.showDataList = true
      this.showImportForm = false
    } else if (to.params.ID === 'new') {
      this.showAddForm = true
      this.showDataList = false
      this.showImportForm = false
    } else if (to.params.ID === 'import') {
      this.showAddForm = false
      this.showDataList = false
      this.showImportForm = true
    }
    next()
  },
  methods: {
    handleCommand(method) {
      if (method && typeof this[method] === 'function') {
        this[method]()
      } else {
        console.warn(`未找到改菜单对应的方法:${method}`)
      }
    },
    beforeImportDialogClose() {
      this.fileList = []
      this.$refs['upload'].clearFiles()
    },
    onSelectionChange(selection) {
      this.selectedRows = selection
    },
    addClick() {
      this.tmpAddWorkflow = {
        name: '',
        type: ''
      }
      this.editWorkflowMode = 1
      this.addWorkflowDialog = true

      this.$router.push({params: {ID: 'new'}})
    },
    async addClickHandler() {
      try {
        await util.validateForm(this.$refs['addWorkflowForm'])
      } catch (e) {
        util.showErrorMessageBox(e)
        return
      }
      let formData = new FormData()
      formData.append('name', this.tmpAddWorkflow.name)
      formData.append('type', this.tmpAddWorkflow.type)
      let resp = await axios.post('/ui/workflows', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      if (resp.data.status === 1) {
        let ID = resp.data.ID
        let copyAdd = 'N'
        this.addWorkflowDialog = false
        this.$router.back()
        window.open(`./workflowEditor.html?ID=${ID}&copyAdd=${copyAdd}`)
      } else {
        util.showResponseMessage(resp.data)
      }
      this.loadWorkflows()
    },
    similarAddClick(selectedRow) {
      this.editWorkflowMode = 3
      this.tmpWorkflow = Object.assign({}, selectedRow)
      let ID = this.tmpWorkflow.ID
      let copyAdd = 'Y'
      window.open(`./workflowEditor.html?ID=${ID}&copyAdd=${copyAdd}`)
    },
    editClick(selectedRow) {
      this.editWorkflowMode = 2
      this.tmpWorkflow = Object.assign({}, selectedRow)
      let ID = this.tmpWorkflow.ID
      let copyAdd = 'N'
      window.open(`./workflowEditor.html?ID=${ID}&copyAdd=${copyAdd}`)
    },

    importClick() {
      this.fileList = []
      this.tmpImportWorkflow = {
        name: '',
        type: ''
      }
      this.importWorkflowDialog = true

      this.$router.push({ params: { ID: 'import' } })
    },
    async exportClick(selectedRows) {
      let workflowIDs = []
      selectedRows.forEach(function(row) {
        workflowIDs.push(row.ID)
      })
      let ids = workflowIDs.join(',')
      try {
        let resp = await axios.get('/ui/workflows/backups', {
          params: {
            ids
          }
        })
        if (resp.data.status === 1) {
          window.location.href = `ui/workflows/downloads?fileName=${resp.data.data.fileName}`
        } else {
          util.showResponseMessage(resp.data)
        }
      } catch (e) {
        util.showErrorNotification(e)
      }
    },

    beforeFileUpload(file) {
      let isTxt = ''
      if (file.raw) {
        isTxt = file.raw.type === 'text/plain'
      } else {
        isTxt = file.type === 'text/plain'
      }
      if (!isTxt) {
        this.$message.error('只能上传txt文件')
      }
      return isTxt
    },

    selectFileChangeHandler(file, files) {
      if (!this.beforeFileUpload(file)) {
        this.$refs.upload.clearFiles()
        this.fileList = []
        return
      }
      this.fileList = files.slice(-1)
    },
    async requestHandler(event) {
      const { file } = event
      let formData = new FormData()
      formData.append('name', this.tmpImportWorkflow.name)
      formData.append('type', this.tmpImportWorkflow.type)
      formData.append('file', file)
      let res = await axios.post('/ui/workflows/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      util.showResponseMessage(res.data)
      this.$refs.upload.clearFiles()
      this.fileList = []
      if (res.data.status === 1) {
        this.loadWorkflows()
        this.$router.back()
        this.importWorkflowDialog = false
      }
    },
    filesExceed(files, fileList) {
      this.$alert('允许最大上传文件数为1', '提示', {
        type: 'info',
        confirmButtonText: '确定'
      })
    },
    handleRemove(file, files) {
      this.$refs.upload.clearFiles()
      this.fileList = []
    },

    async importClickHandler() {
      try {
        await util.validateForm(this.$refs['importWorkflowForm'])
      } catch (e) {
        util.showErrorMessageBox(e)
        return
      }
      if (this.fileList.length === 0) {
        this.$alert('请选择要上传的文件', '提示', {
          type: 'info',
          confirmButtonText: '确定'
        })
        return
      }
      this.$refs.upload.submit()
    },
    async confirmClickHandler() {
      try {
        await util.validateForm(this.$refs['workflowForm'])
      } catch (e) {
        util.showErrorMessageBox(e)
        return
      }

      let addForm = () => {
        return axios.post('/ui/workflows', this.tmpWorkflow)
      }

      let similaraddForm = () => {
        return axios.post('/ui/workflows', this.tmpWorkflow)
      }

      let editForm = () => {
        return axios.put(`/ui/workflows/${this.tmpWorkflow.ID}`, this.tmpWorkflow)
      }
      let res
      if (this.editWorkflowMode === 1) {
        res = await addForm()
      }

      if (this.editWorkflowMode === 2) {
        res = await editForm()
      }

      if (this.editWorkflowMode === 3) {
        res = await similaraddForm()
      }
      util.showResponseMessage(res.data)
      if (res.data.status === 1) {
        this.loadWorkflows()
        this.editWorkflowDialog = false
      }
    },
    async deleteClick(selectedRows) {
      try {
        await this.$confirm('确定删除吗？删除后无法恢复。是否继续删除？', '删除确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch (e) {
        return
      }
      let workflowIDs = []
      selectedRows.forEach(function(row) {
        workflowIDs.push(row.ID)
      })
      let res = await axios.delete(`/ui/workflows/${workflowIDs.join(',')}`)
      util.showResponseMessage(res.data)
      if (res.data.status === 1) {
        this.loadWorkflows()
      }
    },
    loadWorkflows() {
      this.$refs.workflowList.getData()
    },
    startInterval() {
      this.intervalid = setInterval(() => {
        this.loadWorkflows()
      }, 10000)
    }
  },
  async created() {
    let res = await axios.get('/ui/workflowtypes')
    this.workflowTypes = res.data.data

    if (!this.ID) {
      this.showAddForm = false
      this.showDataList = true
      this.showImportForm = false
    } else if (this.ID === 'new') {
      this.showAddForm = true
      this.showDataList = false
      this.showImportForm = false
    } else if (this.ID === 'import') {
      this.showAddForm = false
      this.showDataList = false
      this.showImportForm = true
    }
  }
}
</script>
<style scoped>
.items-dialog-wrap {
  margin-left: -20px;
  margin-right: -20px;
}

.upload-demo .el-upload__input {
  display: none !important;
  margin-bottom: -20px;
}
</style>
