<template>
  <div>
        <el-form :model="tmpCatalog" status-icon ref="form" label-width="150px" label-suffix="：" v-loading="formLoading" class="add-catalog-form">
          <el-row>
            <el-form-item label="上级栏目" :verify="[hasPriv ? '' : 'NotNull']">
              <catalogTree-selector ref="cTreeSelect" :clearable="hasPriv" :items="catalogTree" @click-change="nodeChangedHandler" :value.sync="tmpCatalog.parent.ID" style="width:auto;"  placeholder="请选择上级栏目" ></catalogTree-selector>
              <el-tooltip placement="right" effect="dark">
                <div slot="content">上级栏目为空时默认为顶级栏目，若没有新建顶级栏目权限时上级栏目必选</div>
                <span><i class="fa fa-lightbulb-o" style="color:#FFC125; margin-left:5px"></i></span>
              </el-tooltip>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="继承上级栏目权限" v-if="tmpCatalog.parent.ID">
              <el-switch v-model="tmpCatalog.isExtendParentPriv" active-value="Y" inactive-value="N"></el-switch>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="栏目名称" prop="name" :verify="['NotNull','Length<30']">
              <el-input v-model="tmpCatalog.name" @blur="autoFillAliasAndPath" ></el-input>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="栏目别名" prop="alias" :verify="['NotNull','Regex=^[a-zA-Z0-9_\.\/-]+$|只能包含字母、数字、下划线、中划线、正斜杠、点','Length<100']">
              <el-input v-model="tmpCatalog.alias" ></el-input>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="所在目录" prop="path" :verify="['NotNull','Regex=^[a-zA-Z0-9_\.\/-]+$|只能包含字母、数字、下划线、中划线、正斜杠、点','Length<100']">
              <path-picker
              :path.sync="tmpCatalog.path"
              select-title="选择栏目路径"
              ></path-picker>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="栏目类型" prop="type" :verify="['NotNull']">
              <el-select v-model="tmpCatalog.type" clearable placeholder="请选择" >
                <el-option
                  v-for="item in types"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="内容类型">
              <el-select v-model="tmpCatalog.contentType" clearable placeholder="请选择">
                <el-option
                  v-for="item in contenttypes"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="栏目URL" v-if="tmpCatalog.type==='Link'">
              <div>
                <el-input v-model="tmpCatalog.cName"  :disabled="true"></el-input><br>
                <el-button @click="selectContentClickHandler" type="small">链接到内容</el-button>
                <el-button @click="selectCatalogClickHandler" type="small">链接到栏目</el-button>
                <el-button @click="inputUrlClickHandler" type="small">外部地址</el-button>
              </div>
            </el-form-item>
          </el-row>
        </el-form>
    <!-- 链接到内容弹框 -->
    <content-selector :title="linkContentChoice.title" :show.sync="linkContentChoice.isShowModal" @callback="getChoiceLinkContent"></content-selector>
    <!-- 链接到栏目弹框 -->
    <link-catalog
      :show.sync="linkCatalogChoice.isShowModal"
      :title="linkCatalogChoice.title"
      :catalog-id="linkCatalogChoice.ID"
      :input-type="linkCatalogChoice.inputType"
      @callback="getChoiceLinkCatalog">
    </link-catalog>
    <!-- 外部地址 -->
    <input-link
      :show.sync="linkURL.isShowModal"
      @callback="getInputURL">
    </input-link>
  </div>
