<template>
  <div class="right-detail-toolbar right-list-panel-card">
    <!-- 工具栏 -->
    <el-toolbar v-if="this.ID && String(this.ID) !== '0'">
      <el-button @click="save">
        <i class="fa fa-save"></i>保存</el-button>
      <el-button @click="execute">
        <i class="fa fa-check"></i>执行任务</el-button>
    </el-toolbar>
    <div>
    <el-form :model.sync="tmpTaskData" label-width="170px" ref="DBTaskForm" :rules="DBTaskRules">
      <div class="panel-card">
        <h4 class="panel-legend">基本信息</h4>
        <el-form-item label="任务名称：" prop="name">
          <el-input v-model="tmpTaskData.name" class="form-item"></el-input>
        </el-form-item>
        <el-form-item label="任务状态：" prop="status">
          <el-switch v-model="tmpTaskData.status" active-value="Y" inactive-value="N"></el-switch>
        </el-form-item>
        <el-form-item label="外部数据库连接：" prop="databaseName">
          <el-input v-model="tmpTaskData.databaseName" class="form-item" :disabled="true"></el-input>
          <el-button @click="selectDatabaseClick">选择</el-button>
        </el-form-item>
        <el-form-item label="选择数据表：" prop="tableName">
          <el-select v-model="tmpTaskData.tableName" filterable class="form-item">
            <el-option v-for="item in tableOptions" :key="item.key" :label="item.value" :value="item.key">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="采集内容类型：">
            <el-select clearable v-model="contentType" placeholder="请选择" style="width: 240px;">
              <el-option v-for="item in contentTypes" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
        </el-form-item> -->
        <el-form-item label="采集到此栏目：" prop="catalogID">
          <tree-select :value.sync="tmpTaskData.catalogID" :dim-info="{'enable':true}" @click-change="catalogClickChange"
            width="300"></tree-select>
        </el-form-item>
        <el-form-item label="采集后内容类型状态：" prop="articleStatus">
          <el-select v-model="tmpTaskData.articleStatus" class="form-item">
            <el-option v-for="item in contentStatusOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </div>
      <!-- 判断栏目内容类型 -->
      <div v-if="contentType.indexOf('Article')>-1">
        <div class="panel-card">
          <h4 class="panel-legend">文件路径替换规则</h4>
          <el-form-item label="将：" prop="pathReplacePartOld">
            <el-input v-model="tmpTaskData.pathReplacePartOld" class="form-item"></el-input>
          </el-form-item>
          <el-form-item label="替换为：" prop="pathReplacePartNew">
            <el-input v-model="tmpTaskData.pathReplacePartNew" class="form-item"></el-input>
            <br/> 如果采集过来文章内容含有图片、附件，则需要使用操作系统或其他软件的文件同步功能，将远程服务器上的文件采集到指定目录下，然后将文章内容中的图片路径替换成同步后存放的路径。
          </el-form-item>
        </div>
      </div>
      <div class="panel-card">
        <h4 class="panel-legend">采集条件</h4>
        <el-form-item label="SQL条件：" prop="SQLCondition">
          <el-input v-model="tmpTaskData.SQLCondition" class="form-item"></el-input>&nbsp;即SQL中where关键字之后的查询条件
        </el-form-item>
      </div>
      <div class="panel-card">
        <h4 class="panel-legend">记录查新规则</h4>
        <el-form-item label="规则表达式：" prop="newRecordRule">
          <el-input v-model="tmpTaskData.newRecordRule" class="form-item"></el-input>
          <br/>记录查新规则是为了达到每次采集只采集变动过的数据而设置的查询条件。ID>$ {Max(ID)}表示只采集远程数据为ID字段值大于已经采集过的数据中ID字段最大值的记录。条件之间可以用Or和 And 相连，例如AddTime>$
          {Max(AddTime)} or ModifyTime>$ {Max(ModifyTime)}
          <br/>默认:ID>$ {Max(ID)}
        </el-form-item>
      </div>
    </el-form>
    </div>

    <databaseList-dialog :show.sync="databaseListModal" @callback="databaseListCallback"></databaseList-dialog>

  </div>
</template>

<script>
import util from '@src/common/util.js'
import treeSelect from '@src/components/TreeSelect.vue'
import databaseListDialog from './databaseListDialog.vue'

