<template>
  <div v-if="!noData" class="padding-20 page-box-row-left">
    <FormBlock :title="$t('module.menu.menuInfo')" direction="column" style="width:380px" :style="{height: treeBoxHeight}">
      <el-tree :data="baseData" :props="defaultProps" highlight-current check-strictly default-expand-all indent="10" node-key="menuId" ref="menuTree" @node-click="handleNodeClick" :render-content="renderContent" :expand-on-click-node="false">
      </el-tree>
    </FormBlock>
    <FormBlock :title="$t('module.menu.menuDetail')" direction="column">
      
      <Form ref="menuForm" :model="menuForm" :rules="rules" label-position="right" :label-width="100" v-if="showDetail">
        <div class="">
          <Row :gutter="20" class="code-row-bg">
            <Col span="20">
            <Form-item prop="menuCode" :label="$t('module.menu.code')">
              <Input v-model="menuForm.menuCode" placeholder="" v-bind:readonly="isReadOnly"></Input>
            </Form-item>
            </Col>
          </Row>
          <Row :gutter="20" class="code-row-bg">
            <Col span="20">
            <Form-item prop="menuName" :label="$t('module.menu.name')">
              <Input v-model="menuForm.menuName" placeholder="" v-bind:readonly="isReadOnly"></Input>
              <Icon class="global-icon" v-show="isShow"  @click.native="menuEdit"></Icon>              
            </Form-item>
            </Col>
          </Row>
          <Row :gutter="20" class="code-row-bg">
            <Col span="20">
            <Form-item prop="menuDesc" :label="$t('module.menu.description')">
              <Input v-model="menuForm.menuDesc" placeholder="" v-bind:readonly="isReadOnly"></Input>
            </Form-item>
            </Col>
          </Row>
          <Row :gutter="20" class="code-row-bg">
            <Col span="20">
            <Form-item prop="iconCls" :label="$t('module.menu.iconCls')">
              <!--<Input v-model="menuForm.iconCls" placeholder="" v-bind:disabled ="isReadOnly"></Input>-->
              <Icon :type="menuForm.iconCls" class="icon-size icon-margin-right"></Icon>
              <span v-if="menuForm.iconCls">{{menuForm.menuName}}</span>
              <Icon type="md-menu" class="icon-select icon-size" @click.native="iconEdit"></Icon>
            </Form-item>
            </Col>
          </Row>
          <Row :gutter="20" class="code-row-bg">
            <Col span="20">
            <Form-item prop="parentMenuName" :label="$t('module.menu.parentNode')">
              <Input v-model="menuForm.parentMenuName" placeholder="" readonly="true"></Input>
            </Form-item>
            </Col>
          </Row>
          <Row :gutter="20" class="code-row-bg">
            <Col span="20">
            <Form-item prop="menuType" :label="$t('module.menu.type')">
              <Select v-model="menuForm.menuType" v-bind:disabled="isOrNoteRead">
                <Option value="1">{{$t('module.menu.categoryType')}}</Option>
                <Option value="0">{{$t('module.menu.menuType')}}</Option>
              </Select>
            </Form-item>
            </Col>
          </Row>
          <Row :gutter="20" class="code-row-bg">
            <Col span="20">
            <Form-item prop="sort" :label="$t('module.menu.sortNo')">
              <InputNumber min=0 max=99 v-model="menuForm.sort" placeholder="" style="width:100%" v-bind:readonly="isReadOnly"></InputNumber>
            </Form-item>
            </Col>
          </Row>
          <Row :gutter="20" class="code-row-bg" v-if="menuForm.menuType != 1">
            <Col span="20">
            <Form-item prop="actionUrl" :label="$t('module.menu.frontModule')">
              <Input v-model="menuForm.actionUrl" placeholder="" v-bind:readonly="isReadOnly"></Input>
            </Form-item>
            </Col>
          </Row>
          <Row :gutter="20" class="code-row-bg">
            <Col span="20">
            <Form-item prop="iconCls" :label="$t('module.menu.iconCls')">
              <Input v-model="menuForm.iconCls" placeholder=""></Input>
            </Form-item>
            </Col>
          </Row>
          <Row :gutter="20" class="code-row-bg">
            <Col span="20">
            <Form-item prop="favoriteDesc" :label="$t('module.menu.favoriteDesc')">
              <Input v-model="menuForm.favoriteDesc" placeholder=""></Input>
            </Form-item>
            </Col>
          </Row>
          <Row :gutter="20" class="code-row-bg" v-show="!isReadOnly">
            <Col span="20">
            <Button class="ivu-btn-hr" type="primary" @click="saveOrUpdateMenu" style="margin-left:100px;" :loading="saveLoading">{{btnTitle}}</Button>
            </Col>
          </Row>
        </div>
      </Form>
      <!-- 暂无数据 -->
      <div class="noInfoShow">{{$t("module.menu.noData")}}</div>
    </FormBlock>
  </div>
  <div class="sidelip-noInfor" v-else style=" text-align: center;margin-top: 100px;">
    <span class="infor-icon" style="cursor:pointer;">
      <Icon type="person-add" />
    </span>
    <p>{{$t("module.menu.addMenuTip")}}</p>
    <Button type="primary" icon="plus" style="width:100px" @click="addMenu(true)">{{$t("common.creat")}}</Button>
  </div>
