/* global axios */
import util from '@src/common/util.js'
import TreeSelect from '@src/components/TreeSelect.vue'
import PathPicker from './components/PathPicker.vue'
import LogoPath from './components/LogoPath.vue'
import CatalogBasicExtends from './../contentextend/components/CatalogInfoExtendAction.vue'
import CatalogMergeButton from './components/CatalogMergeButton.vue'
import CatalogPCTemplate from './components/CatalogDefaultTemplate.vue'
import CatalogCleanButton from './components/CatalogCleanButton.vue'
import CatalogContentExportImportDropDown from './components/CatalogContentExportImportDropDown.vue'
import CatalogPrivilegeDropDown from './components/CatalogPrivilegeDropDown.vue'
import CatalogPublishDropDown from './components/CatalogPublishDropDown.vue'
import CatalogScanPreviewDropDown from './components/CatalogScanPreviewDropDown.vue'
import CatalogImportButton from './components/CatalogImportButton.vue'
import CatalogSimilarAddButton from './components/CatalogSimilarAddButton.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: {
    'c-merge-button': CatalogMergeButton,
    'c-publish-dropdown': CatalogPublishDropDown,
    'pc-template': CatalogPCTemplate,
    'tree-select': TreeSelect,
    'path-picker': PathPicker,
    'logo-path': LogoPath,
    'c-privilege-dropdown': CatalogPrivilegeDropDown,
    'catalog-basic-extends': CatalogBasicExtends,
    'c-scan-preview-dropdown': CatalogScanPreviewDropDown,
    'c-content-export-import-dropdown': CatalogContentExportImportDropDown,
    'c-clean-button': CatalogCleanButton,
    'c-import-button': CatalogImportButton,
    'c-similar-add-button': CatalogSimilarAddButton,
    '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: {
      type: String,
      default: ''
    },
    types: Array,
    contentTypes: Array,
    branchTree: Array,
    treeItemsOptions: Object,
    tabName: String,
    dimensionId: {
      type: Number,
      default: 0
    },
    siteId: {
      type: [Number, String],
      default: 0
    }
  },
  data () {
    return {
      submitLoading: false,
      catalogBasicInfo: { logoFile: '', extendModelData: {} } /** 基本信息 */,
      dataLoading: false /** 数据加载 */,
      resourceDialogProps: {},
      innerCode: '0',
      detailNameRules: [],
      codeType: 'DetailNameRule'
    }
  },
  watch: {
    tabName (val) {
      if (val === 'info') {
        this.loadCatalogBasicInfo()
      }
    },
    catalogId: function (val) {
      if (val && this.tabName === 'info') {
        this.loadCatalogBasicInfo()
      }
      if (val === 0) {
        this.$refs['catalog-basic-info'].resetFields()
      }
    }
  },
  created () {
    this.loadCatalogBasicInfo()
  },
  methods: {
    loadCatalogTree (val) {
      if (val === 'del') {
        this.$refs['catalog-basic-info'].resetFields()
      }
      this.$emit('loadCatalogTree', val)
    },
    async catalogImportCallBack (res) {
      let message = `正在导入到[${this.catalogBasicInfo.name}]栏目`
      if (!this.catalogBasicInfo.name) {
        message = '正在导入到文档库'
      }
      await util.showProgress(res.data.taskID, message)
      this.$emit('loadCatalogTree')
    },
    /** 清空栏目弹框回调 */
    async cleanCallBack (res) {
      await util.showProgress(res.data.taskID, `正在清空[${this.catalogBasicInfo.name}]栏目`)
    },
    async visible () {
      if (!this.catalogId) {
        return
      }
      if (this.catalogBasicInfo.visibleFlag === 'Y') {
        try {
          await this.$confirm('警告：您确认要禁用这个栏目吗？', '系统提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
          if (this.catalogBasicInfo.isLeaf === '0') {
            try {
              await this.$confirm('修改本栏目的状态，子栏目的状态也会被改变，确认要执行此操作吗？', '系统提示', {
                confirmButtonText: '确定',
                showCancelButton: false,
                type: 'warning'
              })
              await this.changeVisible()
            } catch (e) {
              return
            }
          } else {
            await this.changeVisible()
          }
        } catch (error) {}
      } else {
        await this.changeVisible()
      }
      this.loadCatalogBasicInfo()
    },
    async changeVisible () {
      let params = {
        catalogID: this.catalogId,
        visibleFlag: this.catalogBasicInfo.visibleFlag
      }
      let res = await axios.put(
        `/ui/catalogs/changevisible`,
        params
      )
      if (res.data.status === 1) {
        this.$emit('loadCatalogTree')
      }
      util.showResponseMessage(res.data)
    },
    /** 栏目合并成功后回调事件 */
    async mergeCallBack (taskID) {
      await util.showProgress(taskID, `正在合并到[${this.catalogBasicInfo.name}]栏目`)
      this.loadCatalogTree()
    },
    /** 撤销 */
    async catalogRollBackClickHandler () {
      try {
        await this.$confirm('确认撤销所有操作吗？', '撤销', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch (e) {
        return
      }
      try {
        let res = await axios.put('/ui/contentcore/siteoperation/rollback')
        util.showResponseMessage(res.data)
      } catch (e) {
        util.showErrorNotification(e)
      }
    },
    /** 生效 */
    async catalogTakeEffectClickHandler () {
      try {
        await this.$confirm('确认使所有操作生效吗？', '生效', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch (e) {
        return
      }
      try {
        let res = await axios.put('/ui/contentcore/siteoperation/takeeffect')
        util.showResponseMessage(res.data)
      } catch (e) {
        util.showErrorNotification(e)
      }
    },
    /** 发布栏目弹框回调 */
    async afterPublishCallBack (taskID) {
      await util.showProgress(taskID, `正在发布[${this.catalogBasicInfo.name}]栏目`, '发布成功')
    },
    /** 保存栏目基本信息 */
    async catalogSaveClickHandler () {
      if (!this.catalogBasicInfo.name || !this.catalogBasicInfo.alias || !this.catalogBasicInfo.path) {
        this.dialog('不能为空')
        return
      }
      this.catalogBasicInfo.name = this.catalogBasicInfo.name.replace('\t', '  ')
      this.catalogBasicInfo.name = this.catalogBasicInfo.name.replace('/\r\b\f/g', '')
      for (let key in this.catalogBasicInfo) {
        if (key.startsWith('metavalue_')) {
          if (typeof this.catalogBasicInfo[key] === 'object') {
            this.catalogBasicInfo[key] = this.catalogBasicInfo[key] ? this.catalogBasicInfo[key].join() : ''
          }
        }
      }

      if (this.oldType !== this.catalogBasicInfo.type) {
        try {
          await this.$confirm('修改栏目类型将清空栏目下的原有内容数据，确认修改？', '系统提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
          await this.saveCatalog()
        } catch (e) {

        }
      } else {
        if (this.contentType !== this.catalogBasicInfo.contentType) {
          try {
            await this.$confirm('修改栏目内容类型将清空栏目下的原有内容数据，确认修改？', '系统提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            })
            await this.saveCatalog()
          } catch (e) {

          }
        } else {
          await this.saveCatalog()
        }
      }
    },
    async saveCatalog () {
      this.submitLoading = true
      let res
      try {
        await util.validateForm(this.$refs['catalog-basic-info'])
        res = await axios.put(`/ui/catalogs/${this.catalogId}`, this.catalogBasicInfo)
      } catch (error) {
        util.showError(error.message)
        return
      } finally {
        this.submitLoading = false
      }
      util.showResponseMessage(res.data)
      if (res.data.status === 1) {
        if (this.type !== this.oldType) { // 栏目类型改变则向上层传递刷新栏目树
          let val = {
            ID: this.catalogBasicInfo.ID,
            contentType: this.catalogBasicInfo.contentType,
            parentID: this.catalogBasicInfo.parentID,
            type: this.catalogBasicInfo.type
          }
          this.$emit('loadCatalogTree', val)
        } else {
          this.$emit('loadCatalogTree')
        }
        this.loadCatalogBasicInfo()
      }
    },
    /** 修改当前栏目类型 */
    catalogTypeChangeHandler (val) {
      this.$emit('update:type', val)
    },
    turnToPlatformTabs (tabName) {
      this.$emit('update:tabName', tabName)
    },
    /** 加载栏目基本信息 */
    async loadCatalogBasicInfo () {
      if (this.catalogId === 0) {
        return
      }
      let codeData = await axios.get(`/ui/codes/${this.codeType}/items`)
      this.detailNameRules = codeData.data.data
      this.dataLoading = true
      let res = await axios.get(`/ui/catalogs/${this.catalogId}`)
      this.dataLoading = false
      this.catalogBasicInfo = res.data.data
      this.catalogBasicInfo.type = 'Default'
      this.resourceDialogProps = {
        dataType: 'CatalogLogo',
        dataID: this.catalogId,
        resourceType: 'image',
        imageType: 'logo',
        catalogID: this.catalogId,
        imageWidth: 120,
        imageHeight: 120,
        inputType: 'radio'
      }
      this.innerCode = this.catalogBasicInfo.innerCode
    },
    // 消息Dialog封装
    dialog (msg) {
      this.$confirm(msg, '系统提示', {
        confirmButtonText: '确定',
        showCancelButton: false,
        type: 'warning'
      })
    }
  }
}
