<template>
  <div class="resourceCatalog">
    <bread-crumb :bread-crumb-list="breadCrumbList"></bread-crumb>
    <div class="con">
      <el-tree
        ref="radioTreeRef"
        v-loading.body="treeLoading"
        class="radioTree"
        :data="treeData" 
        :props="defaultProps" 
        :highlight-current="true"
        :current-node-key='currentNodeKey'
        :default-expanded-keys='expandedKeys'
        node-key="id"
        accordion
        @node-click="radioTreeClick">
      </el-tree>
      <div class="conIn">
        <div class="buttonList">
          <el-button type="info" icon="plus"  @click="newlyBuild">新建</el-button>
          <el-button icon="edit" @click="handleEdit" :disabled="currentNodeData.directoryid === ''">编辑</el-button>
          <el-button type="danger" icon="delete2" @click="handleDelete" :disabled="disableDelete">删除</el-button>
        </div>

        <div class="catalogCon">
          <el-form :model="dataForm" :rules="rules" ref="moduleForm">
            <el-form-item label="目录名称" prop="nameCn">
              <el-input v-model="dataForm.nameCn" :disabled="readlyOnoff"></el-input>
            </el-form-item>
            <el-form-item label="目录英文名" prop="nameEn">
              <el-input v-model="dataForm.nameEn" :disabled="readlyOnoff"></el-input>
            </el-form-item>
            <el-form-item label="数值排序" prop="sort">
              <el-select v-model="dataForm.sort" placeholder="请选择数值排序" :disabled="readlyOnoff">
                <el-option
                  v-for="item in dataForm.options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>

          <div class="buttonList2" v-if="!readlyOnoff">
            <el-button @click="handleCancel">取消</el-button>
            <el-button type="primary" @click="saveCatalog('moduleForm')">确定</el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 删除 -->
    <el-dialog
      title="信息"
      :visible.sync="deleteDialogVisible"
      v-if="deleteDialogVisible"
      v-loading.body="dialogLoading"
      element-loading-text="拼命加载中"
      width="400px">
      <span>是否删除所选目录节点</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sureDeleteCatalog">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import BreadCrumb from '@/components/BreadCrumb.vue'

  import Api from '@/api/index.js'

  export default { 
    components: {
      BreadCrumb
    },
    data () { 
      return {
        dataForm: {
          nameCn: '',
          nameEn: '',
          sort: '',
          options: [{
            value: '1',
            label: '1'
          }, {
            value: '2',
            label: '2'
          }, {
            value: '3',
            label: '3'
          }, {
            value: '4',
            label: '4'
          }, {
            value: '5',
            label: '5'
          }, {
            value: '6',
            label: '6'
          }, {
            value: '7',
            label: '7'
          }, {
            value: '8',
            label: '8'
          }, {
            value: '9',
            label: '9'
          }]
        }, 
        defaultProps: {
          children: 'childDirectoryinfos',
          label: 'nameCn'
        },
        id: '',
        treeData: [{ 
          id: '0',
          directoryid: '',
          parentid: '',
          nameEn: 'catalog',
          nameCn: '目录',
          sort: '0',
          childDirectoryinfos: []
        }],
        currentNodeKey: '',
        expandedKeys: [''],
        treeLoading: false,
        currentNodeData: [],

        readlyOnoff: true,

        dialogLoading: false,
        breadCrumbList: [],
        
        rules: {
          nameCn: [
            {required: true, message: '请输入目录名称', trigger: 'blur'},
            {validator: (rule, value, callback) => {
                if (value.length > 10 || value.length < 2) {
                  callback(new Error('长度必须为2~10个字符'))
                } else {
                  var reg = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>《》/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？]")
                  if (reg.test(value)) {
                    callback(new Error('不能含有特殊字符'))
                  } else {
                    callback()
                  }
                }
              },
              trigger: 'blur'
            }
          ],
          nameEn: [
            {required: true, message: '请输入目录英文名称', trigger: 'blur'},
            {validator: (rule, value, callback) => {
                if (value.length > 30 || value.length < 3) {
                  callback(new Error('长度必须为3~30个字符'))
                } else {
                  var reg = new RegExp('[^\a-\z\A-\Z0-9_]')
                  if (reg.test(value)) {
                    callback(new Error('只能填英文数字和下划线'))
                  } else {
                    callback()
                  }
                }
              },
              trigger: 'blur'
            }
          ],
          sort: [
            {required: true, message: '请选择数值排序', trigger: 'blur'}
          ]
        },
        
        deleteDialogVisible: false,
        newEditOnoff: true,
        disableDelete: true
      }
    },
    watch: {
      $route (newVal) {
        // this.init()
      }
    },
    mounted () { 
      this.init()
    },
    methods: { 
      init () { 
        this.treeLoading = true
        // 初始化目录树
        Api.getCatalogTree()
        .then(data => {
          this.treeLoading = false
          if (data.status === 0) { 
            this.treeData[0].childDirectoryinfos = data.data

            this.dataForm.nameCn = this.treeData[0].nameCn // 目录名
            this.dataForm.nameEn = this.treeData[0].nameEn // 英文名
            this.dataForm.sort = this.treeData[0].sort // 权重

            this.currentNodeData = this.treeData[0]

            this.$nextTick(() => {
              this.$refs.radioTreeRef.setCurrentKey('0')
            })
            this.currentNodeKey = ''
            this.expandedKeys = ['0']
          } else { 
            this.$message({
              type: 'warning',
              message: '获取目录树失败'
            })
          }
        }).catch(res => {
          this.treeLoading = false
          this.$message({
            type: 'error',
            message: '请求数据失败'
          })
        })
        // 初始化面包屑
        this.breadCrumbList = [
          {title: '服务管理'},
          {title: '资源目录管理'},
          {title: '目录'}
        ]
      },
      // 目录树
      getCatalogTree () {
        this.treeLoading = true
        // 初始化目录树
        Api.getCatalogTree()
        .then(data => {
          this.treeLoading = false
          if (data.status === 0) { 
            this.treeData[0].childDirectoryinfos = data.data

            if (!this.newEditOnoff) { // 编辑
              this.currentNodeData.text = this.dataForm.nameCn 
              this.currentNodeData.entext = this.dataForm.nameEn 
              this.currentNodeData.orderId = this.dataForm.sort
            } else { // 新建
              this.dataForm.nameCn = this.currentNodeData.nameCn // 目录名
              this.dataForm.nameEn = this.currentNodeData.nameEn // 英文名
              this.dataForm.sort = this.currentNodeData.sort // 权重
            }
            this.$nextTick(() => {
              this.$refs.radioTreeRef.setCurrentKey(this.currentNodeKey)
            })
          } else { 
            this.$message({
              type: 'warning',
              message: '获取目录树失败'
            })
          }
        }).catch(res => {
          this.treeLoading = false
          this.$message({
            type: 'error',
            message: '请求数据失败'
          })
        })
      },
      // 新建
      newlyBuild () {
        this.readlyOnoff = false
        this.newEditOnoff = true

        this.dataForm.nameCn = ''
        this.dataForm.nameEn = ''
        this.dataForm.sort = ''
      },
      // 编辑
      handleEdit () {
        this.readlyOnoff = false
        this.newEditOnoff = false

        this.dataForm.nameCn = this.currentNodeData.nameCn // 目录名
        this.dataForm.nameEn = this.currentNodeData.nameEn // 英文名
        this.dataForm.sort = this.currentNodeData.sort // 权重
      },
      // 删除
      handleDelete () {
        this.deleteDialogVisible = true
      },
      // 取消
      handleCancel () {
        this.$refs['moduleForm'].resetFields()
        this.readlyOnoff = true

        this.dataForm.nameCn = this.currentNodeData.nameCn
        this.dataForm.nameEn = this.currentNodeData.nameEn
        this.dataForm.sort = this.currentNodeData.sort
      },
      // 保存新建或编辑
      saveCatalog (moduleForm) {
        this.dialogLoading = true
        var formData = new FormData()         
            formData.append('nameCn', this.dataForm.nameCn)
            formData.append('nameEn', this.dataForm.nameEn)
            formData.append('sort', this.dataForm.sort)
        this.$refs[moduleForm].validate((valid) => {
          if (valid) { // 填好信息
            if (this.newEditOnoff) { // 新建
              formData.append('parentid', this.currentNodeData.directoryid || '')   
              Api.saveCatalogService(formData)
              .then(data => {
                this.dialogLoading = false
                // this.dialogNew = false
                if (data.status === 0) {
                  this.readlyOnoff = true
                  this.getCatalogTree()
                  this.$message({
                    type: 'success',
                    message: '新建成功'
                  })
                } else {
                  this.$message({
                    type: 'warning',
                    message: '新建失败'
                  })
                }
              }).catch(res => {
                this.$message({
                  type: 'error',
                  message: '请求数据失败'
                })
              })
            } else { // 编辑
              formData.append('directoryid', this.currentNodeData.directoryid || '') 
              Api.editCatalog(formData)
              .then(data => {
                this.dialogLoading = false
                // this.dialogNew = false
                if (data.status === 0) {
                  this.readlyOnoff = true
                  this.getCatalogTree()
                  this.$message({
                    type: 'success',
                    message: '编辑成功'
                  })
                } else { 
                  this.$message({
                    type: 'warning',
                    message: '编辑失败'
                  })
                }
              }).catch(res => {
                this.$message({
                  type: 'error',
                  message: '请求数据失败'
                })
              })
            }
          } else {
            return false
          }
        })
      },
      // 选择树节点
      radioTreeClick (val) {
        this.readlyOnoff = true
        this.$refs['moduleForm'].resetFields()
        this.currentNodeData = val
        this.currentNodeKey = val.id
        this.expandedKeys = []
        this.expandedKeys.push(val.id)

        if (val.childDirectoryinfos.length === 0) { 
          this.disableDelete = false
        } else { 
          this.disableDelete = true
        }
        // 修改表格内容
        this.dataForm.nameCn = val.nameCn // 目录名
        this.dataForm.nameEn = val.nameEn // 英文名
        this.dataForm.sort = val.sort // 权重
        this.breadCrumbList[this.breadCrumbList.length - 1].title = val.nameCn
      },
      // 确定删除
      sureDeleteCatalog () {
        this.dialogLoading = true
        Api.deleteCatalog(this.currentNodeData.directoryid)
          .then(data => {
            this.dialogLoading = false
            this.deleteDialogVisible = false
            if (data.status === 0) { 
              this.$message({
                type: 'success',
                message: '删除目录节点成功'
              })
              this.init()
            } else { 
              this.$message({
                type: 'warning',
                message: '删除目录节点失败'
              })
            }
          }).catch(res => {
            this.$message({
              type: 'error',
              message: '请求数据失败'
            })
          })
      } 
    }
  }