</template>
<script>
import util from '@src/common/util.js'
import PathPicker from './PathPicker.vue'
import CatalogSelector from './CatalogSelector.vue'
import ContentSelector from '@src/components/contentComponent/ContentSelector.vue'
import InputExternalLink from './inputExternalLink.vue'
import TreeSelect from '@src/components/TreeSelect.vue'
import Privilege from '@src/common/privilege.js'
export default {
  components: {
    'path-picker': PathPicker,
    'content-selector': ContentSelector,
    'link-catalog': CatalogSelector,
    'input-link': InputExternalLink,
    'catalogTree-selector': TreeSelect
  },
  props: {
    catalogId: {
      type: [String, Number],
      required: true
    },
    dimensionId: {
      type: Number,
      default: 0
    },
    parentCatalog: {
      type: Object
    }
  },
  data() {
    return {
      hasPriv: false,
      formLoading: false,
      submitLoading: false,
      tmpCatalog: {
        // 新建顶级栏目对象
        type: 'Default',
        isExtendParentPriv: 'N',
        extendFlag: 'Y',
        parent: { ID: 0, name: '' },
        contentType: '',
        dimensionID: this.dimensionId,
        name: '',
        path: '',
        alias: '',
        siteID: this.$root.siteID
      },
      linkContentChoice: {
        // 选择链接文章子组件
        isShowModal: false,
        title: ''
      },
      linkURL: { isShowModal: false }, //  外部地址
      linkCatalogChoice: {
        // 选择链接栏目子组件
        isShowModal: false,
        title: '',
        ID: '',
        inputType: ''
      },
      types: [], //  栏目类型
      contenttypes: [], //  内容类型
      catalogTree: [], // 栏目树
      parentPath: '',
      parentAlias: ''
    }
  },
  watch: {
    catalogId: function(val) {
      if (val) {
        this.init()
      }
    },
    parentCatalog: {
      handler(newValue, oldValue) {
        this.nodeChangedHandler(newValue)
      },
      deep: true
    },
    dimensionId: function(val) {
      if (val) {
        this.init()
      }
    }
  },
  created() {
    if (this.tmpCatalog.parent.name === '根栏目') {
      this.tmpCatalog.parent.ID = 0
      this.tmpCatalog.parent.name = ''
      this.tmpCatalog.dimensionID = this.dimensionId
      this.tmpCatalog.isExtendParentPriv = 'N'
    }
  },
  methods: {
    init() {
      this.loadCatalogType()
      this.loadContentType()
      this.bindEditorTree()
      this.beforeShowPage()
      this.nodeChangedHandler(this.parentCatalog)
      this.hasPriv = Privilege.hasPriv(`com.zving.cms.Site.AddTopLevelCatalog.${window.app.siteID}`)
    },
    async bindEditorTree() {
      let res = await axios.get(`/ui/dimensions/${this.dimensionId}/catalogstree`, {params: {treeLevel: 9999}})
      let data = res.data.data.filter(cat => {
        if (cat.parentID === 0 && cat.name === '根栏目') {
          return false
        } else {
          return true
        }
      })
      this.catalogTree = data
    },
    nodeChangedHandler(row) {
      if (!row) {
        this.tmpCatalog.parent = {}
        this.parentAlias = ''
        this.parentPath = ''
        return
      }
      this.tmpCatalog.name = ''
      this.tmpCatalog.alias = ''
      this.tmpCatalog.path = ''
      // this.tmpCatalog.isExtendParentPriv = 'Y'
      this.$set(this.tmpCatalog, 'isExtendParentPriv', 'Y') // 需通过this.$set才能设置为响应式属性 暂时没找到原因
      if (row.type) {
        this.tmpCatalog.type = row.type
      }
      if (row.contentType === 'null') {
        this.tmpCatalog.contentType = ''
      } else {
        this.tmpCatalog.contentType = row.contentType
      }
      this.tmpCatalog.parent = {ID: row.ID, name: row.name}
      this.parentAlias = row.alias
      this.parentPath = row.path
    },
    beforeShowPage() {
      if (this.catalogId === 'new') {
        this.tmpCatalog.type = 'Default'
        this.tmpCatalog.contentType = ''
        this.tmpCatalog.parent = { ID: 0, name: '站点根目录' }
        this.tmpCatalog.dimensionID = this.dimensionId
      } else {
        this.initSimilarCatalog()
      }
    },
    // 初始化
    async initSimilarCatalog() {
      let res = await axios.get('/ui/catalogs/similaraddinit', {
        params: { catalogID: this.catalogId }
      })
      if (res.data.status === 1) {
        let tempCatalog = res.data.data
        if (tempCatalog.parent.ID) {
          tempCatalog.isExtendParentPriv = 'Y'
        }
        this.tmpCatalog = tempCatalog
      }
    },
    // 自动填充新建栏目的别名和路径
    async autoFillAliasAndPath() {
      // 暂时去除 类似新建也要自动填充新建栏目的别名和路径
      // if (this.catalogId !== 'new') {
      //   return
      // }
      if (
        this.tmpCatalog.name &&
        (!this.tmpCatalog.alias || !this.tmpCatalog.path)
      ) {
        let path = this.parentPath
        if (!path) {
          path = ''
        } else if (!path.endsWith('/')) {
          path += '/'
        }
        let opts = {
          pPath: path,
          catalogName: encodeURIComponent(this.tmpCatalog.name),
          alias: this.tmpCatalog.alias,
          pAlias: this.parentAlias
        }
        this.formLoading = true
        try {
          let res = await axios.get('/ui/catalogs/aliasanddir', {
            params: opts
          })
          this.formLoading = false

          if (res.data.status === 1) {
            if (!this.tmpCatalog.alias) {
              this.tmpCatalog.alias = res.data.alias
            }
            if (!this.tmpCatalog.path) {
              this.tmpCatalog.path = res.data.path
            }
          } else {
            util.showMessage(res)
          }
        } catch (e) {
          this.formLoading = false
          // util.showErrorNotification(e)
        }
      }
    },
    //  检查填写的字符串格式是否正确替换掉特殊字符,保留中文
    checkFormat() {
      let str = this.tmpCatalog.name
      if (!str) {
        return false
      }
      str = str.replace('\t', '  ')
      str = str.replace(/\r\b\f/g, '')
      //  str = str.replace(/[^a-zA-Z0-9_.-/\s\n\u4e00-\u9fa5]/g '')
      if (!str) {
        this.dialog('请输入正确字符')
        return false
      }
      this.tmpCatalog.name = str
      return true
    },
    // 提交新建栏目
    async confirmClickHandler() {
      this.tmpCatalog.dimensionID = this.dimensionId
      let flag = await this.checkFormat()
      if (!flag) {
        util.showErrorMessageBox('请输入正确的栏目名称')
        return false
      }
      this.submitLoading = true
      try {
        await util.validateForm(this.$refs['form'])
      } catch (e) {
        this.submitLoading = false
        util.showErrorMessageBox(e)
        return false
      }
      if (this.tmpCatalog.parent.name === '根栏目') {
        this.tmpCatalog.parent.ID = 0
        this.tmpCatalog.parent.name = ''
        this.tmpCatalog.dimensionID = this.dimensionId
        this.tmpCatalog.isExtendParentPriv = 'N'
      }
      this.tmpCatalog.parentID = this.tmpCatalog.parent.ID
      try {
        let res
        if (this.catalogId === 'new') {
          res = await axios.post('/ui/catalogs', this.tmpCatalog)
        } else {
          res = await axios.post(`/ui/catalogs/${this.catalogId}`, this.tmpCatalog)
        }
        await this.$nextTick()
        await util.updatePriv()
        this.$refs.form.resetFields()
        this.$emit('callback', res.data.catalog)
        this.submitLoading = false
        if (res.data.status === 0) {
          util.showErrorMessageBox(res.data.message)
          return false
        }
        util.showResponseMessage(res.data)
      } catch (e) {
        this.submitLoading = false
        // util.showErrorNotification(e)
        return false
      }
      return true
    },
    //  链接到栏目内容
    selectContentClickHandler() {
      this.linkContentChoice.isShowModal = true
      this.linkContentChoice.title = '选择内容记录'
    },
    // 得到栏目内容
    getChoiceLinkContent(data) {
      this.tmpCatalog.cName = data.title
      this.tmpCatalog.URL = data.link
    },
    // 链接到栏目
    selectCatalogClickHandler() {
      this.linkCatalogChoice.isShowModal = true
      this.linkCatalogChoice.title = '选择栏目'
      this.linkCatalogChoice.ID = 0
      this.linkCatalogChoice.inputType = 'radio'
    },
    // 得到栏目
    getChoiceLinkCatalog(data) {
      this.tmpCatalog.cName = `栏目：${data.name}`
      this.tmpCatalog.URL = data.link
    },
    // 外部地址
    inputUrlClickHandler() {
      this.linkURL.isShowModal = true
    },
    // 外部地址弹框回调
    getInputURL(URL) {
      this.tmpCatalog.URL = URL
      this.tmpCatalog.cName = URL
    },
    // 消息Dialog封装
    dialog(msg) {
      this.$confirm(msg, '系统提示', {
        confirmButtonText: '确定',
        showCancelButton: false,
        type: 'warning'
      })
    },
    // 加载栏目类型
    async loadContentType() {
      let res = await axios.get('/ui/catalogs/contenttypes', {
        params: { parentID: this.parentID }
      })
      this.contenttypes = res.data.data
    },
    // 加载栏目类型
    async loadCatalogType() {
      let res = await axios.get('/ui/catalogs/catalogtypes')
      this.types = res.data.data
    }
  }
}
</script>
<style>
.add-catalog-form {
  margin-top: 20px;
}
.add-catalog-form .el-form-item .el-input {
  width: 240px;
  margin-right: 5px;
}
</style>
