<template>
  <div
    v-if="!noData"
    class="padding-20 page-box-row-left menuManage-com"
  >
    <FormBlock
      title="功能信息"
      direction="column"
      style="width:380px; overflow:auto"
      :style="{height: treeBoxHeight}"
    >
    <Spin fix v-show="loadingSpin"></Spin>
      <Tree
      ref="menuTree"
      class="SelectMenuManage"
      :data="baseData"
      :render="renderContent"
    ></Tree>
    </FormBlock>
    <FormBlock
      title="功能详情"
      direction="column"
    >
      <Form
        v-if="showDetail"
        ref="menuForm"
        :model="menuForm"
        :rules="rules"
        label-position="right"
        :label-width="100"
      >
        <div class>
          <Row
            :gutter="20"
            class="code-row-bg"
          >
            <Col span="20">
            <Form-item
              prop="menuCode"
              label="编码"
            >
              <Input
                v-model="menuForm.menuCode"
                placeholder
                :readonly="isReadOnly"
              ></Input>
            </Form-item>
            </Col>
          </Row>
          <Row
            :gutter="20"
            class="code-row-bg"
          >
            <Col span="20">
            <Form-item
              prop="menuName"
              label="名称"
            >
              <Input
                v-model="menuForm.menuName"
                placeholder
                :readonly="isReadOnly"
              ></Input>
              <Icon
                v-show="isShow"
                class="global-icon"
                @click.native="menuEdit"
              ></Icon>
            </Form-item>
            </Col>
          </Row>
          <Row
            :gutter="20"
            class="code-row-bg"
          >
            <Col span="20">
            <Form-item
              prop="menuDesc"
              label="描述"
            >
              <Input
                v-model="menuForm.menuDesc"
                placeholder
                :readonly="isReadOnly"
              ></Input>
            </Form-item>
            </Col>
          </Row>
          <Row
            :gutter="20"
            class="code-row-bg"
          >
            <Col span="20">
            <Form-item
              prop="parentMenuName"
              label="上级节点"
            >
              <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="功能类型"
            >
              <Select
                v-model="menuForm.menuType"
                :disabled="isOrNoteRead"
              >
                <Option value="1">
                  目录
                </Option>
                <Option value="0">
                  功能
                </Option>
              </Select>
            </Form-item>
            </Col>
          </Row>
          <Row
            :gutter="20"
            class="code-row-bg"
          >
            <Col span="20">
            <Form-item
              prop="sort"
              label="排序号"
            >
              <InputNumber
                v-model="menuForm.sort"
                :min="0"
                :max="99"
                placeholder
                style="width:100%"
                :readonly="isReadOnly"
              ></InputNumber>
            </Form-item>
            </Col>
          </Row>
          <Row
            v-show="!isReadOnly"
            :gutter="20"
            class="code-row-bg"
          >
            <Col span="20">
            <Button
              class="ivu-btn-hr"
              type="primary"
              style="margin-left:100px;"
              :loading="saveLoading"
              size="small"
              @click="saveOrUpdateMenu"
            >
              {{ btnTitle }}
            </Button>
            </Col>
          </Row>
        </div>
      </Form>
      <!-- 暂无数据 -->
      <div class="noInfoShow">
        暂无数据
      </div>
    </FormBlock>
  </div>
  <div
    v-else
    class="sidelip-noInfor"
    style=" text-align: center;margin-top: 100px;"
  >
    <span
      class="infor-icon"
      style="cursor:pointer;"
    >
      <Icon type="person-add" />
    </span>
    <p>赶紧添加功能信息吧</p>
    <Button
      type="primary"
      icon="plus"
      style="width:100px"
      @click="addMenu(true)"
    >
      添加
    </Button>
  </div>
</template>
<script>
import Three from '../../util/getThree.js';
import MenuEdit from './MenuEdit.vue';
import IconEdit from './IconEdit.vue';
import { DeleteMenu, QueryMenus, EditMenu } from '../server.js';

let $baseData =  [
        // 最外层虚拟功能，防止删除一级目录功能后整棵树消失
        {
          menuName: '根节点',
          menuId: '0',
          menuCode: '0',
          menuDesc: '顶级功能',
          parentMenuName: '无',
          sort: '0',
          actionUrl: '无',
          menuType: '1',
          children: [] // 后天调取的树中的data放在这里
        }
      ]
