<template>
  <div class="systemManagement branchMana" 
    v-loading.body="dialogLoading"
    element-loading-text="拼命加载中">
    <bread-crumb :bread-crumb-list="breadCrumbList"></bread-crumb>
    <div class="con" v-loading.body="loading">
      <el-tree
        ref="radioTreeRef"
        class="radioTree"
        :data="treeData" 
        :props="defaultProps" 
        :expand-on-click-node="true" 
        :highlight-current="true"
        :default-expanded-keys='expandedKeys'
        node-key="moduleguid"
        accordion
        @node-click="radioTreeClick">
      </el-tree>
      <div class="conIn">
        <div class="buttonList">
          <el-button type="info" icon="plus"  @click="newSystem">新建</el-button>
          <el-button icon="edit" @click="editSystem" :disabled="nodeId === ''">编辑</el-button>
          <el-button type="danger" @click="deleteModule" :disabled="deleteOnoff">删除</el-button>
        </div>
        
        <div class="catalogCon">
          <el-form :model="moduleForm" :rules="rules" ref="moduleForm">
            <el-form-item label="模块名称" prop="name">
              <el-input v-model="moduleForm.name" :disabled="readlyOnoff"></el-input>
            </el-form-item>
            <el-form-item label="模块地址" prop="address">
              <el-input v-model="moduleForm.address" :disabled="readlyOnoff"></el-input>
            </el-form-item>
            <el-form-item label="模块权重" prop="weighting" class="otherForm">
              <el-select v-model="moduleForm.weighting" placeholder="请选择数值排序" :disabled="readlyOnoff">
                <el-option
                  v-for="item in moduleForm.options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="代表图标" class="otherForm">
              <el-input v-model="moduleForm.moduleImageUrl" :disabled="readlyOnoff"></el-input>
            </el-form-item>
            <el-form-item label="模块描述">
              <el-input v-model="moduleForm.desc" :disabled="readlyOnoff"></el-input>
            </el-form-item>
            <el-form-item label="配置地址">
              <el-input v-model="moduleForm.configuration" :disabled="readlyOnoff"></el-input>
            </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="信息"
      v-if="deleteDialogVisible"
      :visible.sync="deleteDialogVisible"
      top="10%"
      width="400px">
      <span>是否删除所选中的模块</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="sureDeleteRole">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

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

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

