<template>
  <div class="layout-no-flex right-list-panel-fieldset">
    <!-- 工具栏 -->
    <el-toolbar>
      <el-button @click="goBack" type="primary" size="medium" round class="shadow-primary"><i class="fa fa-chevron-left"></i> 返回上页</el-button>
      <span class="button-separator"></span>
      <span v-show="isAdd">
        <el-button type="button" class="el-button el-button--default save" :loading="saveLoading" @click="addSave"><span><i class="fa fa-save"></i>保存</span></el-button>
      </span>
      <span v-show="!isAdd">
        <el-button type="button" class="el-button el-button--default save" @click="execute(false)"><span><i class="fa fa-check"></i>手工执行</span></el-button>
        <el-button type="button" class="el-button el-button--default save" @click="execute(true)"><span><i class="fa fa-refresh"></i>重新开始采集</span></el-button>
        <el-button type="button" class="el-button el-button--default save" :loading="saveLoading" @click="save"><span><i class="fa fa-save"></i>保存</span></el-button>
      </span>
    </el-toolbar>
    <div v-loading="dataLoading">
      <el-form :model="gatherData" label-width="150px" ref="gatherDataForm" :rules="gatherDataRules">
        <div class="panel-fieldset">
          <h4 class="panel-legend">基本信息</h4>
          <el-form-item label="任务名称：" prop="gatherName" :verify="['NotNull']">
            <el-input v-model="gatherData.gatherName" class="form-item"></el-input>
          </el-form-item>
          <el-form-item label="任务状态：" prop="status">
            <el-switch v-model="gatherData.status" active-value="Y" inactive-value="N"></el-switch>
          </el-form-item>
          <el-form-item label="采集到此栏目" prop="catalogID">
            <tree-select v-model="gatherData.catalogID" :dim-info="{'enable':true}" @click-change="gatherCatalogChange" width="300">
            </tree-select>
          </el-form-item>
          <el-form-item label="同步修改/删除/下线：" prop="syncArticleModify">
            <el-switch v-model="gatherData.syncArticleModify" active-value="Y" inactive-value="N"></el-switch>
          </el-form-item>
          <el-form-item label="初次采集后状态：" prop="afterSyncStatus">
            <el-select v-model="gatherData.afterSyncStatus" class="form-item">
              <el-option v-for="str in afterSyncStatusOptions" :key="str.key" :label="str.value" :value="str.key">
              </el-option>
            </el-select>
            <el-tooltip class="item" effect="dark" content="采集栏目有工作流时只能是初稿状态" placement="right">
              <i class="fa fa-lightbulb-o fa-fw" style="color:#FFC125; margin-left:5px"></i>
            </el-tooltip>
          </el-form-item>
          <el-form-item label="再次采集后状态：" prop="afterModifyStatus">
            <el-select v-model="gatherData.afterModifyStatus" class="form-item">
              <el-option v-for="str in afterModifyStatusOptions" :key="str.key" :label="str.value" :value="str.key">
              </el-option>
            </el-select>
            <el-tooltip class="item" effect="dark" content="采集栏目有工作流时只能是初稿状态" placement="right">
              <i class="fa fa-lightbulb-o fa-fw" style="color:#FFC125; margin-left:5px"></i>
            </el-tooltip>
          </el-form-item>
        </div>
        <div class="panel-fieldset">
          <h4 class="panel-legend">目标栏目列表</h4>
          <el-toolbar>
            <el-button @click="addTarget">
              <i class="fa fa-plus"></i>添加</el-button>
          </el-toolbar>
          <!-- 目标栏目列表表格 -->
          <el-table ref="multipleTable" :data="targetCatalogData" tooltip-effect="dark" @selection-change="targetSelectionChange">
            <el-table-column type="selection" width="50"></el-table-column>
            <el-table-column prop="siteName" label="站点名称" min-width="30%"></el-table-column>
            <el-table-column prop="catalogName" label="栏目名称" min-width="20%"></el-table-column>
            <el-table-column prop="serverAddr" label="服务器地址" min-width="20%"></el-table-column>
            <el-table-column label="操作" align="right" min-width="15%">
              <template slot-scope="scope">
                <el-button @click.stop="editTarget(scope.row)" type="text" title="编辑">
                  <i class="fa fa-edit f16"></i>
                </el-button>
                <el-button @click.stop="deleteTarget(scope.row)" type="text" title="删除">
                  <i class="fa fa-times f16"></i>
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
    </div>
    <addCatalog-dialog :show.sync="addCatalogModal" :target-catalog="tmpTargetCatalog" type="Gather" :content-type="gatherData.contentType"
      :edit-mode="editMode" :catalog-id="gatherData.catalogID" @callback="addCatalogCallback"></addCatalog-dialog>
  </div>
