<template>
  <div class="pane-up-wrap right-list-toolbar" v-loading="dataLoading">
    <el-toolbar v-if="!!id && id!='root' && !createFlag">
      <el-button @click="emitData">
        <i class="fa fa-floppy-o" aria-hidden="true"></i>保存
      </el-button>
      <el-button @click="execute">
        <i class="fa fa-check" aria-hidden="true"></i>执行任务
      </el-button>
      <el-button @click="delResult">
        <i class="fa fa-exclamation-triangle" aria-hidden="true"></i>清空采集数据
      </el-button>
      <el-button @click="dealData">
        <i class="fa fa-key" aria-hidden="true"></i>处理数据
      </el-button>
      <el-button @click="cancel">
        <i class="fa fa-times-circle" aria-hidden="true"></i>终止执行
      </el-button>
      <!-- <el-dropdown @command="handleCommand">
        <el-button>
          <i class="fa fa-ellipsis-h" aria-hidden="true"></i>
        </el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item command="delResult">
            <i class="fa fa-exclamation-triangle" aria-hidden="true"></i>清空采集数据
          </el-dropdown-item>
          <el-dropdown-item command="dealData">
            <i class="fa fa-key" aria-hidden="true"></i>处理数据
          </el-dropdown-item>
          <el-dropdown-item command="cancel">
            <i class="fa fa-times-circle" aria-hidden="true"></i>终止执行
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown> -->
    </el-toolbar>
    <div>
      <el-form class="padding-top-bottom" :model="basicInfo" ref="basicInfo" label-suffix="：" label-width="120px">
        <div class="panel-fieldset">
          <h4 class="panel-legend">基本信息</h4>
          <el-row type="flex" justify="center" :gutter="20">
            <el-col :span="11">
              <el-form-item label="采集类别">
                <el-radio-group @change="typeRadioClick" v-model="basicInfo.type">
                  <el-radio label="D">文章采集</el-radio>
                  <el-radio label="T">自定义采集</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="任务名称" prop="name" :verify="['NotNull']">
                <el-input v-model="basicInfo.name">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex" justify="center" :gutter="20">
            <el-col :span="11">
              <el-form-item label="任务状态">
                <el-switch v-model="basicInfo.status" active-value="Y" inactive-value="N"></el-switch>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="发布日期格式">
                <el-input  v-model="basicInfo.publishDateFormat">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex" justify="center" :gutter="20">
            <el-col :span="11">
              <el-form-item label="采集到此栏目" v-if="basicInfo.type=='D'" prop="catalogID" :verify="['NotNull']">
                <catalogTree-selector v-model="catalog" :level="100" contentType="Article" type="Default,Link">
                </catalogTree-selector>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="默认字符集">
                <el-input  v-model="basicInfo.defaultCharset">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex" justify="center" :gutter="20">
            <el-col :span="22">
              <el-form-item label="采集选项" v-if="basicInfo.type=='D'">
                <el-checkbox v-model="basicInfo.copyImage">下载远程图片和文件</el-checkbox>
                <el-checkbox v-show="basicInfo.copyImage" v-model="basicInfo.withoutImageExt">允许下载自定义后缀图片</el-checkbox>
                <el-checkbox v-model="basicInfo.cleanLink">去掉除内容中的超链接</el-checkbox>
                <el-checkbox v-model="basicInfo.dealAfterGather">采集完后手动处理</el-checkbox>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex" justify="center" :gutter="20">
            <el-col :span="22">
              <el-form-item label="任务描述">
                <el-input  v-model="basicInfo.intro">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <div class="panel-fieldset">
          <h4 class="panel-legend">URL层级</h4>
          <el-row type="flex" justify="center" :gutter="20">
            <el-col :span="22">
              <el-button class="dashed" @click="addURL">
                <i class="fa fa-plus" aria-hidden="true"></i>增加URL层级
              </el-button>
              <el-button class="dashed" @click="removeURL" :disabled="this.urlList.length<=1 || (!id || id=='root') && !createFlag">
                <i class="fa fa-minus" aria-hidden="true"></i>减少URL层级
              </el-button>
            </el-col>
          </el-row>
          <div style="padding:5px"></div>
          <el-row type="flex" justify="center" :gutter="20">
            <el-col :span="22">
              <el-form ref="basicInfoURLForm"  class="demo-dynamic" v-if="this.urlList.length>0">
                <template v-for="u in urlList">
                  <el-form-item label="" :key="u.name" style="margin-bottom:5px;" :verify="['NotNull']">
                    <el-input type="textarea" :placeholder="u.name" v-model="u.url" :rows="3"></el-input>
                  </el-form-item>
                </template>
              </el-form>
            </el-col>
          </el-row>
        </div>

        <div class="panel-fieldset">
          <h4 class="panel-legend">高级选项</h4>
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-form-item label="列表页最大采集数" prop="maxListCount" label-width="180px">
                <el-input-number v-model="basicInfo.maxListCount"  :min="-1"></el-input-number>
                <span>(-1表示不限制)</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="采集线程数" prop="threadCount" label-width="180px">
                <el-input-number v-model="basicInfo.threadCount"  :min="1" :max="100"></el-input-number>
                <span> (1-100)</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-form-item label="超时等待时间" prop="timeOut" label-width="180px">
                <el-input-number v-model="basicInfo.timeOut"  :min="1" :max="600"></el-input-number>
                <span>秒 (1-600)</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="发生错误时重试次数" prop="retryTimes" label-width="180px">
                <el-input-number v-model="basicInfo.retryTimes"  :min="1" :max="10"></el-input-number>
                <span>(1-10)</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex" justify="center" :gutter="20">
            <el-col :span="22">
              <el-form-item label="采集关键词">
                <el-input placeholder="关键词之间用空格隔开" v-model="basicInfo.keyWords">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <div class="panel-fieldset">
          <h4 class="panel-legend">
            <el-checkbox v-model="basicInfo.proxyFlag">使用代理服务器</el-checkbox>
          </h4>
          <el-row type="flex" justify="center" :gutter="20">
            <el-col :span="11">
              <el-form-item label="服务器地址">
                <el-input v-model="basicInfo.proxyHost" :disabled="!basicInfo.proxyFlag || (!id || id=='root') && !createFlag">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="端口">
                <el-input v-model="basicInfo.proxyPort" :disabled="!basicInfo.proxyFlag || (!id || id=='root') && !createFlag">
                </el-input>
                <!-- <el-input-number v-model="basicInfo.proxyPort"  :min="1" :max="65534" :disabled="!basicInfo.proxyFlag || (!id || id=='root') && !createFlag"></el-input-number> -->
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex" justify="center" :gutter="20">
            <el-col :span="11">
              <el-form-item label="用户名">
                <el-input v-model="basicInfo.proxyUserName" :disabled="!basicInfo.proxyFlag || (!id || id=='root') && !createFlag">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="密码">
                <el-input  v-model="basicInfo.proxyPassword" :disabled="!basicInfo.proxyFlag || (!id || id=='root') && !createFlag">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <div class="panel-fieldset">
          <h4 class="panel-legend">
            <el-checkbox v-model="basicInfo.filterFlag">URL过滤</el-checkbox>
          </h4>
          <el-row type="flex" justify="center" :gutter="20">
            <el-col :span="22">
              <el-form-item label="过滤表达式">
                <el-input type="textarea" placeholder="" v-model="basicInfo.filterExpr" :rows="3"
                  :disabled="!basicInfo.filterFlag || (!id || id=='root') && !createFlag"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
    </div>

    <!-- 选择文章dialog组件 -->
    <fromweb-article-dialog :id="id" ref="fromwebarticledialog" @ok="doDealData"></fromweb-article-dialog>

  </div>
