<template>
  <div class="layout-no-flex">
    <el-toolbar>
      <el-button @click="$router.back()" type="primary" size="medium" round class="shadow-primary"><i class="fa fa-chevron-left"></i> 返回上页</el-button>
      <span class="button-separator"></span>
      <el-button type="button" class="el-button el-button--default save" :loading="submitLoading" @click="confirmClickHandler"><span><i class="fa fa-save"></i>保存</span></el-button>
    </el-toolbar>
    <div>
      <div class="detail-panel">
        <div class="panel-header">
          <div class="title">{{catalogId=='new'?'新建栏目':'类似创建'}}</div>
        </div>
        <el-form :model="tmpCatalog" status-icon ref="form" label-width="250px" label-suffix="：" v-loading="formLoading" class="add-dim-form">
          <el-form-item label="上级栏目">
            <catalogTree-selector :items="items" :value.sync="tmpCatalog.parent.ID" style="width:auto;" @click-change="nodeChangedHandler"  placeholder="请选择上级栏目" ></catalogTree-selector>
          </el-form-item>
          <el-form-item label="栏目名称" prop="name" :verify="['NotNull','Length<30']">
            <el-input v-model="tmpCatalog.name" @blur="autoFillAliasAndPath"></el-input>
          </el-form-item>
          <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-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-form>
      </div>
    </div>
  </div>
</template>
<script>
import util from '@src/common/util.js'
import PathPicker from '../../contentcore/components/PathPicker.vue'
import TreeSelect from '@src/components/TreeSelect.vue'
export default {
  components: {
    'path-picker': PathPicker,
    'catalogTree-selector': TreeSelect
  },
  props: {
    dimensionId: {
      type: [Number, String],
      default: 0,
      required: true
    },
    catalogId: {
      type: [Number, String],
      default: 0,
      required: true
    }
  },
  data() {
    return {
      formLoading: false,
      submitLoading: false,
      tmpCatalog: {
        // 新建栏目对象
        parent: { ID: 0, name: '' }
      },
      items: [],
      parentPath: '',
      parentAlias: ''
    }
  },
  mounted() {
    this.loadAdvanceCatalogTree()
    this.beforeShowPage()
  },
  methods: {
    nodeChangedHandler(row) {
      if (this.catalogId !== 'new') {
        return
      }
      this.tmpCatalog.parent = {ID: row.ID, name: row.name}
      this.parentAlias = row.alias
      this.parentPath = row.path
    },
    async beforeShowPage() {
      if (this.catalogId === 'new') {
        this.tmpCatalog.parent = { ID: 0, name: '站点根目录' }
      } else {
        this.initSimilarCatalog()
      }
    },
    //  加载栏目树
    async loadAdvanceCatalogTree () {
      let res = await axios.get(`/ui/dimesion/${this.dimensionId}/catalog`)
      this.items = res.data.data
    },
    // 自动填充新建栏目的别名和路径
    async autoFillAliasAndPath() {
      if (this.catalogId !== 'new') {
        return
      }
      if (
        this.tmpCatalog.name &&
        (!this.tmpCatalog.alias || !this.tmpCatalog.path)
      ) {
        let path = this.parentPath
        if (!path) {
          path = '/'
        }
        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/dimesion/${this.dimensionId}/catalog/aliasanddir`,
            {
              params: opts
            }
          )
          this.formLoading = false

          if (res.data.status === 1) {
            if (!this.tmpCatalog.alias) {
              this.tmpCatalog.alias = res.data.data.alias
            }
            if (!this.tmpCatalog.path) {
              this.tmpCatalog.path = res.data.data.path
            }
          } else {
            util.showMessage(res)
          }
        } catch (e) {
          this.formLoading = false
          // util.showErrorNotification(e)
        }
      }
    },
    //  检查填写的字符串格式是否正确替换掉特殊字符,保留中文
    checkFormat() {
      let str = this.tmpCatalog.name
      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.$alert('请输入正确字符', '系统提示', {
          type: 'warning'
        })
        return false
      }
      this.tmpCatalog.name = str
      return true
    },
    // 提交新建栏目
    async confirmClickHandler() {
      if (!this.checkFormat()) {
        return
      }
      this.submitLoading = true
      try {
        await util.validateForm(this.$refs['form'])
        let res
        if (this.catalogId !== 'new') {
          res = await axios.post(
            `/ui/dimesion/${this.dimensionId}/catalog/similardimensionadd`,
            this.tmpCatalog
          )
        } else {
          res = await axios.post(
            `/ui/dimesion/${this.dimensionId}/catalog`,
            this.tmpCatalog
          )
        }
        this.submitLoading = false
        util.showMessage(res)
      } catch (e) {
        this.submitLoading = false
        util.showErrorMessageBox(e)
      }
    },
    // 初始化
    async initSimilarCatalog() {
      let res = await axios.get(
        `/ui/dimesion/${this.dimensionId}/catalog/similardimensionaddinit`,
        {
          params: { ID: this.catalogId }
        }
      )
      if (res.data.status === 1) {
        this.tmpCatalog = res.data.data
      }
    }
  }
}
</script>
<style>
.add-dim-form {
  margin-top: 20px;
}
.add-dim-form .el-form-item .el-input {
  width: 240px;
  margin-right: 5px;
}
</style>
