<template>
  <div>
    <!-- 工具栏 -->
    <el-toolbar v-if="!isAdd">
      <el-button :disabled="!ID" @click="save">
        <i class="fa fa-save"></i>保存</el-button>
      <el-button :disabled="!ID" @click="execute(false)">
        <i class="fa fa-hand-pointer-o f18"></i>手动执行</el-button>
      <el-button :disabled="!ID" @click="execute(true)">
        <i class="fa fa-refresh"></i>重新开始分发</el-button>
    </el-toolbar>
    <div class="layout-content-padding scroll">
      <el-form :model="deployData" label-width="150px" ref="deployDataForm" :rules="deployDataRules" :disabled="!editable">
        <div class="panel-card">
          <h4 class="panel-legend">基本信息</h4>
            <el-form-item label="任务名称：" prop="deployName" :verify="['NotNull']">
              <el-input v-model="deployData.deployName" class="form-item"></el-input>
            </el-form-item>
            <el-form-item label="任务状态：">
              <el-switch v-model="deployData.status" active-value="Y" inactive-value="N"></el-switch>
            </el-form-item>
            <el-form-item label="从此栏目分发：" prop="catalogID">
              <tree-select v-model="deployData.catalogID" :items="catalogTree" @click-change="deployCatalogChange" :disabled="!editable" width="300">
              </tree-select>
            </el-form-item>
            <el-form-item label="同步修改/删除/下线：">
              <el-switch v-model="deployData.syncArticleModify" active-value="Y" inactive-value="N"></el-switch>
            </el-form-item>
            <el-form-item label="初次分发后状态：">
              <el-select v-model="deployData.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="再次分发后状态：">
              <el-select v-model="deployData.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-card">
          <h4 class="panel-legend">目标栏目列表</h4>
          <el-toolbar>
            <el-button @click="addTarget" :disabled="!editable" type="primary">
              <i class="fa fa-plus"></i>添加</el-button>
            <!-- <el-button @click="editTarget" :disabled="!editable">
              <i class="fa fa-edit"></i>编辑</el-button> -->
            <el-button @click="deleteTarget(selectedRows)" :disabled="!editable || selectedRows.length===0" type="danger">
              <i class="fa fa-remove"></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 f18"></i></el-button>
                <el-button @click.stop="deleteTarget(scope.row)" type="text" title="删除">
                  <i class="fa fa-times f18"></i></el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
    </div>
    <addCatalog-dialog :show.sync="addCatalogModal" :target-catalog="tmpTargetCatalog" type="Deploy" :content-type="deployData.contentType"
      :edit-mode="editMode" :catalog-id="deployData.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 {
  data() {
    var checkTree = (rule, value, callback) => {
      if (value < 0) {
        return callback(new Error('不能为空'))
      } else {
        callback()
      }
    }
    return {
      deployData: {},
      tmpTargetCatalog: {},
      addCatalogModal: false,
      editMode: 0,
      targetCatalogData: [],
      oldCatalogID: '',
      oldCatalogType: '',
      afterSyncStatusOptions: [],
      catalogTree: [],
      afterModifyStatusOptions: [],
      selectedRows: [], // 选中的目标栏目行
      deployDataRules: {
        catalogID: [
          {
            required: true,
            validator: checkTree,
            trigger: 'blur,change'
          }
        ]
      } // 网站群分发数据匹配规则
    }
  },
  watch: {
    ID() {
      this.init()
      if (!this.isAdd) {
        this.dialogClose()
      }
    },
    deployData: {
      handler: function () {
        this.$emit('callback', this.deployData)
      },
      deep: true
    }
  },
  mounted() {
    this.init()
  },
  computed: {
    editable() {
      return this.ID || this.isAdd
    }
  },
  methods: {
    dialogClose() {
      this.$refs['deployDataForm'].resetFields()
    },
    async init() {
      if (String(this.ID) === '0') {
        return
      }
      this.selectedRows = []
      this.editMode = 0
      let treeProps = {
        isTarget: true,
        type: 'Deploy'
      }
      let bindCatalogTree = await axios.get(
        '/ui/sitegroup/bindcatalogtree',
        {
          params: treeProps
        }
      )
      this.catalogTree = bindCatalogTree.data.data
      let getStatus1 = await axios.get('/ui/sitegroup/getstatus', {
        params: {
          first: true
        }
      })
      this.afterSyncStatusOptions = getStatus1.data.data
      let getStatus2 = await axios.get('/ui/sitegroup/getstatus', {
        params: {
          first: false
        }
      })
      this.afterModifyStatusOptions = getStatus2.data.data
      let init = await axios.get('/ui/sitegroupdeploy/init', {
        params: {
          ID: this.ID
        }
      })
      this.deployData = init.data.data
      this.oldCatalogID = init.data.data.catalogID
      this.oldCatalogType = init.data.data.contentType
      this.deployData.afterSyncStatus = init.data.data.afterSyncStatus + ''
      this.deployData.afterModifyStatus = init.data.data.afterModifyStatus + ''
      if (this.ID === 0) {
        return
      }
      let bindTargetCatalog = await axios.get(
        '/ui/sitegroupdeploy/bindtargetcatalog',
        {
          params: {
            ID: this.ID
          }
        }
      )
      this.targetCatalogData = bindTargetCatalog.data.data
      this.deployData.targetCatalog = bindTargetCatalog.data.data
    },
    validateForm() {
      return util.validateForm(this.$refs['deployDataForm'])
    },
    deployCatalogChange(obj) {
      this.deployData.catalogID = obj.ID
      this.deployData.catalogName = obj.name
      this.deployData.contentType = obj.contentType
    },
    /** 保存任务按钮 */
    async save() {
      if (
        this.oldCatalogID !== this.deployData.catalogID ||
          this.oldCatalogType !== this.deployData.contentType
      ) {
        try {
          await this.$confirm('检测到来源栏目被修改，在此之前的部分内容可能不会被同步到目标栏目，你确定保存？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
          this.sendSaveDeployaxios()
        } catch (e) {

        }
      } else {
        this.sendSaveDeployaxios()
      }
    },
    /** 手工执行任务按钮 */
    async execute(restartFlag) {
      if (!this.ID || this.ID <= 0) {
        this.$alert('请先选择一条任务！', '提示', {
          type: 'info'
        })
        return
      }
      try {
        await this.$confirm('确定要执行该任务吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        let res = await axios.put(
          `/ui/sitegroupdeploy/${this.ID}/execute`,
          { restartFlag: this.restartFlag ? 'Y' : 'N' }
        )
        if (res.data.status === 1) {
          await util.showProgress(res.data.taskID, '正在分发数据. . .')
        } else {
          util.showErrorMessageBox(res.data.message)
        }
      } catch (e) {

      }
    },
    /** 添加目标栏目按钮 */
    async addTarget() {
      if (this.deployData.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.deployData.contentType &&
          this.targetCatalogData.length > 0 &&
          this.ID > 0
      ) {
        try {
          await this.$confirm('栏目类型变化会清空旧数据', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
          this.targetCatalogData = []
          this.addCatalogModal = true
        } catch (e) {

        }
      } else {
        this.addCatalogModal = true
      }
    },
    /** 编辑目标栏目按钮 */
    editTarget(row) {
      // //判断是否有选中的栏目数据
      // if (this.selectedRows.length < 1) {
      //   this.$alert('请先选择要编辑的行！', '提示', {
      //     type: 'info',
      //   })
      //   return
      // }
      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.deployData, 'targetCatalog')
      Vue.set(this.deployData, 'targetCatalog', this.targetCatalogData.concat())
      if (!this.isAdd) {
        this.sendSaveDeployaxios()
      }
    },
    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.deployData, 'targetCatalog')
      Vue.set(this.deployData, 'targetCatalog', this.targetCatalogData.concat())

      if (!this.isAdd) {
        this.sendSaveDeployaxios()
      }
    },
    async sendSaveDeployaxios() {
      try {
        await util.validateForm(this.$refs['deployDataForm'])
      } catch (e) {
        util.showErrorMessageBox(e)
        return
      }
      let obj = Object.assign({}, this.deployData)
      Vue.set(obj, 'data', JSON.stringify(this.targetCatalogData))
      let update = await axios.put(`/ui/sitegroupdeploy/${obj.ID}`, obj)
      util.showResponseMessage(update.data)
      if (update.data.status === 1) {
        this.$emit('callback', true)
        this.init()
      }
    },
    /** 改变选中目标栏目数据 */
    targetSelectionChange(selection) {
      if (selection.length === 0) {
        return
      }
      this.selectedRows = selection
    }
  },
  props: ['ID', 'isAdd'],
  components: {
    'tree-select': TreeSelect,
    'addCatalog-dialog': addCatalogDialog
  }
}
</script>

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

</style>