</template>

<script>
import util from '@src/common/util.js'
import CatalogTreeSelector from '../../search/components/ArticleCatalogTreeSelector.vue'
import FromWebArticleDialog from './FromWebArticleDialog.vue'

export default {
  data() {
    return {
      id: 0, // 采集任务id
      interval: null,
      page: {
        dealDataTablePageIndex: 0,
        dealDataTablePageSize: 10
      },
      pageIndex: 0,
      pageSize: 10,
      tableDataTotal: 0,
      selectedRows: [],
      formData: {},
      dataLoading: false, // 数据加载状态
      catalogTree: [], // 栏目树数据
      catalog: {},
      urlList: [{ name: '起始URL', rowNo: 1, url: '' }], // url层级
      basicInfo: {
        ID: null,
        siteID: '',
        name: '', // 任务名称
        type: 'D', // 采集类别
        status: 'Y', // 任务状态
        publishDateFormat: 'yyyy-MM-dd', // 发布日期格式
        defaultCharset: '', // 默认字符集
        copyImage: true, // 下载远程图片和文件
        withoutImageExt: false, // 下载自定义图片后缀文件
        cleanLink: true, // 去除内容中的超链接
        dealAfterGather: false, // 采集完后手动处理
        catalogName: '', // 栏目名称
        catalogID: null, // 栏目ID
        intro: '', // 任务描述

        maxListCount: -1, // 列表页最大采集数
        threadCount: 1, // 采集线程数
        timeOut: 30, // 超时等待时间
        retryTimes: 2, // 发生错误重试次数
        keyWords: '', // 采集关键字

        proxyFlag: false, // 使用代理服务器？
        proxyHost: '', // 服务器地址
        proxyPort: '', // 端口
        proxyUserName: '', // 用户名
        proxyPassword: '', // 密码

        filterFlag: false, // URL过滤？
        filterExpr: '', // 过滤表达式

        addUser: '',
        addTime: ''
      }, // 基本信息tabs数据
      emitBasicInfo: {},
      resultDetail: {}, // 处理结果详情
      gatherResultArticleTableLoading: false,
      gatherResultDialogVisible: false, // 采集结果Dialog状态
      gatherResultDialogDataLoading: false, // 采集结果Dialog数据加载状态
      gatherResultArticle: [], // 采集结果_文章
      formValidate: {
        name: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
        catalogID: [{ required: true, message: '请选择采集栏目', trigger: 'blur' }],
        url1: [{ required: true, message: '请填写URL层级', trigger: 'blur' }],
        maxListCount: [{ type: 'number', required: true, message: '请填写列表页最大采集数', trigger: 'blur' }],
        threadCount: [{ type: 'number', required: true, message: '请填写采集线程数', trigger: 'blur' }],
        timeOut: [{ type: 'number', required: true, message: '请填写超时等待时间', trigger: 'blur' }],
        retryTimes: [{ type: 'number', required: true, message: '请填写发生错误时重试次数', trigger: 'blur' }]
      }
    }
  },
  methods: {
    handleCommand(method) {
      if (method && typeof this[method] === 'function') {
        this[method]()
      } else {
        console.warn(`未找到改菜单对应的方法:${method}`)
      }
    },
    async init(id) {
      this.basicInfo.ID = this.id = id
      this.dataLoading = true
      let param = { ID: this.id }
      let res = await axios.get(`/ui/fromweb/init`, { params: param })
      this.dataLoading = false
      this.basicInfo = res.data.status === 1 ? Object.assign({}, res.data.data) : this.basicInfo
      this.basicInfo.copyImage = this.basicInfo.copyImage === '1' || this.basicInfo.copyImage === 1
      this.basicInfo.withoutImageExt = this.basicInfo.withoutImageExt === '1' || this.basicInfo.withoutImageExt === 1
      this.basicInfo.cleanLink = this.basicInfo.cleanLink === '1' || this.basicInfo.cleanLink === 1
      this.basicInfo.dealAfterGather = this.basicInfo.dealAfterGather === '1' || this.basicInfo.dealAfterGather === 1
      this.basicInfo.proxyFlag = this.basicInfo.proxyFlag === '1' || this.basicInfo.proxyFlag === 1
      this.basicInfo.filterFlag = this.basicInfo.filterFlag === '1' || this.basicInfo.filterFlag === 1
      this.catalog = {
        ID: this.basicInfo.catalogID,
        name: this.basicInfo.catalogName
      }
      this.$emit('onTypeChange', this.basicInfo.type)
      this.loadURLList(this.id)
    },

    async emitData() {
      try {
        await util.validateForm(this.$refs.basicInfo)
      } catch (e) {
        util.showErrorMessageBox(e)
        return
      }
      let flag = await this.validateForm(this.basicInfo)
      if (flag) {
        this.basicInfo['catalogID'] = this.catalog.ID
        this.basicInfo['catalogName'] = this.catalog.name
        let prop = Object.getOwnPropertyNames(this.emitBasicInfo)
        for (let i = 1; i < prop.length; i++) {
          if (
            prop[i] === 'copyImage' ||
            prop[i] === 'withoutImageExt' ||
            prop[i] === 'cleanLink' ||
            prop[i] === 'dealAfterGather' ||
            prop[i] === 'proxyFlag' ||
            prop[i] === 'filterFlag'
          ) {
            this.emitBasicInfo[prop[i]] = this.basicInfo[prop[i]] === true ? 1 : 0
          } else {
            this.emitBasicInfo[prop[i]] = this.basicInfo[prop[i]]
          }
        }
        for (let i = 0; i < this.urlList.length; i++) {
          this.basicInfo['url' + this.urlList[i].rowNo] = this.urlList[i].url
          this.emitBasicInfo['url' + this.urlList[i].rowNo] = this.urlList[i].url
        }
        this.emitBasicInfo['ID'] = this.id
        let data = {
          type: 'Info',
          data: this.emitBasicInfo,
          flag: flag
        }
        this.$emit('getData', data)
      }
    },

    // 采集类别radio改变事件
    typeRadioClick(label) {
      this.basicInfo.type = label
      this.$emit('onTypeChange', label)
    },

    // 增加URL层级
    addURL(type) {
      if (type && type === 'add') {
        this.createWebGatherFormData.URL.push({
          name: 'URL层级' + (this.createWebGatherFormData.URL.length + 1),
          rowNo: this.createWebGatherFormData.URL.length + 1,
          url: ''
        })
      } else {
        this.urlList.push({ name: 'URL层级' + (this.urlList.length + 1), rowNo: this.urlList.length + 1, url: '' })
      }
    },
    // 减少URL层级
    removeURL(type) {
      if (type && type === 'add') {
        this.createWebGatherFormData.URL.splice(this.createWebGatherFormData.URL.length - 1, 1)
      } else {
        this.urlList.splice(this.urlList.length - 1, 1)
      }
    },
    // 加载URL层级数据
    async loadURLList(id) {
      id = id || this.id
      let res = await axios.get(`/ui/fromweb/urllist`, {params: {ID: id}})
      this.urlList = res.data.status === 1 ? res.data.data : this.urlList
      this.urlList = !this.urlList || this.urlList.length === 0 ? [{ name: '起始URL', rowNo: 1, url: '' }] : this.urlList
    },

    // 表单验证处理
    validateForm(form) {
      if (!form) {
        return false
      }
      if (!form.name || form.name.trim() === '') {
        this.$alert('任务名称不能为空', '系统提示', {type: 'error'})
        return false
      }
      if (form.type === 'D') {
        if (!this.catalog.ID) {
          this.$alert('采集到此栏目不能为空 ！', '系统提示', {type: 'error'})
          return false
        }
      }
      if (!this.urlList || this.urlList.length < 1 || !this.urlList[0].url) {
        this.$alert('起始URL不能为空 ！', '系统提示', {type: 'error'})
        return false
      }
      if (form.proxyFlag) {
        if (!form.proxyHost) {
          this.$alert('服务器地址不能为空 ！', '系统提示', {type: 'error'})
          return false
        }
        if (!form.proxyPort) {
          this.$alert('端口不能为空 ！', '系统提示', {type: 'error'})
          return false
        }
        if (!form.proxyUserName) {
          this.$alert('用户名不能为空 ！', '系统提示', {type: 'error'})
          return false
        }
        if (!form.proxyPassword) {
          this.$alert('密码不能为空 ！', '系统提示', {type: 'error'})
          return false
        }
      }
      if (form.filterflag && !form.filterexpr) {
        this.$alert('过滤表达式不能为空 ！', {type: 'error'})
        return false
      }
      return true
    },

    // 清空采集数据
    async delResult() {
      if (!this.id) {
        this.$alert('请选择一个采集任务 ！', {type: 'info'})
        return
      }
      try {
        // const h = this.$createElement
        await this.$confirm('', '系统提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          dangerouslyUseHTMLString: true,
          message:
            '采集数据是指从指定URL下载的文本文件和图片文件<font color="red">不包括已经传入栏目的文章。</font><br><br>确认要清空该任务的采集数据吗 ？',
          type: 'warning'
        })
        let res = await axios.delete(`/ui/fromweb/result/${this.id}`)
        util.showMessage(res)
      } catch (e) {

      }
    },

    // 处理数据选择文章表格数据选中事件
    dealDataTableSelectionChange(selection) {
      this.selectedRows = selection
    },

    // 处理数据
    dealData() {
      if (!this.id) {
        this.$alert('请选择一个采集任务 ！')
        return
      }
      if (this.basicInfo.dealAfterGather) {
        this.$refs.fromwebarticledialog.initDialog(this.id)
      } else {
        this.doDealData()
      }
    },
    // 处理数据
    async doDealData(rows) {
      if (!!rows && !!rows.length) {
        this.selectedRows = rows
      }
      let urlsArr = []
      for (var item of this.selectedRows) {
        urlsArr.push(item.URL)
      }
      let param = {
        ID: this.id,
        urls: urlsArr.join()
      }
      let res = await axios.put(`/ui/fromweb/${param.ID}/result`, param)
      if (res.data.status === 1) {
        this.selectedRows = []
        await util.showProgress(res.data.data.taskID, '执行中...')
      } else {
        util.showMessage(res)
      }
    },

    // 执行任务
    async execute() {
      if (!this.id) {
        this.$alert('请选择一个采集任务 ！')
        return
      }
      try {
        await this.$confirm('确认要执行该任务吗 ？', '系统提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        let res = await axios.put(`/ui/fromweb/${this.id}/execute`)
        if (res.data.status === 1) {
          await util.showProgress(res.data.data.taskID, '在抓取web文件...')
        } else {
          util.showMessage(res)
        }
      } catch (e) {

      }
    },
    // 终止执行
    async cancel() {
      if (!this.id) {
        this.$alert('请选择一个采集任务 ！')
        return
      }
      try {
        await this.$confirm('确认要终止执行该任务吗 ？', '系统提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        let res = await axios.put(`/ui/fromweb/${this.id}/executes`)
        util.showMessage(res)
      } catch (e) {

      }
    }
  },

  created() {
    this.basicInfo.ID = this.id = this.taskID
    this.emitBasicInfo = Object.assign({}, this.basicInfo)
    if (this.createFlag && this.createFlag === 'screate') {
      this.init(this.basicInfo.ID)
    }
  },
  components: {
    'catalogTree-selector': CatalogTreeSelector,
    'fromweb-article-dialog': FromWebArticleDialog
  },
  props: {
    taskID: {
      type: [String, Number],
      default: 0
    },
    createFlag: {
      type: [String],
      default: ''
    }
  },
  watch: {
    catalog(val) {
      this.basicInfo.catalogID = val.ID
      this.basicInfo.catalogName = val.name
    }
  }
}
</script>

<style scoped>
.el-row .form-label{
  text-align: end;
  align-self: center;
}
.tabs-wrap {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  flex-wrap: nowrap;
}

.info-form-wrap {
  margin-top: 10px;
  padding: 10px 0;
  width: 560px;
}

.tag-item,
.title {
  line-height: 1.5;
  margin: 0.2em 0 0.3em 0;
}

.tag-item .tag-label {
  display: inline-block;
  text-align: right;
  width: 100%;
}

.title {
  margin-top: 1em;
  font-size: 20px !important;
}

.panel-fieldset .el-textarea {
  margin-bottom: 8px;
}

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

.input-300 {
  width: 90%;
  max-width: 300px;
}

.input-203 {
  width: 203px;
}
</style>
<style>
.tagP {
  font-size: 13px;
  margin: 20px 0 10px 10px;
}

input[type='file'] {
  display: none !important;
}

.el-upload__input {
  display: none !important;
}

/* label {
  margin: 0 !important;
  font-weight: normal !important;
} */

.title .el-checkbox__label {
  font-size: inherit;
}

</style>