</script>

<style lang="scss">
  $topicColor: rgba(8, 139, 134, 1);

  .resourceCatalog{ 
    width: 100%;
    position: relative;
    display: flex;
    flex-direction: column;
    
    .con{ 
      width: 100%;
      height: 100%;
      position: relative;

      .radioTree{ 
        width: 230px;
        height: 100%;
        padding-bottom: 46px;
        box-sizing: border-box;
        overflow-y: auto;
        background: #fbfbfb;
        box-shadow: 1px 2px 8px rgba(32, 34, 42, .2);
        position: absolute;
        left: 0;
        top: 0;
      }

      .conIn{ 
        width: 100%;
        padding-left: 230px;
      }

      .catalogCon {
        display: inline-block;
        padding: 30px 30px 20px 20px;
        margin-left: 20px;
        background: #f7f8fa;
        border: solid 1px #d5d6da;
        border-radius: 4px;
      }

      .el-form-item__content{
        display: inline-block;
      }

      .el-form-item__label{
        width: 100px;
      }
      .el-input {
        min-width: 500px;
      }
  
      .buttonList{ 
        padding: 20px 0 20px 20px;
        // margin-bottom: 20px;
        display: flex;

        .save{ 
          margin-left: 230px;
        }
      }

      .buttonList2{
        width: 100%;
        padding-top: 20px;
        text-align: center;  
      }
      
      /* tr{ 
        height: 40px;
        text-align: center;
      }
      .readIpt{ 
        width: 100%;
        height:30px;
        display: block;
        margin: auto; 
        text-align: center;
        border: none;
        outline: none;
        text-align: center;
      }
      
      .mapDetailTable{ 
        width: 100%;
        border-color: #d5d4d9;
      } */
    }
    .addParts{ 
      .el-dialog--small{ 
        width: 40%;
      } 
      .el-dialog__header{ 
        padding: 20px 20px 0 20px;
        text-align: center;
        .el-dialog__title{ 
          color: #666;
        }
      }
      .el-dialog__body{ 
        padding: 20px 40px 10px 15px;
      }
      .el-form-item__label{ 
        width: 120px;
      }
      .el-form-item__content{ 
        display: flex;
      }
      .el-form-item{ 
        margin-bottom: 18px;
      }
      .dialog-footer{ 
        text-align: center;
        
      }
    }
  }
</style>