export default { 
  name: 'SystemManagement',
  components: { 
    BreadCrumb
  },
  data () { 
    return {
      dialogLoading: false,
      loading: false,

      treeData: [{ 
        id: '0',
        moduleguid: '',
        parentguid: '',
        modulename: '菜单目录',
        moduleimageurl: '&#xe601;',
        pageurl: '',
        priority: '1',
        bstate: '',
        classid: '',
        config: '',
        modulecode: '',
        moduledescription: '',
        childModuleinfos: []
      }],
      defaultProps: {
        children: 'childModuleinfos',
        label: 'modulename'
      },
      id: '',
      nodeId: '',
      expandedKeys: [],
      breadCrumbList: [],
      moduleForm: {
        name: '',
        address: '',
        weighting: '',
        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'
        }, {
          value: '10',
          label: '10'
        }],
        desc: '',
        moduleImageUrl: '',
        configuration: ''
      },
      rules: {
        name: [
          {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'
          }
        ],
        address: [
          { required: true, message: '请输入模块地址', trigger: 'blur' }
        ],
        weighting: [
          {required: true, message: '请输入模块权重', trigger: 'blur'}
        ]
      },
      deleteOnoff: false,
      readlyOnoff: true,
      newEditOnoff: true,
      formData: {},
      deleteDialogVisible: false
    }
  },
  /* watch: {
    $route (newVal) {
      this.init()
    }
  }, */
  mounted () {
    this.init()
  },
  methods: { 
    init () { 
      // 初始化面包屑
      this.breadCrumbList = [
        { title: '系统安全' },
        { title: '系统模块管理' },
        { title: '服务监测' }
      ]
      // this.getTree()
      this.loading = true
      let yObj = localStorage.getItem('gisopUserInfo')
      if (yObj !== null) {
        let yId = JSON.parse(yObj).info.userguid.trim()
        Api.getAllCatalog(yId, 0).then(data => {
          this.loading = false
          let datas = data.data
          if (data.status === 0) {
            this.treeData[0].childModuleinfos = datas
            this.formData = datas[0]

            this.expandedKeys = []

            this.nodeId = datas[0].moduleguid
            this.expandedKeys.push(datas[0].moduleguid)

            this.$nextTick(() => {
              this.$refs.radioTreeRef.setCurrentKey(datas[0].moduleguid)
            })

            this.moduleForm.name = datas[0].modulename
            this.moduleForm.desc = datas[0].moduledescription
            this.moduleForm.address = datas[0].pageurl
            this.moduleForm.moduleImageUrl = datas[0].moduleimageurl
            this.moduleForm.weighting = datas[0].priority
            this.moduleForm.configuration = datas[0].config

            this.deleteOnoff = true
          } else {
            this.$message({
              type: 'error',
              message: '请求失败'
            })
          }
        }).catch(res => { 
          this.loading = false
          this.$message({
            type: 'error',
            message: '获取数据失败'
          })
        })
      }
    },
    // 目录树
    getTree () { 
      this.loading = true
      let yObj = localStorage.getItem('gisopUserInfo')
      if (yObj !== null) {
        let yId = JSON.parse(yObj).info.userguid.trim()
        Api.getAllCatalog(yId, 0).then(data => {
          this.loading = false
          let datas = data.data
          if (data.status === 0) {
            if (datas !== null) {
              this.treeData[0].childModuleinfos = datas
              this.expandedKeys = []
              this.expandedKeys.push(this.nodeId)
              this.$nextTick(() => {
                this.$refs.radioTreeRef.setCurrentKey(this.nodeId)
              })
            } 
          } else { 
            this.$message({
              type: 'error',
              message: '获取数据失败'
            })
          }
        }).catch(res => { 
          this.loading = false
          this.$message({
            type: 'error',
            message: '获取数据失败'
          })
        })
      }
    },
    // 关闭弹窗
    closeDialog (attr) { 
      this[attr] = false
    },
    // 选择树节点
    radioTreeClick (val) {
      this.readlyOnoff = true
      this.$refs['moduleForm'].resetFields()
      this.formData = val
      this.nodeId = val.moduleguid
      // 修改表格内容
      this.moduleForm.name = val.modulename
      this.moduleForm.desc = val.moduledescription
      this.moduleForm.address = val.pageurl
      this.moduleForm.moduleImageUrl = val.moduleimageurl
      this.moduleForm.weighting = val.priority
      this.moduleForm.configuration = val.config

      this.breadCrumbList[this.breadCrumbList.length - 1].title = val.modulename

      if (val.moduleguid === '10041001' || val.moduleguid === '10041002' || val.moduleguid === '10041003' || val.childModuleinfos !== null) { // 系统安全里面的所有模块以及父级都不能删除
        this.deleteOnoff = true
      } else { 
        this.deleteOnoff = false
      }
    },
    // 新建
    newSystem () { 
      this.readlyOnoff = false
      this.newEditOnoff = true

      this.moduleForm.name = ''
      this.moduleForm.desc = ''
      this.moduleForm.address = ''
      this.moduleForm.moduleImageUrl = ''
      this.moduleForm.weighting = ''
      this.moduleForm.configuration = ''
    },
    // 编辑
    editSystem () {
      this.readlyOnoff = false
      this.newEditOnoff = false

        Api.showModuleData(this.nodeId).then(data => {
          let datas = data.data
        if (data.status === 0) {
          this.moduleForm.name = datas.modulename
          this.moduleForm.desc = datas.moduledescription || ''
          this.moduleForm.address = datas.pageurl
          this.moduleForm.moduleImageUrl = datas.moduleimageurl || ''
          this.moduleForm.weighting = datas.priority || ''
          this.moduleForm.configuration = datas.config || ''
        } else {
          this.$message({
            type: 'warning',
            message: '请求数据失败'
          })
        }
      }).catch(res => { 
        this.$message({
          type: 'error',
          message: '请求数据失败'
        })
      })
    },
    // 取消
    handleCancel () {
      this.$refs['moduleForm'].resetFields()
      this.readlyOnoff = true

      this.moduleForm.name = this.formData.modulename
      this.moduleForm.desc = this.formData.moduledescription
      this.moduleForm.address = this.formData.pageurl
      this.moduleForm.moduleImageUrl = this.formData.moduleimageurl
      this.moduleForm.weighting = this.formData.priority
      this.moduleForm.configuration = this.formData.config
    },
    // 保存新建
    saveCatalog (ruleForm) {
      this.$refs[ruleForm].validate((valid) => {
        if (valid) {
          // this.dialogLoading = true

          if (this.newEditOnoff) { 
            let formData = new FormData()

            formData.append('modulename', this.moduleForm.name)
            formData.append('moduledescription', this.moduleForm.desc)
            formData.append('pageurl', this.moduleForm.address)
            formData.append('moduleimageurl', this.moduleForm.moduleImageUrl)
            formData.append('priority', this.moduleForm.weighting)
            formData.append('config', this.moduleForm.configuration)
            formData.append('parentguid', this.formData.moduleguid || '')

            Api.saveMoudle(formData)
            .then(data => {
              // this.dialogLoading = false
              // this.dialogNew = false
              if (data.status === 0) {
                this.readlyOnoff = true 
                this.$message({ 
                  type: 'success',
                  message: '新建成功'
                })
                this.getTree()
              } else {
                this.$message({ 
                  type: 'warning',
                  message: '新建失败'
                })
              }
            }).catch(res => { 
              this.$message({
                type: 'error',
                message: '请求数据失败'
              })
            })
          } else { 
            let formData = new FormData()

            formData.append('modulename', this.moduleForm.name)
            formData.append('moduledescription', this.moduleForm.desc)
            formData.append('pageurl', this.moduleForm.address)
            formData.append('moduleimageurl', this.moduleForm.moduleImageUrl)
            formData.append('priority', this.moduleForm.weighting)
            formData.append('config', this.moduleForm.configuration)
            formData.append('moduleguid', this.formData.moduleguid)
            
            Api.updateMoudle(formData)
            .then(data => {
              // this.dialogLoading = false
              // this.dialogNew = false
              if (data.status === 0) { 
                this.readlyOnoff = true 
                this.$message({ 
                  type: 'success',
                  message: '编辑成功'
                })
                this.getTree()
              } else {
                this.$message({ 
                  type: 'warning',
                  message: '编辑失败'
                })
              }
            }).catch(res => { 
              this.$message({
                type: 'error',
                message: '请求数据失败'
              })
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 删除
    deleteModule () { 
      this.deleteDialogVisible = true
    },
    // 确定删除
    sureDeleteRole () { 
      Api.checkDeleteMoudle(this.nodeId)
        .then(data => { 
          if (data.status === 0) {
            this.$message({
              type: 'success',
              message: '删除成功'
            })
            this.init()
          } else {
            this.$message({
              type: 'warning',
              message: '删除失败'
            })
          }
        })
        .catch(res => {
          this.$message({
            type: 'error',
            message: '申请失败'
          })
        })
      this.deleteDialogVisible = false
    }
  }
}
</script>

<style lang="scss">
  .conIn::-webkit-scrollbar { width: 0 !important }
  .systemManagement{ 
    display: flex;
    flex-direction: column;
    flex: 1;
    
    .con{
      flex: 1;
      display: flex;
      flex-direction: row;

      .radioTree{ 
        width: 230px;
        box-sizing: border-box;
        background: #fafdfd;
        box-shadow: 1px 2px 8px rgba(32, 34, 42, .2);
        // -ms-overflow-style: none;
        // overflow: -moz-scrollbars-none;
        .el-tree-node {
          width: 230px;
        }
      }

      .conIn{ 
        width: 100%;
        // padding: 0 20px 0 250px;
        overflow: auto;
      }
      .catalogCon {
        display: inline-block;
        padding: 30px 30px 0 20px;
        margin-left: 20px;
        background: #f7f8fa;
        border: solid 1px #d5d6da;
        border-radius: 4px;
        margin-bottom: 20px;
      }
      .el-form-item__content{
        display: inline-block;
      }

      .el-form-item__label{
        width: 100px;
      }
      .el-input {
        min-width: 500px;
      }

      .otherForm {
        .el-input {
          min-width: 300px;
        }
      }
  
      .buttonList{ 
        padding: 20px 0 20px 20px;
        // margin-bottom: 20px;
        display: flex;

        .save{ 
          margin-left: 230px;
        }
      }
      .buttonList2{
        width: 100%;
        padding-top: 20px;
        text-align: center; 
        margin-bottom: 20px;
      }
      
      /* tr{ 
        height: 36px;
        text-align: center;
      } */
      .readIpt{ 
        width: 100%;
        height:30px;
        display: block;
        margin: auto; 
        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 30px 10px 15px;
      }
      .el-form-item__label{ 
        width: 80px;
      }
      .el-form-item__content{ 
        display: flex;
      }
      .el-form-item{ 
        margin-bottom: 18px;
      }
      .dialog-footer{ 
        text-align: center;
        
      }
    }
  }

   @media screen and (max-width:1366px) {
    .systemManagement {
      .con {
        .catalogCon {
          padding: 20px 30px 0 15px;
          margin-bottom: 20px;
        }
        .buttonList2 {
          padding: 0;
        }
      }
    }
  }
</style>
