<template>
  <div>

    <div class="layout-col-detail">

      <!-- 工具条start -->
      <el-toolbar v-if="typeID !== ''">
        <el-button @click="backListPage" 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="saveClick" :loading="confirmLoading" type="text" :priv="typeID!=='new' ? ('com.zving.cms.Block.Edit.' + blockID) : ''" title="保存">
          <i class="fa fa-save" aria-hidden="true"></i>保存
        </el-button>
        <span v-show="!!selectedRow.ID && typeID !== 'edit'">
          <el-button @click="publish([selectedRow])" type="text" title="发布" :priv="`com.zving.cms.Block.Publish.${blockID}`">
            <i class="fa fa-send-o" aria-hidden="true"></i>发布
          </el-button>
          <el-button @click="preview(selectedRow)" type="text" title="预览">
            <i class="fa fa-search" aria-hidden="true"></i>预览
          </el-button>
          <el-button @click="versionClick" v-show="selectedRow.type === 'Html'||selectedRow.type ==='Manual'"  type="text" title="版本" :priv="`com.zving.cms.Block.Edit.${blockID}`">
            <i class="fa fa-book" aria-hidden="true"></i>版本
          </el-button>
        </span>
      </el-toolbar>

      <!-- 工具条end -->

      <!-- 右侧模块 -->
      <div class="padding-top-bottom">
        <div class="detail-panel" v-for="item in blockExtraItems" :key="item.ID">
          <div class="panel-header">
            <span class="title">{{item.name}}</span>
          </div>

          <div class="main">
            <component
              :is="item.ID"
              :ID="selectedRow.ID"
              :change-flag="changeFlag"
              :tmp-condition.sync="tmpConditions"
              :data-model.sync="selectedRow"
              :auto-model.sync="autoModel"
              :widget-model.sync="widgetModel"
              :save-flag="saveFlag"
              :content.sync="selectedRow.content"
              :panel-title="panelTitle"
              :is-detail="typeID !== blockID"
              @validate="validateCallBack"
              @blockTypeChange="blockTypeChange"
            >
            </component>
          </div>
        </div>

      </div>
    </div>
    <!-- 版本编辑弹窗 -->
    <version-dialog :show.sync="version.isShowModal" @clickRestore="restore" :blockID.sync="blockID"></version-dialog>

  </div>
</template>

<script>
import util from '@src/common/util.js'
import BlockDocDialog from '../workspace/components/BlockDocDialog.vue'
import VersionDialog from './versionDialog.vue'
import basicInfo from './components/BasicInfoBlock.vue'
import chooseContent from './components/ChooseContentBlock.vue'
import selfTemplate from './components/SelfTemplateBlock.vue'
import pageWidget from './components/PageWidgetBlock.vue'
import filterContent from './components/FilterContentBlock.vue'
import htmlEditor from './components/HtmlEditorBlock.vue'
import templateSelect from './components/TemplateSelectBlock.vue'