</template>

<style>

</style>

<script>
import Three from "../../../tools/getThree.js";
import MenuEdit from "./MenuEdit.vue";
import IconEdit from "./IconEdit.vue";
export default {
  name: 'menu-manage',
  title: "this.$t('module.menu.manageMenu')",
  components: {},
  data() {
    const validateMenuCode = (rule, value, callback) => {
      if (value === "") {
        callback(new Error(this.$t("module.menu.warning.enterMenuCode")));
      } else if (value.length > 50) {
        callback(new Error(this.$t("module.menu.warning.menuCodeMoreThan50Charts")));
      } else if (!new RegExp("^[a-zA-Z0-9_]{1,}$").test(value)) {
        callback(new Error(this.$t("module.menu.warning.menuCodeForm")));
      }
      callback();
    };
    const validateMenuName = (rule, value, callback) => {
      if (value === "") {
        callback(new Error(this.$t("module.menu.warning.enterMenuName")));
      } else if (value != value.trim()) {
        callback(new Error(this.$t("module.menu.warning.menuNameNoSpace")));
      } else if (value.length > 50) {
        callback(new Error(this.$t("module.menu.warning.menuNameMoreThan50Charts")));
      }
      callback();
    };
    const validateMenuDesc = (rule, value, callback) => {
      if (value != null && value != value.trim() && value.trim() === "") {
        callback(new Error(this.$t("module.menu.warning.enterMenuDescription")));
      }
      if (value != null && value.length > 200) {
        callback(new Error(this.$t("module.menu.warning.menuDescriptionMoreThan200Charts")));
      }
      callback();
    };
    const validateSort = (rule, value, callback) => {
      if (
        !new RegExp("^[0-9]d*$").test(value) &&
        !value.replace(/(^\s*)|(\s*$)/g, "")
      ) {
        callback(new Error(this.$t("module.menu.warning.sortNoMustBeNum")));
      }
      callback();
    };
    return {
      version: '',
      isShow: false,
      currentId:"",
      isReadOnly: false,
      menuId: "",
      menuCode: "",
      menuName: "",
      menuDesc: "",
      sort: "",
      actionUrl: "",
      iconCls: "",
      favoriteDesc: "",
      menuType: "",
      noData: false,
      saveLoading: false,
      orgSelectWin: false,
      showDetail: false,
      btnTitle: this.$t('common.save'),
      firstLoading: true,
      currentNodeIsRootMenu: false,
      menuForm: {
        menuCode: "",
        menuName: "",
        menuId: "",
        parentMenuName: "",
        menuModuleId: "", //parentMenuId
        menuDesc: "",
        sort: "",
        actionUrl: "",
        menuType: "",
        iconCls: "",
        favoriteDesc: "",
      },

      rules: {
        menuCode: [
          { validator: validateMenuCode, trigger: "blur", required: true }
        ],
        menuName: [
          { validator: validateMenuName, trigger: "blur", required: true }
        ],
        menuDesc: [{ validator: validateMenuDesc, trigger: "blur" }]
      },
      baseData: [
        //最外层虚拟功能，防止删除一级目录功能后整棵树消失
        {
          menuName: this.$t('module.menu.rootNode'),
          menuId: "0",
          menuCode: "0",
          menuDesc: this.$t('module.menu.topMenu'),
          parentMenuName: this.$t('module.menu.nothing'),
          sort: "0",
          actionUrl: this.$t('module.menu.nothing'),
          menuType: "1",
          children: [] //后天调取的树中的data放在这里
        }
      ],
      selectedData: {},
      defaultProps: {
        children: "children",
        label: "menuName"
      },
      node: {},
      nodeElement: {},
      treeBoxHeight: (window.innerHeight - 110) + "px"
    };
  },
  computed: {},
  created: function () {
    this.$emit("setTitle", this.menuName);
    this.loadNode(); //初始化加载
  },
  mounted: function () {
    //this.selectFirstMenu(); //加载时默认显示页
  },
  methods: {
    menuEdit(){
      new this.$pageModal(
        MenuEdit,
        {
          props:{
            menuId: this.currentId,
          },
        },(data) => {
          //编辑名称后刷新左侧功能树
          this.loadNode(); 
          //编辑名称后刷新右侧表单
          for(const key in data){
            if(window.localStorage.language == data[key].langCode){
              this.menuForm.menuName = data[key].menuName;//编辑名称后刷新右侧功能详情
            }
          }
        }
      )
    },
    append(store, data, sonData) {
      store.append(sonData, data);
      let menuTree = this.$refs["menuTree"];
      menuTree.setCurrentKey(sonData.menuId);
      this.node = menuTree.getCurrentNode();
      this.btnTitle = this.$t('common.save');
    },
    gotoAddMenu(data) {
      this.selectedData = data;
      this.addMenu(false);
    },
    //添加删除小图标
    renderContent(h, { node, data, store }) {
      return (
        <span>
          <span title={node.label}>{node.label}</span>
          <div class="orgEditMenu" id={"MENU" + data.menuId}>
            <span
              v-show={data.menuType != "0"} //条件过滤显示
              class="orgEditSonMenu"
              on-click={(event) => this.addMenu(false, node, event)}//传入event解决火狐兼容性问题
            >
              <i class="el-icon-plus" title={this.$t('module.menu.create')}>
                {" "}
              </i>
            </span>
            <span
              v-show={data.menuId != "0"} //条件过滤显示
              class="orgEditSonMenu"
              on-click={(event) => this.deleteMenu(data, node, event)}
            >
              <i class="el-icon-delete" title={this.$t('module.menu.delete')}>
                {" "}
              </i>
            </span>
          </div>
        </span>
      );
    },
    remove(store, data) {
      store.remove(data);
    },
    handleNodeClick(data, node, nodeElement) {
      this.version = data.version
      this.isShow = true;
      this.currentId = data.menuId;
      this.isOrNoteRead = true;
      if (data.menuId == "0") {
        this.isReadOnly = true;
      } else {
        this.isReadOnly = false;
      }
      this.currentNodeIsRootMenu = false;
      this.node = node;

      this.showDetail = true;
      this.btnTitle = this.$t('common.save');
      let v_parentMenuName =node.parent.data.menuName;
      this.menuForm = {
        menuId: data.menuId,
        menuCode: data.menuCode,
        menuName: data.menuName,
        menuDesc: data.menuDesc,
        menuType: data.menuType,
        menuModuleId: data.menuModuleId,
        sort: data.sort,
        actionUrl: data.actionUrl,
        iconCls: data.iconCls,
        favoriteDesc: data.favoriteDesc,
        parentMenuName: v_parentMenuName
      };
    },
    loadNode(node, resolve) {
      $store
        .dispatch("QueryMenus", {
          commonPageDTO: {
            currentPage: 1,
            pageSize: 10000
          }
        })
        .then(res => {
          let tree = new Three(res.recordList, {
            sort: true
          });
          this.baseData[0].children = tree.json;
        });
      //node.checked = checked;
    },
    addMenu(addTopMenu, node, event) {
      // node.data.menuId;
      this.isShow = false;
      event.stopPropagation(); //阻止点击事件向上冒泡
      this.isOrNoteRead = false;
      let parentMenuName = "";
      let parentId = "";
      this.node = node;
      this.isReadOnly = false;
      if (addTopMenu || this.node == null || this.node.data.length == 0) {
        this.noData = false;
        parentMenuName = this.menuName;
        parentId = "";
      } else {
        parentMenuName = this.node.data.menuName;
        parentId = this.node.data.menuId == "0" ? "" : this.node.data.menuId;
      }
      this.showDetail = true;
      this.btnTitle = this.$t('module.menu.createNewMenu');
      this.menuForm = {
        menuId: this.menuId,
        menuCode: "",
        menuName: "",
        menuDesc: "",
        actionUrl: "",
        menuType: "1",
        sort: "0",
        parentMenuName: parentMenuName,
        iconCls: "",
        favoriteDesc: "",
        menuModuleId: parentId
      };
    },
    deleteMenu(data, node, event) {
       event.stopPropagation();//火狐不支持
      this.handleNodeClick(data, node); //此处将当前详情页修改为当前点击条目，这样做，不太理想：Yelow
      let parentNode = node.parent;
      new $confirm(this.$t('module.menu.confirmDelete'), this).then(() => {
        $store.dispatch("DeleteMenu", data.menuId).then(res => {
          if (!res.success) {
            this.$Message.warning({
              content: res.msg,
              duration: 3
            });
            return;
          }
          this.$Message.success({
            content: this.$t('module.menu.deleteSuccess'),
            duration: 3
          });
          //此处应该刷新功能树,右侧显示上级功能
          this.remove(node.store, node.data);
          if (parentNode.level > 0) {
            this.$refs["menuTree"].setCurrentKey(parentNode.data.menuId);
            this.handleNodeClick(parentNode.data, parentNode);
          } else {
            this.baseData = [];
            this.firstLoading = true;
            this.noData = true;
          }
        });
      });
    },
    saveOrUpdateMenu() {
      this.$refs["menuForm"].validate(valid => {
        let v_parentMenuName = this.menuForm.parentMenuName;
        if (valid) {
          this.saveLoading = true;
          let paramEdit = {
            menuId: this.menuForm.menuId,
            menuCode: this.menuForm.menuCode,
            menuName: this.menuForm.menuName,
            menuDesc: this.menuForm.menuDesc,
            menuType: this.menuForm.menuType,
            actionUrl: this.menuForm.actionUrl,
            menuModuleId: this.menuForm.menuModuleId,
            version: this.version,
            iconCls: this.menuForm.iconCls,
            favoriteDesc: this.menuForm.favoriteDesc,
            sort: this.menuForm.sort
          };
          let paramAdd = {
            menuId: this.menuForm.menuId,
            menuCode: this.menuForm.menuCode,
            menuName: this.menuForm.menuName,
            menuDesc: this.menuForm.menuDesc,
            menuType: this.menuForm.menuType,
            actionUrl: this.menuForm.actionUrl,
            menuModuleId: this.menuForm.menuModuleId,
            iconCls: this.menuForm.iconCls,
            favoriteDesc: this.menuForm.favoriteDesc,
            sort: this.menuForm.sort
          };
          if (this.menuForm.menuId) {
            $store.dispatch("EditMenu", paramEdit).then(response => {
              if (response.success) {
                //编辑后刷新页面
                this.loadNode();
                this.$Message.success({
                  content: this.$t('module.menu.modifySuccess'),
                  duration: 3
                });
                this.saveLoading = false;
                if (this.currentNodeIsRootMenu) {
                  this.baseData[0].menuName = param.menuName;
                  this.baseData[0].menuDesc = param.menuDesc;
                  this.baseData[0].menuType = param.menuType;
                  this.baseData[0].menuCode = param.menuCode;
                  this.baseData[0].sort = param.sort;
                  this.baseData[0].actionUrl = param.actionUrl;
                  this.baseData[0].menuModuleId = param.menuModuleId;
                  this.baseData[0].iconCls = param.iconCls,
                  this.baseData[0].favoriteDesc = param.favoriteDesc
                } else {
                  //此处更新功能树
                  this.node.data.menuName = param.menuName;
                  this.node.data.menuDesc = param.menuDesc;
                  this.node.data.menuCode = param.menuCode;
                  this.node.data.menuType = param.menuType;
                  this.node.data.sort = param.sort;
                  this.node.data.actionUrl = param.actionUrl;
                  this.node.data.menuModuleId = param.menuModuleId;
                  this.node.data.iconCls = param.iconCls,
                  this.node.data.favoriteDesc = param.favoriteDesc
                }
              } else {
                this.$Message.error({
                  content: response.msg,
                  duration: 3
                });
              }
              this.saveLoading = false;
            });
          } else {
            $store.dispatch("EditMenu", paramAdd).then(response => {
              if (response.success) {
                this.isShow = true;
                //添加后刷新页面
                this.loadNode();
                //此处更新功能
                this.$Message.success({
                  content: this.$t('module.menu.createSuccess'),
                  duration: 3
                });
                this.isOrNoteRead = true;
                // this.saveLoading = false;
                // console.log(param);
                param.menuId = response.dataResult.menu.menuId;
                this.menuForm.menuId = param.menuId; //此处有bug，应该是从response返回结果中取menuId
                let child = {
                  menuId: param.menuId,
                  menuName: param.menuName,
                  menuCode: param.menuCode,
                  menuDesc: param.menuDesc,
                  parentId: param.parentId,
                  sort: param.sort,
                  menuType: param.menuType,
                  parentMenuName: v_parentMenuName,
                  menuModuleId: param.menuModuleId,
                  actionUrl: param.actionUrl,
                  iconCls: param.iconCls,
                  favoriteDesc: param.favoriteDesc,
                  children: []
                };

                if (this.baseData.length == 0) {
                  this.baseData.push(child);
                } else {
                  this.append(this.node.store, this.node.data, child);
                }
              } else {
                this.$Message.error({
                  content: response.msg
                });
              }
            });
              this.saveLoading = false;
          }
        } else {
          this.$Message.error(this.$t('module.menu.validateFail'));
        }
      });
    },
    selectFirstMenu() {
      //默认显示第一个功能信息
      if (this.firstLoading && this.baseData.length > 0) {
        this.$refs["menuTree"].setCurrentKey(this.baseData[0].menuId);
        this.showDetail = true;
        this.menuForm = {
          menuId: this.menuId,
          menuCode: this.baseData[0].menuCode,
          menuName: this.baseData[0].menuName,
          menuDesc: "",
          parentenuName: "",
          parentId: this.baseData[0].parentId
        };

        this.firstLoading = false;
        this.currentNodeIsRootMenu = true;
      }
    },
    iconEdit() {
      new this.$pageModal(
          IconEdit,
          {
          },
          data => {
              if(!! data) {
                  this.menuForm.iconCls = data.vsiValue
              }
          }
      );
    },
  },
  watch: {},
  directives: {}
};
</script>

<style lang="less">
  .noInfoShow{
    display: block;
    text-align: center;
    margin:5% 0;
  }
  .ivu-form + .noInfoShow{
    display: none;
  }
  .icon-margin-right {
    margin-right: 5px;
  }
  .icon-size {
    font-size: 12px;
  }
  .icon-select {
    width: 20px;
    height: 20px;
    background-size: cover;
    display: inline-block;
    position: absolute;
    right: 6px;
    top: 7px;
    cursor: pointer;
  }
</style>