</template>

<script>

import util from '@src/common/util.js'
import TreeSelect from '@src/components/TreeSelect.vue'
import addCatalogDialog from './addCatalogDialog.vue'

export default {
  components: {
    'tree-select': TreeSelect,
    'addCatalog-dialog': addCatalogDialog
  },
  props: {
    ID: {
      type: [String, Number]
    }
  },
  data() {
    var checkTree = (rule, value, callback) => {
      if (!value || value < 0) {
        return callback(new Error('栏目不能为空'))
      } else {
        callback()
      }
    }
    return {
      saveLoading: false,
      dataLoading: true,
      isAdd: false,
      gatherData: {
        gatherName: '',
        status: 'Y',
        syncArticleModify: 'Y',
        catalogID: '',
        afterSyncStatus: '0',
        afterModifyStatus: '20',
        targetCatalog: ''
      },
      tmpTargetCatalog: {},
      addCatalogModal: false,
      editMode: 0,
      targetCatalogData: [],
      oldCatalogID: '',
      oldCatalogType: '',
      afterSyncStatusOptions: [],
      catalogTree: [],
      afterModifyStatusOptions: [],
      selectedRows: [], // 选中的目标栏目行
      gatherDataRules: {
        catalogID: [
          {
            required: true,
            validator: checkTree,
            trigger: 'blur,change'
          }
        ]
      } // 网站群分发数据匹配规则
    }
  },
  async mounted() {
    this.isAdd = this.ID === 'new'
    this.dataLoading = true
    let datas
    try {
      datas = await Promise.all([
        axios.get(
          '/ui/sitegroup/bindcatalogtree',
          {
            params: {
              isTarget: true,
              type: 'Gather'
            }
          }
        ), axios.get('/ui/sitegroup/getstatus', {
          params: {
            first: true
          }
        }), axios.get('/ui/sitegroup/getstatus', {
          params: {
            first: false
          }
        })
      ])
    } catch (e) {
      util.showErrorMessageBox(e)
      return
    } finally {
      this.dataLoading = false
    }
    this.catalogTree = datas[0].data.data
    this.afterSyncStatusOptions = datas[1].data.data
    this.afterModifyStatusOptions = datas[2].data.data
    this.init()
  },
  methods: {
    async addSave() {
      this.saveLoading = true
      try {
        await util.validateForm(this.$refs.gatherDataForm)
      } catch (e) {
        util.showErrorMessageBox(e)
        this.saveLoading = false
        return
      }
      if (this.gatherData.targetCatalog.length === 0) {
        this.$alert('请先添加目标栏目', '提示', {
          type: 'warning'
        })
        this.saveLoading = false
        return
      }
      let res
      try {
        res = await axios.post('/ui/sitegroupgather', this.gatherData)
      } catch (e) {
        util.showErrorMessageBox(e)
        return
      } finally {
        this.saveLoading = false
      }
      util.showResponseMessage(res.data)
      if (res.data.status === 1) {
        this.isAdd = false
        this.oldCatalogID = this.gatherData.catalogID
        this.oldCatalogType = this.gatherData.contentType
        this.$router.replace(`/datachannel/gather/${res.data.ID}`)
      }
    },
    goBack() {
      this.$router.back()
    },
    async init() {
      this.dataLoading = true
      this.targetCatalogData = []
      this.selectedRows = []
      this.editMode = 0
      if (this.isAdd) {
        this.dataLoading = false
        return
      }
      let res
      try {
        res = await axios.get('/ui/sitegroupgather/init', {
          params: {
            ID: this.ID
          }
        })
      } catch (e) {
        util.showErrorMessageBox(e)
        return
      } finally {
        this.dataLoading = false
      }
      this.gatherData = res.data.data
      this.oldCatalogID = res.data.data.catalogID
      this.oldCatalogType = res.data.data.contentType
      this.gatherData.afterSyncStatus = res.data.data.afterSyncStatus + ''
      this.gatherData.afterModifyStatus = res.data.data.afterModifyStatus + ''
      this.targetCatalogData = res.data.data.targetCatalogData
      this.gatherData.targetCatalog = res.data.data.targetCatalogData
    },
    gatherCatalogChange(obj) {
      this.gatherData.catalogID = obj.ID
      this.gatherData.catalogName = obj.name
      this.gatherData.contentType = obj.contentType
    },
    // 保存任务按钮
    async save() {
      this.saveLoading = true
      if (
        this.oldCatalogID !== this.gatherData.catalogID ||
          this.oldCatalogType !== this.gatherData.contentType
      ) {
        try {
          await this.$confirm('检测到来源栏目被修改，在此之前的部分内容可能不会被同步到目标栏目，你确定保存？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
          this.sendSavegatherRequest()
        } catch (e) {
          this.saveLoading = false
        }
      } else {
        this.sendSavegatherRequest()
      }
    },
    // 手工执行任务按钮
    async execute(restartFlag) {
      if (this.isAdd) {
        this.$alert('页面异常，请刷新页面！', '提示', {
          type: 'info'
        })
        return
      }
      try {
        await this.$confirm('确定要执行该任务吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        let res = await axios.put(
          `/ui/sitegroupgather/${this.ID}/execute`,
          { restartFlag: restartFlag }
        )
        util.showResponseMessage(res.data)
        if (res.data.status === 1) {
          await util.showProgress(res.data.taskID, '正在采集数据. . .')
        }
      } catch (e) {

      }
    },
    // 添加目标栏目按钮
    async addTarget() {
      if (this.gatherData.catalogID <= 0) {
        this.$alert('请先添加基本信息中采集到此栏目的内容', '提示', {
          type: 'info'
        })
        return
      }

      this.editMode = 0
      this.tmpTargetCatalog = {
        serverAddr: 'localhost',
        siteID: '-1',
        siteName: '',
        catalogID: '-1',
        catalogName: '',
        password: '',
        lastTime: ''
      }
      if (
        this.oldCatalogType !== this.gatherData.contentType &&
          this.targetCatalogData.length > 0 && !this.isAdd
      ) {
        try {
          await this.$confirm('栏目类型变化会清空旧数据', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
          this.targetCatalogData = []
          this.addCatalogModal = true
        } catch (e) {

        }
      } else {
        this.addCatalogModal = true
      }
    },
    // 编辑目标栏目按钮
    editTarget(row) {
      this.editMode = 1
      this.tmpTargetCatalog = Object.assign({}, row)
      this.addCatalogModal = true
    },
    // 删除目标栏目按钮
    deleteTarget(data) {
      let isArray = Array.isArray(data)
      // 判断是否有选中的栏目数据
      if (isArray) {
        if (data.length < 1) {
          this.$alert('请先选择要删除的记录！', '提示', {
            type: 'info'
          })
          return
        }
        let rowIds = []
        data.forEach(row => {
          let index = this.targetCatalogData.findIndex(val => val === row)
          rowIds.push(index)
        })
        this.targetCatalogData = this.targetCatalogData.filter(
          (val, i) => !rowIds.includes(i)
        )
      } else {
        this.targetCatalogData = this.targetCatalogData.filter(val => val !== data)
      }
      Vue.delete(this.gatherData, 'targetCatalog')
      Vue.set(this.gatherData, 'targetCatalog', this.targetCatalogData.concat())
      if (!this.isAdd) {
        this.sendSavegatherRequest()
      }
    },
    addCatalogCallback(val) {
      if (this.editMode === 1) {
        let index = this.targetCatalogData.findIndex(
          val => val === this.selectedRows[0]
        )
        this.targetCatalogData.splice(index, 1, Object.assign({}, val))
      } else {
        this.targetCatalogData = [
          ...this.targetCatalogData,
          Object.assign({}, val)
        ]
      }
      Vue.delete(this.gatherData, 'targetCatalog')
      Vue.set(this.gatherData, 'targetCatalog', this.targetCatalogData.concat())

      if (!this.isAdd) {
        this.sendSavegatherRequest()
      }
    },
    async sendSavegatherRequest() {
      this.saveLoading = true
      try {
        await util.validateForm(this.$refs['gatherDataForm'])
      } catch (e) {
        util.showErrorMessageBox(e)
        this.saveLoading = false
        return
      }
      let obj = Object.assign({}, this.gatherData)
      Vue.set(obj, 'data', JSON.stringify(this.targetCatalogData))
      let res
      try {
        res = await axios.put(`/ui/sitegroupgather/${obj.ID}`, obj)
      } catch (e) {
        util.showErrorMessageBox(e)
        return
      } finally {
        this.saveLoading = false
      }
      util.showResponseMessage(res.data)
    },
    // 改变选中目标栏目数据
    targetSelectionChange(selection) {
      if (selection.length === 0) {
        return
      }
      this.selectedRows = selection
    }
  }
}
</script>

<style scoped>
  .form-item {
    width: 300px;
  }
</style>