export default {
  components: {
    'blockDoc-dialog': BlockDocDialog,
    'version-dialog': VersionDialog,
    basicInfo,
    chooseContent,
    selfTemplate,
    pageWidget,
    filterContent,
    templateSelect,
    htmlEditor

  },
  props: {
    ID: [String, Number]
  },
  data() {
    return {
      typeID: '',
      dataLoading: true,
      blockID: 0,
      catalogID: 0,
      // 自动列表数据模型
      autoModel: {
        ID: '',
        Type: '',
        retemplateContent: '',
        templateParams: '',
        content: {}
      },
      // 自动列表内容数据模型
      autoContent: {
        fromCatalogID: '',
        contentType: 'Article',
        contentTypeName: '文章',
        isCascade: '',
        fromCatalogName: '',
        condition: [[]],
        sortField: [[]],
        items: {}
      },
      changeFlag: false,
      saveFlag: false,
      validateOk: false,
      count: 0,
      htmlContent: '',
      widgetModel: {},
      blockType: 3, // 1:自动列表 2:HTML代码 3:手工选择 4:模板生成 5:页面部件
      blockSelectVisible: false, // 路径选择弹窗
      blockListData: [],
      selectedRows: [],
      selectedRow: {},
      confirmLoading: false,
      version: { isShowModal: false },
      tmpConditions: {}, // 筛选条件数据
      blockExtraItems: [],
      panelTitle: ''
    }
  },
  async mounted() {
    this.catalogID = this.$route.query.catalogID || null
    this.typeID = this.$route.params.ID
    if (this.typeID === 'new') {
      this.panelTitle = '新建区块'
      this.blockID = this.$route.query.blockID || null
      if (!this.blockID) {
        let obj = {
          type: 'Manual',
          name: '',
          code: '',
          width: '',
          path: 'include/block/',
          minWeight: '',
          maxWeight: '',
          weightrange: '',
          recommendType: 1
        }
        await this.loadDetailInfo([obj])
        this.dataLoading = false
        return
      }
      this.panelTitle = '类似新建'
      let res = await axios.get(`/ui/blocklist/${this.blockID}/initdialog`)
      let obj = Object.assign({}, res.data.data)
      Vue.delete(obj, 'ID')
      await this.loadDetailInfo([obj])
      this.dataLoading = false
    } else {
      this.blockID = this.typeID === 'edit' ? this.$route.query.blockID : this.typeID
      let res = await axios.get(`/ui/blocklist/${this.blockID}/initdialog`)
      await this.loadDetailInfo([res.data.data])
      this.dataLoading = false
    }
  },
  methods: {
    restore(row) {
      this.loadDetailInfo([row])
    },
    blockTypeChange(val) {
      this.selectedRow.type = val
      this.loadDetailInfo([])
    },
    async loadDetailInfo(selection) {
      this.changeFlag = false
      if (selection[0]) {
        this.selectedRow = JSON.parse(JSON.stringify(selection[0]))
      }
      if (!this.selectedRow.ID || this.typeID === 'edit') {
        this.blockExtraItems = [{ID: 'basicInfo', name: this.typeID === 'edit' ? '编辑区块信息' : this.panelTitle}]
        return
      }

      /* 点击左侧表格,加载数据到右侧,自动区块和页面部件需要对数据进行处理 */
      if (this.selectedRow.type === 'Auto') {
        this.blockExtraItems = [{ID: 'basicInfo', name: '基本信息'}, {ID: 'filterContent', name: '自选内容'}, {ID: 'selfTemplate', name: '内置模板'}]
        this.$nextTick(() => {
          if (selection[0] && selection[0].ID) {
            this.changeFlag = true
          }
          if (!this.selectedRow.content) {
            this.autoModel.content = this.autoContent
          } else {
            this.autoModel.content = JSON.parse(this.selectedRow.content)
          }
          this.autoModel.ID = this.selectedRow.ID
          this.autoModel.type = this.selectedRow.type
          this.autoModel.templateContent = this.selectedRow.templateContent
          this.autoModel.templateParams = this.selectedRow.templateParams
          this.tmpConditions = {
            column1: '',
            column1OperatorSelected: '',
            column1Operator: '',
            column1Value: '',
            column1ValueSelected: '',
            columnGroup2: '',
            column2: '',
            column2OperatorSelected: '',
            column2Operator: '',
            column2Value: '',
            column2ValueSelected: '',
            columnGroup3: '',
            column3: '',
            column3OperatorSelected: '',
            column3Operator: '',
            column3Value: '',
            column3ValueSelected: '',
            group: 'and',
            column4: '',
            column4OperatorSelected: '',
            column4Operator: '',
            column4Value: '',
            column4ValueSelected: '',
            columnGroup5: '',
            column5: '',
            column5OperatorSelected: '',
            column5Operator: '',
            column5Value: '',
            column5ValueSelected: '',
            columnGroup6: '',
            column6: '',
            column6OperatorSelected: '',
            column6Operator: '',
            column6Value: '',
            column6ValueSelected: '',
            orderColumnCount: 5,
            orderColumn1: 'ID',
            orderColumn1OrderType: '',
            orderColumn2: 'OrderFlag',
            orderColumn2OrderType: '',
            orderColumn3: 'PublishDate',
            orderColumn3OrderType: '',
            orderColumn4: 'TopFlag',
            orderColumn4OrderType: '',
            orderColumn5: 'BranchInnerCode',
            orderColumn5OrderType: ''
          }
        })
      }
      if (this.selectedRow.type === 'Widget') {
        this.widgetModel = this.selectedRow.content || ''
        this.blockExtraItems = [{ID: 'basicInfo', name: '基本信息'}, {ID: 'pageWidget', name: '页面部件'}]
      }
      if (this.selectedRow.type === 'Manual') {
        this.blockExtraItems = [{ID: 'basicInfo', name: '基本信息'}, {ID: 'chooseContent', name: '内容'}, {ID: 'selfTemplate', name: '内置模板'}]
      }
      if (this.selectedRow.type === 'Html') {
        this.blockExtraItems = [{ID: 'basicInfo', name: '基本信息'}, {ID: 'htmlEditor', name: 'HTML编辑器'}]
      }
      if (this.selectedRow.type === 'Template') {
        this.blockExtraItems = [{ID: 'basicInfo', name: '基本信息'}, {ID: 'templateSelect', name: '模板文件'}]
      }
    },
    backListPage() {
      this.$router.back()
    },

    versionClick() {
      this.version.isShowModal = true
    },

    saveClick() {
      this.confirmLoading = true
      this.saveFlag = true
      /* 此时saveFlag值发生改变，
        会被其他组件监听到，触发表单验证，
        验证完成后会在回调方法validateCallBack()中完成保存 */
      this.count = 0
    },

    /* 组件中的表单验证完成后回调方法 */
    async validateCallBack(value) {
      this.saveFlag = false
      if (!this.selectedRow.ID && value) {
        let res = await axios.post('/ui/blocklist', Object.assign({}, this.selectedRow, {catalogID: this.catalogID}))
        try {
          util.showResponseMessage(res.data)
          this.confirmLoading = false
          if (res.data.status === 1) {
            // this.backListPage()
            // this.$router.replace(`/editorWorkspace/Block/edit?blockID=${res.data.ID}&catalogID=${this.catalogID}`)
            let refreshRes = await axios.get(`/ui/blocklist/${res.data.ID}/initdialog`)
            await this.loadDetailInfo([refreshRes.data.data])
          }
          return
        } catch (e) {
          return
        }
      }
      if (value) {
        this.count++
      } else {
        util.showErrorMessageBox('没有正确填写表单项！')
        this.confirmLoading = false
        return
      }
      if (this.selectedRow.type === 'Auto' && (this.count === 2 || this.typeID === 'edit')) {
        this.save()
      } else if (this.selectedRow.type !== 'Auto' && this.count === 1) {
        this.save()
      }
    },

    async save() {
      // 自动区块和页面部件部分对象合并
      if (this.selectedRow.type === 'Auto') {
        let condition = [[]]
        let sortField = [[]]
        await new Promise(resolve => {
          let condition1 = []
          let condition2 = []
          condition1.push({
            column: '',
            operator: '(',
            value: '',
            type: 'group'
          })
          for (let i = 1; i <= 3; i++) {
            if (
              this.tmpConditions['column' + i] !== '' &&
              this.tmpConditions['column' + i + 'OperatorSelected'] &&
              this.tmpConditions['column' + i + 'ValueSelected'] &&
              this.tmpConditions['column' + i + 'OperatorSelected'] !== '' &&
              this.tmpConditions['column' + i + 'ValueSelected'] !== ''
            ) {
              if (this.tmpConditions['columnGroup' + i] !== '' && condition1.length > 1) {
                condition1.push({
                  column: '',
                  operator: this.tmpConditions['columnGroup' + i],
                  value: '',
                  type: 'columngroup'
                })
              }
              if (this.tmpConditions['column' + i] === 'Attribute') {
                this.tmpConditions['column' + i + 'ValueSelected'] = this.tmpConditions['column' + i + 'ValueSelected'].join(',')
              }
              condition1.push({
                column: this.tmpConditions['column' + i],
                operator: this.tmpConditions['column' + i + 'OperatorSelected'],
                value: this.tmpConditions['column' + i + 'ValueSelected'],
                type: 'column'
              })
            }
          }
          condition1.push({
            column: '',
            operator: ')',
            value: '',
            type: 'group'
          })
          condition2.push({
            column: '',
            operator: '(',
            value: '',
            type: 'group'
          })
          for (let i = 4; i <= 6; i++) {
            if (
              this.tmpConditions['column' + i] !== '' &&
              this.tmpConditions['column' + i + 'OperatorSelected'] &&
              this.tmpConditions['column' + i + 'ValueSelected'] &&
              this.tmpConditions['column' + i + 'OperatorSelected'] !== '' &&
              this.tmpConditions['column' + i + 'ValueSelected'] !== ''
            ) {
              if (this.tmpConditions['columnGroup' + i] !== '' && condition2.length > 1) {
                condition2.push({
                  column: '',
                  operator: this.tmpConditions['columnGroup' + i],
                  value: '',
                  type: 'columngroup'
                })
              }
              if (this.tmpConditions['column' + i] === 'Attribute') {
                this.tmpConditions['column' + i + 'ValueSelected'] = this.tmpConditions['column' + i + 'ValueSelected'].join(',')
              }
              condition2.push({
                column: this.tmpConditions['column' + i],
                operator: this.tmpConditions['column' + i + 'OperatorSelected'],
                value: this.tmpConditions['column' + i + 'ValueSelected'],
                type: 'column'
              })
            }
          }
          condition2.push({
            column: '',
            operator: ')',
            value: '',
            type: 'group'
          })
          if (condition1.length > 2) {
            condition[0] = condition1
          }
          if (condition1.length > 2 && condition2.length > 2) {
            condition[0].push({
              column: '',
              operator: this.tmpConditions.group,
              value: '',
              type: 'group'
            })
          }
          if (condition2.length > 2) {
            condition[0] = condition[0].concat(condition2)
          }
          for (let i = 1; i <= 3; i++) {
            if (this.tmpConditions['orderColumn' + i] !== '' && this.tmpConditions['orderColumn' + i + 'OrderType'] !== '') {
              sortField[0].push({
                column: this.tmpConditions['orderColumn' + i],
                type: this.tmpConditions['orderColumn' + i + 'OrderType']
              })
            }
          }
          resolve()
        })
        this.autoModel.content.condition = condition
        this.autoModel.content.sortField = sortField
        var optionalContent = {
          content: JSON.stringify(this.autoModel.content),
          templateContent: this.selectedRow.templateContent,
          templateParams: this.selectedRow.templateParams
        }
      }
      if (this.selectedRow.type === 'Widget') {
        var pageComponent = { content: this.widgetModel }
      }
      let obj = Object.assign({}, this.selectedRow, pageComponent, optionalContent)
      // 保存
      let res = await axios.put(`/ui/blocklist/${obj.ID}`, obj)
      util.showResponseMessage(res.data)
      this.loadDetailInfo([obj])
      this.confirmLoading = false
    },

    async publish(selectedRows) {
      let IDs = []
      selectedRows.forEach(function (row) {
        IDs.push(row.ID)
      })
      if (!IDs) {
        return
      }
      let data
      try {
        data = await axios.put(`/ui/blocklist/publish/${IDs.join(',')}`)
      } catch (e) {
        util.showErrorMessageBox('请求失败，请稍后重试！')
      }
      util.showResponseMessage(data.data)
    },

    async preview(selectedRow) {
      if (selectedRow.type === 'Widget') {
        if (!selectedRow.content) {
          this.$alert('请先为页面部件区块选取相应的页面部件！', '提示', {type: 'warning'})
          return
        }
        let content = JSON.parse(selectedRow.content)
        window.open(`preview.html?&ID=${content.ID}&type=${content.type}`)
      } else {
        window.open(`preview.html?id=${selectedRow.ID}&type=block_preview`)
      }
    }

  }
}
</script>

<style scoped>
  .status-tag {
    margin: 8px 0;
  }
  .detail-panel .block-tabs {
    list-style: none;
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
    justify-content: flex-end;
  }
  .detail-panel .block-tabs li {
    font-size: 15px;
    color: #424242;
    margin: 16px;
    cursor: pointer;
  }
  .detail-panel .block-tabs li.on {
    color: #29b06d;
    border-bottom: 1px solid #29b06d;
  }

  .detail-panel .panel-footer {
    margin-top: 20px;
    background-color: #fff;
    padding-bottom: 0;
  }
</style>
