<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .appmenumanage .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 50px;
    height: 50px;
    line-height: 50px;
    text-align: center;
  }

  .avatar {
    width: 50px;
    height: 50px;
    display: block;
  }
</style>
<template>
  <div class="flexOne appmenumanage">
    <div class="query-box">
      <ul>
        <li>
          <span><em>名称</em><el-input v-model='msg.MenuName' class="permiss-input" placeholder="请输入内容"></el-input></span>
        </li>
        <li>
					<span><em>菜单类别</em>
            <el-select v-model='msg.Tier' @change="tireSelectChange()" placeholder="请选择">
                <el-option label="不限" value="0"></el-option>
								<el-option label="导航菜单" value="1"></el-option>
								<el-option label="二级菜单" value="2"></el-option>
              <!--<el-option label="三级" value="3"></el-option>-->
							</el-select>
				      </span>
        </li>

        <li>
					<span><em>所属菜单</em><el-select filterable v-model='msg.ParentId' filterable placeholder="请选择">
								<el-option label="不限" value="0"></el-option>
							    <el-option
                    v-for="item in getParentNodeData"
                    :key="item.MenuId"
                    :label="item.MenuName"
                    :value="item.MenuId">
							    </el-option>
							  </el-select>
				      </span>
        </li>
        <li>
					<span><em>状态</em><el-select v-model="msg.MenuStatus" placeholder="请选择">
							    <el-option label="不限" value="-1"></el-option>
							    <el-option label="开启" value="0"></el-option>
							    <el-option label="关闭" value="1"></el-option>
							  </el-select>
				      </span>
        </li>
        <li>
          <input type="button" class="hollowFixedBtn" name="" id="" value="查询" @click="resetPageIndex(),getList()"/>
          <input type="button" @click="outerVisible = true,dialogTitle='新增权限菜单',clearMessage();" class="normalBtn"
                 value="新增"/>
        </li>
      </ul>
    </div>
    <table class="singeRowTable" border="0" cellspacing="0" cellpadding="0">
      <tr>
        <th width="300">名称</th>
        <th width="500">菜单地址</th>
        <th>层级</th>
        <th>状态</th>
        <th>排序</th>
        <th>最低使用版本</th>
        <th width="100">操作</th>
      </tr>
      <tr v-for="(item,index) in DataList">
        <td>{{item.MenuName}}</td>
        <td>{{item.MenuUrl}}</td>
        <td>{{item.Tier | tierFormat(item.Tier)}}</td>
        <td>{{item.MenuStatus==0?'开启':'关闭'}}</td>
        <td>{{item.Sort}}</td>
        <td>{{item.LowVersion}}</td>
        <td>
          <el-row>
            <el-tooltip class="item" effect="dark" content="修改" placement="top-start">
              <el-button @click="outerVisible = true,dialogTitle='修改权限菜单',updateData(index,item.MenuId)" type="primary"
                         icon="el-icon-edit" circle></el-button>
            </el-tooltip>
          </el-row>
        </td>
      </tr>
    </table>
    <el-pagination
      background
      @current-change="handleCurrentChange"
      :current-page.sync="currentPage"
      layout="total,prev, pager, next, jumper"
      :page-size=msg.pageSize
      :total='total'>
    </el-pagination>

    <el-dialog custom-class='w750' :title="dialogTitle" :visible.sync="outerVisible" center
               :before-close="closeChangeMachie">
      <el-form :model="addMsg" :rules="rules" ref="addMsg" label-width="120px">
        <table class="layerNoIcon">
          <tr>
            <td>
              <el-form-item label="名称" prop="MenuName">
                <el-input maxlength='50' class='w200' type="text" v-model="addMsg.MenuName"
                          :placeholder="$t('pub.pleaseImport')"></el-input>
              </el-form-item>
            </td>
            <td>
              <el-form-item label="菜单URL" prop="MenuUrl">
                <el-input maxlength='50' class='w200' type="text" v-model="addMsg.MenuUrl"
                          :placeholder="$t('pub.pleaseImport')"></el-input>
              </el-form-item>
            </td>
          </tr>
          <tr>
            <td>
              <el-form-item label="菜单类别" prop="Tier">
                <el-select class='w200' v-model="addMsg.Tier" @change='getChildMenu(true)' placeholder="请选择">
                  <el-option label="导航菜单" value="1"></el-option>
                  <el-option label="二级菜单" value="2"></el-option>
                  <!--<el-option label="三级" value="3"></el-option>-->
                </el-select>
              </el-form-item>
            </td>
            <td>
              <el-form-item label="所属菜单" prop="ParentId">
                <el-select filterable class='w200' v-model='addMsg.ParentId' :placeholder="$t('pub.pleaseSel')">
                  <el-option v-for="item in layerGetParentNodeData" :key="item.MenuId" :label="item.MenuName"
                             :value="item.MenuId">
                  </el-option>
                </el-select>
              </el-form-item>
            </td>
          </tr>
          <tr>
            <td>
              <el-form-item label="排序" prop="Sort">
                <el-input class='w200' type="text" @keyup.native="checkInteger(addMsg,'Sort')" v-model="addMsg.Sort"
                          :placeholder="$t('pub.pleaseImport')"></el-input>
              </el-form-item>
            </td>
            <td>
              <el-form-item label="状态">
                <el-switch v-model="addMsg.MenuStatus" active-value="0" inactive-value="1"></el-switch>
              </el-form-item>
            </td>
          </tr>
          <tr v-if="addMsg.Tier==1">
            <td>
              <el-form-item label="标识码">
                <el-input class='w200' type="text" maxlength='50' v-model="addMsg.Code"
                          :placeholder="$t('pub.pleaseImport')"></el-input>
              </el-form-item>
            </td>
            <td>
              <el-form-item label="国际化">
                <el-input class='w200' type="text" maxlength='50' v-model="addMsg.Language"
                          :placeholder="$t('pub.pleaseImport')"></el-input>
              </el-form-item>
            </td>
          </tr>
          <tr v-if="addMsg.Tier==1">
            <td>
              <el-form-item label="菜单图标">
                <el-upload
                  class="avatar-uploader"
                  action=""
                  accept="image/jpeg,image/gif,image/png,image/bmp"
                  :http-request="uploadMenuImage"
                  :show-file-list="false">
                  <img v-if="addMsg.Image" :src="addMsg.Image" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-form-item>
            </td>
            <td>
              <el-form-item label="选中图标">
                <el-upload
                  class="avatar-uploader"
                  action=""
                  accept="image/jpeg,image/gif,image/png,image/bmp"
                  :http-request="uploadMenuSelectImage"
                  :show-file-list="false">
                  <img v-if="addMsg.SelectImage" :src="addMsg.SelectImage" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-form-item>
            </td>
          </tr>
          <tr v-if="addMsg.Tier==2">
            <td>
              <el-form-item label="国际化">
                <el-input class='w200' type="text" maxlength='50' v-model="addMsg.Language"
                          :placeholder="$t('pub.pleaseImport')"></el-input>
              </el-form-item>
            </td>
            <td>
              <el-form-item label="菜单图标">
                <el-upload
                  class="avatar-uploader"
                  action=""
                  accept="image/jpeg,image/gif,image/png,image/bmp"
                  :http-request="uploadMenuImage"
                  :show-file-list="false">
                  <img v-if="addMsg.Image" :src="addMsg.Image" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-form-item>
            </td>
          </tr>
          <tr>
            <td>
              <el-form-item label="最低使用版本" prop="Sort">
                <el-input class='w200' type="text" maxlength='50' v-model="addMsg.LowVersion"
                          :placeholder="$t('pub.pleaseImport')"></el-input>
              </el-form-item>
            </td>
          </tr>
        </table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <button class="hollowFixedBtn" @click="outerVisible = false,resetForm('addMsg'),getList()">
          {{$t('pub.cancelBtn')}}
        </button> &nbsp;
        <button class="normalBtn" type="primary" @click="submitForm('addMsg'),getList()">{{$t('pub.saveBtn')}}</button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    data() {
      let validateParent = (rule, value, callback) => {
        if (this.addMsg.Tier != '1' && this.addMsg.Tier != '' && value == '') {
          return callback(new Error('请选择上级层级'));
        } else {
          callback();
        }
      }
      let validateUrl = (rule, value, callback) => {
        callback();
        // if(this.addMsg.Tier!='2'&&this.addMsg.Tier!=''&&value==''){
        // 	 return callback(new Error('请输入菜单'));
        // }else{
        // 	 callback();
        // }
      }

      return {
        dialogTitle: '',
        DataList: '',
        total: 0,
        pageSize: '',
        currentPage: 1,
        thisColor: '#E95252',
        predefineColors: [
          '#ff4500',
          '#ff8c00',
          '#ffd700',
          '#90ee90',
          '#00ced1',
          '#1e90ff',
          '#c71585',
        ],
        outerVisible: false,
        addStatus: [{
          value: '0',
          label: '开启'
        }, {
          value: '1',
          label: '关闭'
        }],
        msg: { //列表查询请求数据
          "pageIndex": 1,
          'pageSize': 15,
          'MenuName': '',
          'ParentId': '',
          'MenuStatus': '0',
          'Tier': ''
        },
        addMsg: {
          'MenuId': '0',
          'Tier': '',
          'MenuName': '',
          'MenuUrl': '',
          'ParentId': '0',
          'MenuStatus': '0',
          'Sort': 0,
          Code: '',
          Language: '',
          Image: '',
          SelectImage: '',
          LowVersion: '',
        },
        rules: {
          MenuName: [
            {required: true, message: '请输入菜单名称', trigger: 'blur'}
          ],
          Tier: [
            {required: true, message: '请选择菜单层级', trigger: 'change'}
          ],
          ParentId: [
            {validator: validateParent, trigger: 'change'}
          ],
          MenuUrl: [
            {validator: validateUrl, trigger: 'blur'}
          ],
          Sort: [
            {required: true, message: '请输入排序', trigger: 'blur'}
          ],
        },
        getParentNodeMsg: {
          'Tier': '0',
          "ParentId": '0',
          "MenuStatus": '0',
          "MenuName": '',
        },
        layerGetParentNodeData: [],
        getParentNodeData: [],
        currentUpdateIndex: -1,
        allMenuNodeData: []//所有菜单节点
      }
    },
    mounted() {
      this.getList();
      this.getParentNode()
      this.getAllMenuNodeData();
    },
    filters: {
      tierFormat(value) {
        if (value == '1')
          return '导航菜单'
        if (value == '2')
          return '二级菜单'
        if (value == '3')
          return '三级菜单'
      }
    },
    methods: {
      getParentNode() { //上级权限
        this.getParentNodeMsg.Tier = this.msg.Tier - 1;
        this.apipost('admin_get_AppSysMenuGetList', this.getParentNodeMsg, res => {
          if (this.outerVisible) {
            this.layerGetParentNodeData = res.data.data;
          } else {
            if (this.getParentNodeMsg.Tier >= 1) {
              this.getParentNodeData = res.data.data;
            } else {
              this.getParentNodeData = [];
            }
          }
        }, err => {
        });
      },
      getList() { //列表查询
        this.apipost('admin_get_AppSysMenuGetPageList', this.msg, res => {
          if (res.data.resultCode == 1) {
            this.DataList = res.data.data.pageData;
            this.total = res.data.data.count;
          }
        }, err => {
        })
      },
      getChildMenu(isRestParentId) {
        if(isRestParentId){
          this.addMsg.ParentId = '';
        }
        this.layerGetParentNodeData = [];
        if (this.addMsg.Tier >= 1) {
          this.getParentNodeMsg.Tier = this.addMsg.Tier - 1;
          this.allMenuNodeData.forEach(x => {
            if (x.Tier === this.getParentNodeMsg.Tier) {
              this.layerGetParentNodeData.push(x);
            }
          });
        }
      },
      addData() { //新增数据
        if (this.addMsg.MenuName == '') {
          this.$message.error('菜单名不能为空');
          return
        }
        this.apipost('admin_post_AppSysMenuSet', this.addMsg, res => {
          if (res.data.resultCode == 1) {
            this.outerVisible = false;
            this.$message.success(res.data.message)
            if (this.currentUpdateIndex > -1) {
              this.DataList[this.currentUpdateIndex] = this.addMsg
            }
            this.getList();
            this.getAllMenuNodeData();
          } else {
            this.$message.error(res.data.message);
          }
        }, err => {
        })
      },
      updateData(index, id) { //修改
        this.apipost('admin_get_AppSysMenuGet', {MenuId: id}, res => {
          let updateList = res.data.data;
          this.addMsg.MenuId = id;
          this.addMsg.MenuName = updateList.MenuName;
          this.addMsg.Tier = updateList.Tier.toString();
          this.addMsg.ParentId = updateList.ParentId;
          this.addMsg.MenuUrl = updateList.MenuUrl;
          this.addMsg.MenuStatus = updateList.MenuStatus.toString();
          this.addMsg.Sort = updateList.Sort;
          this.addMsg.Code = updateList.Code;
          this.addMsg.Language = updateList.Language;
          this.addMsg.Image = updateList.Image
          this.addMsg.SelectImage = updateList.SelectImage;
          this.addMsg.LowVersion = updateList.LowVersion;
          this.currentUpdateIndex = index;
          this.getChildMenu(false);
        }, err => {
        });
        this.currentUpdateIndex = index
      },
      handleCurrentChange(val) {
        this.msg.pageIndex = val;
        this.getList();
      },
      clearMessage() {
        this.addMsg = {
          'Tier': '',
          'MenuName': '',
          'MenuUrl': '',
          'ParentId': '',
          'MenuStatus': '0',
          Sort: 0,
          Code: '',
          Language: '',
          Image: '',
          SelectImage: ''
        }
      },
      resetPageIndex() {
        this.msg.pageIndex = 1
        this.currentPage = 1
      },
      submitForm(addMsg) {//提交创建、修改表单
        this.$refs[addMsg].validate((valid) => {
          if (valid) {
            this.addData()
          } else {
            return false;
          }
        });
      },
      closeChangeMachie(done) {//弹出框关闭初始化弹框内表单
        done();
        this.resetForm('addMsg');
      },
      resetForm: function (formName) {//弹出框取消 初始化谈框内表单
        this.$refs[formName].resetFields();
      },
      tireSelectChange() {
        if (this.allMenuNodeData.length === 0) {
          this.getAllMenuNodeData();
        } else {
          this.initAllMenuNodeData();
        }
      },
      getAllMenuNodeData() {
        let tempParentNodeMsg = JSON.parse(JSON.stringify(this.getParentNodeMsg));
        tempParentNodeMsg.Tier = 0;
        this.apipost('admin_get_AppSysMenuGetList', tempParentNodeMsg, res => {
          if (res.data.resultCode === 1) {
            this.allMenuNodeData = res.data.data;
            this.initAllMenuNodeData();
          } else {
            this.Error(res.message);
          }
        }, err => {
        });
      },
      initAllMenuNodeData() {
        this.getParentNodeData = [];
        let tier = this.msg.Tier - 1;
        this.allMenuNodeData.forEach(x => {
          if (x.Tier === tier) {
            this.getParentNodeData.push(x);
          }
        });
      },
      //上传菜单图标
      uploadMenuImage(item) {
        let newArr = [];
        newArr.push(item.file);
        let path = "/Upload/Icon/AppMenuIcon/";
        this.UploadSelfFileT(path, newArr, x => {
          var str = this.domainManager().ViittoFileUrl + x.data.FilePath;
          this.addMsg.Image = str
        });
      },
      //上传菜单选中图标
      uploadMenuSelectImage(item) {
        let newArr = [];
        newArr.push(item.file);
        let path = "/Upload/Icon/AppMenuIcon/";
        this.UploadSelfFileT(path, newArr, x => {
          var str = this.domainManager().ViittoFileUrl + x.data.FilePath;
          this.addMsg.SelectImage = str
        });
      }
    }
  }
</script>