export default {
  name: 'MenuManage',
  title: '功能管理',
  components: {},
  directives: {},
  data() {
    const validateMenuCode = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入功能编码'));
      } else if (!new RegExp('^[a-zA-Z0-9_]{1,}$').test(value)) {
        callback(new Error('功能编码只能有a-zA-Z0-9组成'));
      }
      callback();
    };
    const validateMenuName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入功能名称'));
      } else if (value != value.trim()) {
        callback(new Error('功能名称前后不能有空格'));
      }
      callback();
    };
    const validateMenuDesc = (rule, value, callback) => {
      if (value != null && value != value.trim() && value.trim() === '') {
        callback(new Error('请输入合法的功能描述'));
      }
      if (value != null && value.length > 200) {
        callback(new Error('功能描述长度超过200个字符限制'));
      }
      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: '保存',
      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: $baseData,
      selectedData: {},
      treeData_bak: [],
      defaultProps: {
        children: 'children',
        label: 'menuName'
      },
      node: {},
      nodeElement: {},
      treeBoxHeight: window.innerHeight - 250 + 'px',
      loadingSpin: true
    };
  },
  computed: {},
  watch: {},
  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);
      const menuTree = this.$refs.menuTree;
      menuTree.setCurrentKey(sonData.menuId);
      this.node = menuTree.getCurrentNode();
      this.btnTitle = '保存';
    },
    gotoAddMenu(data) {
      this.selectedData = data;
      this.addMenu(false);
    },
    // 添加删除小图标
    renderContent (h, { root, node, data }) {
        return h('span', {
            style: {
                display: 'inline-block',
                width: '100%'
            }
        }, [
            h('span', {
              on: {
                        click: () => { this.handleNodeClick(root, data, node) }
                    }
            },[
                h('Icon', {
                    props: {
                        type: 'ios-paper-outline'
                    },
                    style: {
                        marginRight: '8px'
                    }
                }),
                h('span', data.title)
            ]),
            h('span', {
                style: {
                    display: 'flex',
                    float: 'right',
                    marginRight: '32px',
                    marginTop: '-7px'
                }
            }, [
                h('span', {
                    style: {
                        display: data.menuType != '0' ? 'block' : 'none',
                        fontSize: '18px',
                        padding: '0 5px'
                    },
                    on: {
                        click: () => { this.addMenu(false, node, data) }
                    }
                },[h('Icon', {
                    props: {
                        type: 'md-add'
                    }
                })]),
                h('span', {
                    style: {
                      display: data.menuCode != 'baozhangshenqing' ? 'block' : 'none',
                      fontSize: '18px',
                      padding: '0 5px'
                    },
                    on: {
                        click: () => { this.deleteMenu(root, node, data) }
                    }
                },[h('Icon', {
                    props: {
                        type: 'md-trash'
                    }
                })])
            ])
        ]);
    },

    remove(store, data) {
      store.remove(data);
    },

    // 展示右边 编辑框内容
    handleNodeClick(root, node, data) {
      this.version = node.version;
      this.isShow = true;
      this.currentId = node.menuId;
      this.isOrNoteRead = true;
      if (node.menuCode == 'baozhangshenqing') {
        this.isReadOnly = true;
      } else {
        this.isReadOnly = false;
      }
      this.currentNodeIsRootMenu = false;
      this.node = node;
      this.showDetail = true;
      this.btnTitle = '保存';
      const parentMenuName = node.parentNode // node.parent.data.menuName;
      this.menuForm = {
        menuId: node.menuId,
        menuCode: node.menuCode,
        menuName: node.menuName,
        menuDesc: node.menuDesc,
        menuType: node.menuType,
        menuModuleId: node.menuModuleId,
        sort: node.sort,
        actionUrl: node.actionUrl,
        iconCls: node.iconCls,
        favoriteDesc: node.favoriteDesc,
        parentMenuName
      };
      // 增加回调
      this.$emit('handleSelect', this.menuForm);
    },

    // 初始化数据加载
    loadNode(node, resolve) {
      this.loadingSpin = true
      this.baseData = $baseData
      QueryMenus({
        commonPageDTO: {
          currentPage: 1,
          pageSize: 10000
        }
      }).then(res => {
        this.loadingSpin = false
        // 整理数据
        const list = res.dataResult.recordList;
        // 定义父级
        const pNode = list.find(item => item.menuCode == 'baozhangshenqing');
        if (pNode) {
          pNode.title = pNode.menuName;
          this.formatMenuData(pNode.menuId, list);
          this.treeData_bak.push(pNode);
        }
        const tree = new Three(this.treeData_bak, {
          sort: true
        });
        this.baseData = tree.json;
      });
      // node.checked = checked;
    },

    formatMenuData(pid, list) {
      const result = [];
      list.forEach(item => {
        if (item.menuModuleId === pid) {
          // // item["expand"] = true;
          // item["children"] = this.formatMenuData(item.menuId, list);
          this.formatMenuData(item.menuId, list);
          // result.push(item);
          this.treeData_bak.push(item);
        }
      });
      return result;
    },

    // 添加 树节点
    addMenu(addTopMenu, node, data) {
      // node.data.menuId;
      this.isShow = false;
      this.isOrNoteRead = false;
      let parentMenuName = '';
      let parentId = '';
      this.node = data;
      this.isReadOnly = false;
      if (addTopMenu || this.node == null || this.node.length == 0) {
        this.noData = false;
        parentMenuName = this.parentNode;
        parentId = "";
      } else {
        parentMenuName = data.parentNode;
        parentId = data.menuId == "0" ? "" : data.menuId;
      }
      this.showDetail = true;
      this.btnTitle = '添加新功能';
      this.menuForm = {
        menuId: this.menuId,
        menuCode: '',
        menuName: '',
        menuDesc: '',
        actionUrl: '',
        menuType: '1',
        sort: 0,
        parentMenuName: parentMenuName,
        iconCls: '',
        favoriteDesc: '',
        menuModuleId: parentId
      };
    },

    // 删除 树节点
    deleteMenu(root, node, data) {
      this.handleNodeClick(root, node, data); // 此处将当前详情页修改为当前点击条目，这样做，不太理想：Yelow
      const parentNode = node.parent;
      this.$Modal.confirm({
          title: '删除提示',
          content: '<p>确认删除？</p>',
          'ok-text': '确定',
          'cancel-text': '取消',
          onOk: async() => {
            const DeleteMenuData = await DeleteMenu(data.menuId);
            // console.log("DeleteMenuData----", DeleteMenuData)
            if (data.statusCode === '-1') {
              this.$Message.error(data.msg);
            } else {
              this.$Message.success('删除成功');

              //更新dom
              const parentKey = root.find(el => el === node).parent;
              const parent = root.find(el => el.nodeKey === parentKey).node;
              const index = parent.children.indexOf(data);
              parent.children.splice(index, 1);
              // 此处应该刷新功能树,右侧显示上级功能
              // 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;
              // }
            }
          },
          onCancel: () => {}
        });
    },

    // 保存 树节点
    saveOrUpdateMenu() {
      this.$refs.menuForm.validate(valid => {
        const parentMenuName = this.menuForm.parentMenuName;
        if (valid) {
          this.saveLoading = this.loadingSpin = true;
          if (this.menuForm.menuId) { // 修改
            const param = {
              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
            };

            EditMenu(param).then(response => {
              const {dataResult: {menu = {}} = {}, statusCode, msg = ''} = response
              this.saveLoading = this.loadingSpin = false;
              if (statusCode == 0) {
                  this.$Message.success({
                    content: '功能修改成功',
                    duration: 3
                  });
                  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.menuName = param.menuName;
                    this.node.menuDesc = param.menuDesc;
                    this.node.menuCode = param.menuCode;
                    this.node.menuType = param.menuType;
                    this.node.sort = param.sort;
                    this.node.actionUrl = param.actionUrl;
                    this.node.menuModuleId = param.menuModuleId;
                    this.node.iconCls = param.iconCls;
                    this.node.favoriteDesc = param.favoriteDesc;
                    this.node.title = menu.menuName,
                    this.node.expand = true
                  }

                  // 更新dom
                const children = this.node.children || [];
                this.$set(this.node, 'children', children);

                // 编辑后刷新页面
                // this.loadNode();
              } else {
                  this.$Message.error({
                    content: msg || '功能修改失败',
                    duration: 3
                  });
              }
            });
          } else { // 新建
            const param = {
              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
            };
            
            EditMenu(param).then(data => {
              this.saveLoading = this.loadingSpin = false;
              const {dataResult: {menu = {}} = {}, statusCode, msg = ''} = data
              if (statusCode == 0) {
                this.isShow = true;
                // this.loadNode();// 此处更新功能
                this.$Message.success({
                  content: '功能添加成功',
                  duration: 3
                });
                this.isOrNoteRead = true;
                this.menuForm.menuId = menu.menuId; // 此处有bug，应该是从response返回结果中取menuId
                const child = {
                  menuId: menu.menuId,
                  menuName: menu.menuName,
                  menuCode: menu.menuCode,
                  menuDesc: menu.menuDesc,
                  parentId: menu.parentId,
                  sort: menu.sort,
                  menuType: menu.menuType,
                  parentMenuName: parentMenuName,
                  menuModuleId: menu.menuModuleId,
                  actionUrl: menu.actionUrl,
                  iconCls: menu.iconCls,
                  favoriteDesc: param.favoriteDesc,
                  children: [],
                  title: menu.menuName,
                  expand: true
                };

                // 更新dom
                const children = this.node.children || [];
                children.push(child)
                this.$set(this.node, 'children', children);
              } else {
                this.$Message.error({
                  content: msg || '功能添加失败',
                  duration: 3
                });
              }
            }); 
          }
        } else {
          this.$Message.error('表单验证失败，请补充功能信息后再提交');
        }
      });
    },


    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;
        }
      });
    },

    // 抛给父组件
    getNodeData() {
      return this.node;
    }
  }
};
</script>

<style lang="less">
.menuManage-com{
  display: flex;
  .form-block:last-child{
    flex: 1;
  }
}
.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;
}
.SelectMenuManage .el-tree-node {
  white-space: initial;
}
.SelectMenuManage .el-tree-node__content {
  height: initial;
  padding-right: 20px;
}
</style>