export default {
  components: {
    'tree-select': treeSelect,
    'databaseList-dialog': databaseListDialog
  },
  props: {
    ID: [String, Number],
    copyID: [String, Number]
  },
  data() {
    var checkCatalog = (rule, value, callback) => {
      if (value === 0) {
        return callback(new Error('不能选择站点目录！'))
      } else if (!value || value < 0) {
        return callback(new Error('请选择栏目！'))
      } else {
        callback()
      }
    }
    return {
      databaseListModal: false,
      contentStatusOptions: [],
      tableOptions: [],
      contentType: 'Article',
      tmpTaskData: {
        name: null
      },
      contentTypes: [{value: 'Article', label: '文章'}, {value: 'Image', label: '图片'}],
      DBTaskRules: {
        name: [
          {
            required: true,
            message: '不能为空',
            trigger: 'blur'
          }
        ],
        databaseName: [
          {
            required: true,
            message: '不能为空',
            trigger: 'blur'
          }
        ],
        tableName: [
          {
            required: true,
            message: '不能为空',
            trigger: 'blur'
          }
        ],
        catalogID: [
          {
            required: true,
            validator: checkCatalog,
            trigger: 'change'
          }
        ]
      },
      treeData: []
    }
  },
  watch: {
    tmpTaskData: {
      handler: function() {
        this.$emit('callback', this.tmpTaskData)
      },
      deep: true
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    resetFields() {
      this.$refs.DBTaskForm.resetFields()
    },
    validateForm() {
      return util.validateForm(this.$refs['DBTaskForm'])
    },
    databaseListCallback(database) {
      Vue.set(this.tmpTaskData, 'databaseID', database.ID)
      Vue.set(this.tmpTaskData, 'databaseName', database.name)
      this.getTables()
    },
    selectDatabaseClick() {
      this.databaseListModal = true
    },
    catalogClickChange(val) {
      if (val.ID <= 0) {
        return
      }
      if (val.contentType === '') {
        this.contentType = 'Article'
      } else {
        this.contentType = val.contentType
      }
      Vue.set(this.tmpTaskData, 'catalogName', val.name)
    },
    async init() {
      let obj = {
        type: 'Default,Link'
      }
      let bindEditorTree = await axios.get('/ui/catalog/bindeditortree', {
        params: obj
      })
      this.treeData = bindEditorTree.data.data
      let getCodeList = await axios.get('/ui/platform/codes/ContentStatus')
      this.contentStatusOptions = getCodeList.data.data
      let init = await axios.get('/ui/fromdb/init', {
        params: {
          ID: this.ID,
          copyID: this.copyID
        }
      })
      this.tmpTaskData = init.data.data
      Vue.set(
        this.tmpTaskData,
        'articleStatus',
        this.tmpTaskData.articleStatus + ''
      )
      if (this.ID || this.copyID) {
        this.getTables()
      } else {
        this.tableOptions = []
      }
    },
    async getTables() {
      let res = await axios.get('/ui/database/gettables', {
        params: {
          databaseID: this.tmpTaskData.databaseID
        }
      })
      this.tableOptions = []
      if (res.data.status === 1) {
        for (let i = 0; i < res.data.data.length; i++) {
          this.tableOptions.push({
            key: res.data.data[i],
            value: res.data.data[i]
          })
        }
      }
    },
    async save() {
      try {
        await this.validateForm()
      } catch (e) {
        util.showErrorMessageBox(e)
        return
      }
      Vue.set(this.tmpTaskData, 'saveType', 'Info')
      if (this.ID && String(this.ID) !== '0') {
        Vue.set(this.tmpTaskData, 'ID', this.ID)
      }
      let res = await axios.put(
        `/ui/fromdb/${this.tmpTaskData.ID}`,
        this.tmpTaskData
      )
      util.showResponseMessage(res.data)
      if (res.data.status === 1) {
        this.$emit('save-callback', this.ID)
      }
    },
    async execute(restartFlag) {
      try {
        await this.$confirm('确定要执行该任务吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        let obj = {
          ID: this.ID,
          restartFlag: restartFlag ? 'Y' : 'N'
        }
        let res = await axios.post('/ui/fromdb/execute', obj)
        util.showResponseMessage(res.data)
        if (res.data.status === 1) {
          await util.showProgress(res.data.taskID, '正在删除. . .')
        }
      } catch (e) {

      }
    }
  }
}
</script>

<style scoped>
.content-title {
  font-size: 16px;
  font-weight: bold;
  margin: 10px 0 0 40px;
}

.form-item{
  max-width:300px;
  width:80%;
}
</style>
