/* global axios */
import util from '@src/common/util.js'
import PCTemplate from './components/CatalogDefaultTemplate.vue'
import PathPicker from './components/PathPicker.vue'
import LogoPath from './components/LogoPath.vue'
import TreeSelect from '@src/components/TreeSelect.vue'
import CatalogSelector from './components/CatalogSelector.vue'
import ConditionItem from '@src/components/contentComponent/conditionItem.vue'
import CommonCatalogSelector from './components/CommonCatalogSelector.vue'
import CatalogPublishDropDown from './components/CatalogPublishDropDown.vue'
import CatalogPrivilegeDropDown from './components/CatalogPrivilegeDropDown.vue'
import CatalogScanPreviewDropDown from './components/CatalogScanPreviewDropDown.vue'
import CatalogImportButton from './components/CatalogImportButton.vue'
import CatalogDeleteButton from './components/CatalogDeleteButton.vue'
import CatalogExportStructureButton from './components/CatalogExportStructureButton.vue'
import CatalogMoveButton from './components/CatalogMoveButton.vue'
import CatalogSortButton from './components/CatalogSortButton.vue'
export default {
  components: {
    'pc-template': PCTemplate,
    'tree-select': TreeSelect,
    'path-picker': PathPicker,
    'logo-path': LogoPath,
    'virtual-condition': ConditionItem,
    'catalog-selector': CatalogSelector,
    'common-catalog-selector': CommonCatalogSelector,
    'c-publish-dropdown': CatalogPublishDropDown,
    'c-privilege-dropdown': CatalogPrivilegeDropDown,
    'c-scan-preview-dropdown': CatalogScanPreviewDropDown,
    'c-import-button': CatalogImportButton,
    'c-del-button': CatalogDeleteButton,
    'c-export-structure-button': CatalogExportStructureButton,
    'c-move-button': CatalogMoveButton,
    'c-sort-button': CatalogSortButton
  },
  props: {
    catalogId: [Number, String],
    type: String,
    oldType: String,
    contentType: String,
    types: Array,
    contentTypes: Array,
    branchTree: Array,
    treeItemsOptions: Object,
    tabName: String,
    dimensionId: {
      type: [Number, String],
      default: 1
    }
  },
  data () {
    return {
      submitLoading: false,
      siteID: 0,
      platformID: 'pc', /** 平台类型 */
      catalogVirtualInfo: {
        conditions: {
          fromCatalogID: '',
          contentType: 'Article',
          contentTypeName: '文章',
          isCascade: 'Y',
          fromCatalogName: '',
          condition: ''
        },
        branchInnerCode: '',
        logoFile: ''
      }, /** 基本信息 */
      tmpCondition: {}, /** 数据拷贝 */
      checkMappingLoading: [false, false],
      dataLoading: false, /** 数据加载 */
      mappingFlags: [], /** 映射类型 */
      resourceDialogProps: {},
      catalogSelector: {
        isShowModal: false,
        showCheckBox: false,
        hasCheckedIds: []
      }, /** 选择栏目子组件变量 */
      commonCatalogSelector: {
        isShowModal: false,
        showCheckBox: false,
        hasCheckedIds: []
      }, /** 选择栏目子组件变量 */
      hasLoadBasic: false, /** 加载虚拟栏目条件筛选模块 */
      conditionInitURL: []
    }
  },
  watch: {
    tabName (val) {
      if (val === 'info') {
        this.hasLoadBasic = false
        this.loadVirtualCatalogInfo()
      }
    },
    catalogId: function (val) {
      if (val && this.tabName === 'info') {
        this.hasLoadBasic = false
        this.loadVirtualCatalogInfo()
      }
    }
  },
  created () {
    this.loadVirtualCatalogInfo()
    this.loadVirtualMappingTypes()
  },
  methods: {
    loadCatalogTree (val) {
      if (val === 'del') {
        this.$refs['catalog-virtual-info'].resetFields()
      }
      this.$emit('loadCatalogTree', val)
    },
    async visible () {
      if (!this.catalogId) {
        return
      }
      let changeVisible = async () => {
        let params = {
          catalogID: this.catalogId,
          visibleFlag: this.catalogVirtualInfo.visibleFlag
        }
        let res = await axios.put(
          `/ui/catalogs/changevisible`,
          params
        )
        if (res.data.status === 1) {
          this.$emit('loadCatalogTree')
        }
        util.showResponseMessage(res.data)
      }
      if (!this.catalogVirtualInfo.isLeaf) {
        try {
          await this.$confirm('修改本栏目的状态，子栏目的状态也会被改变，确认要执行此操作吗？', '系统提示', {
            confirmButtonText: '确定',
            showCancelButton: false,
            type: 'warning'
          })
          await changeVisible()
        } catch (e) {
          return
        }
      } else {
        await changeVisible()
      }
      this.loadCatalogBasicInfo()
    },
    /** 选择栏目回调 */
    getCatalogIds (data) {
      data = data || {}
      this.catalogVirtualInfo.conditions.fromCatalogID = data.ids || 0
      this.catalogVirtualInfo.conditions.fromCatalogName = data.names || ''
    },
    /** 选择公共站点栏目回调 */
    getCommonCatalogIds (data) {
      data = data || {}
      this.catalogVirtualInfo.conditions.fromCatalogID = data.ids || 0
      this.catalogVirtualInfo.conditions.fromCatalogName = data.names || ''
    },

    /** 选择公共站点栏目 */
    selectCommonCatalogClickHandler () {
      this.commonCatalogSelector.hasCheckedIds = []
      this.commonCatalogSelector.isShowModal = true
      this.commonCatalogSelector.showCheckBox = true
      if (this.catalogVirtualInfo.conditions.fromCatalogID) {
        let ids = this.catalogVirtualInfo.conditions.fromCatalogID.split(',')
        ids.forEach(row => {
          this.commonCatalogSelector.hasCheckedIds.push(parseInt(row, 10))
        })
      }
    },
    /** 选择栏目 */
    selectVirtualCatalogClickHandler () {
      this.catalogSelector.hasCheckedIds = []
      this.catalogSelector.isShowModal = true
      this.catalogSelector.showCheckBox = 'checkbox'
      if (this.catalogVirtualInfo.conditions.fromCatalogID) {
        let ids = this.catalogVirtualInfo.conditions.fromCatalogID.split(',')
        ids.forEach(row => {
          this.catalogSelector.hasCheckedIds.push(parseInt(row, 10))
        })
      }
    },
    /** 保存虚拟栏目条件筛选 */
    async saveConditions () {
      this.catalogVirtualInfo.conditions.condition = [[]]
      await new Promise(resolve => {
        let condition1 = []
        let condition2 = []
        condition1.push({
          column: '',
          operator: '(',
          value: '',
          type: 'group'
        })
        for (let i = 1; i <= 3; i++) {
          if (
            this.tmpCondition['column' + i] !== '' &&
            this.tmpCondition['column' + i + 'OperatorSelected'] &&
            this.tmpCondition['column' + i + 'ValueSelected'] &&
            this.tmpCondition['column' + i + 'OperatorSelected'] !== '' &&
            this.tmpCondition['column' + i + 'ValueSelected'] !== ''
          ) {
            if (this.tmpCondition['columnGroup' + i] !== '' && condition1.length > 1) {
              condition1.push({
                column: '',
                operator: this.tmpCondition['columnGroup' + i],
                value: '',
                type: 'columngroup'
              })
            }
            if (this.tmpCondition['column' + i] === 'Attribute' && this.tmpCondition['column' + i + 'ValueSelected'].length > 0) {
              this.tmpCondition['column' + i + 'ValueSelected'] = this.tmpCondition['column' + i + 'ValueSelected'].join(',')
            }
            condition1.push({
              column: this.tmpCondition['column' + i],
              operator: this.tmpCondition['column' + i + 'OperatorSelected'],
              value: this.tmpCondition['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.tmpCondition['column' + i] !== '' &&
            this.tmpCondition['column' + i + 'OperatorSelected'] &&
            this.tmpCondition['column' + i + 'ValueSelected'] &&
            this.tmpCondition['column' + i + 'OperatorSelected'] !== '' &&
            this.tmpCondition['column' + i + 'ValueSelected'] !== ''
          ) {
            if (this.tmpCondition['columnGroup' + i] !== '' && condition2.length > 1) {
              condition2.push({
                column: '',
                operator: this.tmpCondition['columnGroup' + i],
                value: '',
                type: 'columngroup'
              })
            }
            if (this.tmpCondition['column' + i] === 'Attribute' && this.tmpCondition['column' + i + 'ValueSelected'].length > 0) {
              this.tmpCondition['column' + i + 'ValueSelected'] = this.tmpCondition['column' + i + 'ValueSelected'].join(',')
            }
            condition2.push({
              column: this.tmpCondition['column' + i],
              operator: this.tmpCondition['column' + i + 'OperatorSelected'],
              value: this.tmpCondition['column' + i + 'ValueSelected'],
              type: 'column'
            })
          }
        }
        condition2.push({
          column: '',
          operator: ')',
          value: '',
          type: 'group'
        })
        if (condition1.length > 2) {
          this.catalogVirtualInfo.conditions.condition[0] = condition1
        }
        if (condition1.length > 2 && condition2.length > 2) {
          this.catalogVirtualInfo.conditions.condition[0].push({
            column: '',
            operator: this.tmpCondition.group,
            value: '',
            type: 'group'
          })
        }
        if (condition2.length > 2) {
          this.catalogVirtualInfo.conditions.condition[0] = this.catalogVirtualInfo.conditions.condition[0].concat(condition2)
        }
        resolve()
      })
    },
    /** 保存栏目基本信息 */
    async catalogSaveClickHandler () {
      if (!this.catalogVirtualInfo.name || !this.catalogVirtualInfo.alias || !this.catalogVirtualInfo.path) {
        this.dialog('不能为空')
        return
      }
      this.catalogVirtualInfo.name = this.catalogVirtualInfo.name.replace('\t', '  ')
      this.catalogVirtualInfo.name = this.catalogVirtualInfo.name.replace('/\r\b\f/g', '')
      let saveCatalog = async () => {
        this.saveConditions()
        await util.validateForm(this.$refs['catalog-virtual-info'])
        let res = await axios.put(`/ui/virtualcatalog/${this.catalogId}`, this.catalogVirtualInfo)
        this.submitLoading = false
        util.showResponseMessage(res.data)
        if (res.data.status === 1) {
          this.$emit('loadCatalogTree', this.catalogVirtualInfo)
          this.loadVirtualCatalogInfo()
        }
      }
      if (this.oldType !== this.catalogVirtualInfo.type) {
        try {
          await this.$confirm('修改栏目类型将清空栏目下的原有内容数据，确认修改？', '系统提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
          saveCatalog()
        } catch (e) {
        }
      } else {
        if (this.contentType !== this.catalogVirtualInfo.contentType) {
          try {
            await this.$confirm('修改栏目内容类型将清空栏目下的原有内容数据，确认修改？', '系统提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            })
            saveCatalog()
          } catch (e) {
          }
        } else {
          saveCatalog()
        }
      }
    },
    /** 发布栏目弹框回调 */
    async afterPublishCallBack (taskID) {
      await util.showProgress(taskID, `正在发布[${this.catalogVirtualInfo.name}]栏目`)
    },
    async catalogImportCallBack (res) {
      await util.showProgress(res.data.taskID, `正在导入到[${this.catalogVirtualInfo.name}]栏目`)
    },
    /** 撤销 */
    // async catalogRollBackClickHandler () {
    //   try {
    //     let res = await axios.put('/ui/contentcore/siteoperation/rollback')
    //     util.showResponseMessage(res.data)
    //   } catch (e) {
    //     util.showErrorNotification(e)
    //   }
    // },
    /** 生效 */
    // async catalogTakeEffectClickHandler () {
    //   try {
    //     let res = await axios.put('/ui/contentcore/siteoperation/takeeffect')
    //     util.showResponseMessage(res.data)
    //   } catch (e) {
    //     util.showErrorNotification(e)
    //   }
    // },
    /** 检查虚拟栏目映射 */
    async checkMapping () {
      this.checkMappingLoading[0] = true
      try {
        let res = await axios.put(`/ui/virtualcatalog/${this.catalogId}/checkmapping`)
        this.checkMappingLoading[0] = false
        if (res.data.status === 1) {
          await util.showProgress(res.data.taskID, '正在检查映射')
        } else {
          util.showResponseMessage(res.data)
        }
      } catch (e) {
        this.checkMappingLoading[0] = false
        // util.showErrorNotification(e)
      }
    },
    /** 检查虚拟栏目全部映射 */
    async checkMappingAll () {
      this.checkMappingLoading[1] = true
      try {
        let res = await axios.put(`/ui/virtualcatalog/0/checkmappingall`)
        this.checkMappingLoading[1] = false
        if (res.data.status === 1) {
          await util.showProgress(res.data.taskID, '正在检查映射')
        } else {
          util.showResponseMessage(res.data)
        }
      } catch (e) {
        this.checkMappingLoading[1] = false
        // util.showErrorNotification(e)
      }
    },
    turnToPlatformTabs (tabName) {
      this.$emit('update:tabName', tabName)
    },
    /** 加载映射类型 */
    async loadVirtualMappingTypes () {
      let codeid = 'VirtualMappingType'
      let res = await axios.get(`/ui/platform/codes/${codeid}`)
      this.mappingFlags = res.data.data
    },
    /** 加载虚拟栏目基本信息 */
    async loadVirtualCatalogInfo () {
      this.dataLoading = true
      let res = await axios.get(`/ui/virtualcatalog/${this.catalogId}`)
      this.hasLoadBasic = true
      this.tmpCondition = {
        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: ''
      }
      this.dataLoading = false
      this.catalogVirtualInfo = res.data.data
      this.catalogVirtualInfo.type = 'Virtual'
      this.conditionInitURL = [
        '/ui/virtualcatalog/initcondition',
        {
          params: {
            catalogID: this.catalogId,
            contentType: this.catalogVirtualInfo.conditions.contentType
          }
        }
      ]
      this.resourceDialogProps = {
        dataType: 'CatalogLogo',
        dataID: this.catalogId,
        resourceType: 'image',
        imageType: 'logo',
        catalogID: this.catalogId,
        imageWidth: 120,
        imageHeight: 120,
        inputType: 'radio'
      }
    },
    // 消息Dialog封装
    dialog (msg) {
      this.$confirm(msg, '系统提示', {
        confirmButtonText: '确定',
        showCancelButton: false,
        type: 'warning'
      })
    }
  }
}
