import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {NzMessageService, NzModalService} from 'ng-zorro-antd';
import {HttpClient} from '@angular/common/http';
import {SystemService} from '../../../services/system.service';
import {environment} from '../../../../environments/environment';
declare var $: any;

@Component({
  selector: 'app-menu',
  templateUrl: './menu.component.html',
  styleUrls: ['./menu.component.less', '../../../../assets/css/bootstrap-treeview.min.css']
})
export class MenuComponent implements OnInit {


  /* 请求参数-查询 */
  queryMenuName = null;
  /* 请求参数-增加、修改 */
  menu: any = {
    id: null,
    menuPSid: null,
    menuType: null,
    menuName: null,
    menuUrl: null,
    showOnMobile: false,
    menuMobileUrl: null,
    menuUrlImg: null,
    menuSort: null,
    menuDesc: null
  };
  parentMenuName = '无';
  /* 查询结果 */
  menuTree = [];
  treeNodeCount = 0;
  /* 权限 */
  USER_INFO;
  WEB_SERVE_URL = environment.baseUrl;
  FILE_URL = environment.imageUrl;
  /* 页面元素 */
  updateType = 'default';
  delAble = false;    // 删除按钮是否可用
  // 选中节点信息
  selectedMenu: any = {
    // 数据信息
    id: null,
    pId: null,
    text: null,
    showOnMobile: null,
    nodes: null,
    state: null,

    // 节点信息
    nodeId: null,
    parentId: null,
  };
  checkedMenu = [];
  validateFormQuery: FormGroup;
  validateFormEdit: FormGroup;
  loadingSearch = false;    // 加载菜单树
  loadingSearchDetail = false;    // 加载菜单详情
  loadingImg = false;    // 图片上传
  pcMenu = true;    // PC手机菜单切换 true-PC菜单 false-手机菜单

  constructor(
    private fb: FormBuilder,
    private message: NzMessageService,
    private http: HttpClient,
    private systemService: SystemService,
    private modalService: NzModalService,
  ) {
    this.validateFormQuery = this.fb.group({
      queryMenuName: [null],
      pcMenu: [null],
    });
    this.validateFormEdit = this.fb.group({
      menuType: [null, [Validators.required]],
      menuName: [null, [Validators.required]],
      showOnMobile: [null, [Validators.required]],
      menuUrl: null,
      menuMobileUrl: null,
      menuSort: [null, [Validators.required]],
      menuDesc: null,
      menuUrlImg: null,
      parentMenuName: null
    });

  }

  ngOnInit() {
    this.getMenuTree();
  }

  /** 构建菜单树 start */
  // 查询菜单树
  getMenuTree() {
    this.loadingSearch = true;

    let showOnMobile = 0;
    if (this.pcMenu === false) {
      showOnMobile = 1;
    }
    this.systemService.findAllMenuTree(showOnMobile, data => {
        this.menuTree = data['return_data'];
        this.buildMenuTree(this.menuTree);
    });
  }

  // 构建菜单树
  buildMenuTree(treeData) {
    const that = this;

    $('#menu-tree').treeview({
      data: treeData,
      levels: 0,
      showCheckbox: false,
      showBorder: false,
      onNodeSelected(event, data) {
        that.onNodeSelected(data);
      },
      onNodeUnselected(event, data) {
        that.clearDataArea();
      }

    });

    this.loadingSearch = false;
  }

  // 选中节点
  onNodeSelected(data) {
    this.delAble = true;
    this.updateType = 'update';

    this.loadingSearchDetail = true;

    this.systemService.findMenuById(data.id, res => {
        this.menu = res['return_data'];

        // 是否为手机菜单
        if (this.menu.showOnMobile === 1) {
            this.menu.showOnMobile = true;
        } else {
            this.menu.showOnMobile = false;
        }

        // 设置父级菜单名称
        let parentNode = null;
        if (data.parentId != null) {
            parentNode = $('#menu-tree').treeview('getNode', data.parentId);

            this.parentMenuName = parentNode.text;
        } else {
            this.parentMenuName = '无';
        }
        this.loadingSearchDetail = false;
    });
  }

  /** 构建菜单树 end */

  /** 图片上传 start */
  handleChange(info: any): void {
    this.loadingImg = true;
    if (info.file.response == null) {
      return;
    }
    this.loadingImg = false;
    if (info.file.response['return_code'] === '000000') {
      this.menu.menuUrlImg = info.file.response['return_data'][0];
    } else {
      this.message.create('error', `上传失败！`);
    }
  }
  /** 图片上传 end */

  /** 按钮事件 start */
  // 搜索
  onSearch() {
    const queryMenuName = this.validateFormQuery.value.queryMenuName;

    if (queryMenuName != null && queryMenuName !== '') {
      $('#menu-tree').treeview('search', [ queryMenuName, { ignoreCase: false, exactMatch: false }, 'text']);
    } else {
      $('#menu-tree').treeview('clearSearch');
      $('#menu-tree').treeview('collapseAll', { silent: true });
    }
  }

  // 增加按钮-验证父级菜单
  onClickAdd() {
    this.delAble = false;
    this.updateType = 'add';
    this.menu = {
      id: null,
      menuPSid: null,
      menuType: null,
      menuName: null,
      menuUrl: null,
      showOnMobile: false,
      menuMobileUrl: null,
      menuUrlImg: null,
      menuSort: null,
      menuDesc: null
    };

    const selectedMenu = $('#menu-tree').treeview('getSelected');
    if (selectedMenu.length === 0) {
      this.parentMenuName = '无';
    } else if (selectedMenu.length === 1) {
      this.menu.menuPSid = selectedMenu[0].id;
      this.parentMenuName = selectedMenu[0].text;
    } else {
      this.updateType = 'default';
      this.clearDataArea();
      this.message.create('warning', `只可选择一个节点作为父节点！`);
      // return;    // 若后面增加语句, 此处需增加return
    }
  }

  // 增加、修改
  onCommit(requestType): void {
    // tslint:disable-next-line:forin
    for (const i in this.validateFormEdit.controls) {
      this.validateFormEdit.controls[i].markAsDirty();
      this.validateFormEdit.controls[i].updateValueAndValidity();
    }

    if (this.menu.menuType == null || this.menu.menuType === '') {
      this.message.create('warning', `请选择菜单类型！`);
      return;
    } else if (this.menu.menuName == null || this.menu.menuName === '') {
      this.message.create('warning', `请输入菜单名称！`);
      return;
    } else if (this.menu.showOnMobile == null || this.menu.showOnMobile === '') {
      this.message.create('warning', `请选择是否手机菜单！`);
      return;
    } else if (this.menu.showOnMobile === false && (this.menu.menuUrl == null || this.menu.menuUrl === '')) {
      this.message.create('warning', `请输入菜单路由！`);
      return;
    }  else if (this.menu.showOnMobile === true && (this.menu.menuMobileUrl == null || this.menu.menuMobileUrl === '')) {
      this.message.create('warning', `请输入菜单路由！`);
      return;
    }  else if (this.menu.menuSort == null || this.menu.menuSort === '') {
      this.message.create('warning', `请输入菜单顺序！`);
      return;
    }

    let requestUrl = null;
    if (requestType === 'add') {
      requestUrl = '/secMenu/addMenu';
    } else if (requestType === 'update') {
      requestUrl = '/secMenu/editMenu';
    } else {
      return;
    }
    const params = {
      id: this.menu.id,
      menuPSid: this.menu.menuPSid,
      menuType: this.menu.menuType,
      menuName: this.menu.menuName,
      menuUrl: this.menu.menuUrl,
      showOnMobile: this.menu.showOnMobile,
      menuMobileUrl: this.menu.menuMobileUrl,
      menuUrlImg: this.menu.menuUrlImg,
      menuSort: this.menu.menuSort,
      menuDesc: this.menu.menuDesc
    };
    if (this.menu.showOnMobile === true) {
      params.showOnMobile = 1;
    } else {
      params.showOnMobile = 0;
    }

    this.loadingSearchDetail = true;
    this.http.post(this.WEB_SERVE_URL + requestUrl, params).subscribe(data => {
      if (data['return_code'] === '000000') {
        this.message.create('success', `提交成功！`);

        this.getMenuTree();
        this.clearDataArea();
      } else {
        this.message.create('warning', data['return_msg']);
      }

      setTimeout(() => {
        this.loadingSearchDetail = false;
      }, 1000);
    }, error => {
      this.loadingSearchDetail = false;
      this.message.create('error', `未知错误！`);
    });
  }

  // 删除
  // 對話框删除
  showDeleteConfirm(): void {
    this.modalService.confirm({
      nzTitle: '确定删除',
      nzOkText: '是',
      nzOnOk: () => this.onDelete(this.menu.id),
      nzCancelText: '否',
    });
  }

  onDelete(id) {
    if (id == null || id === '') {
      return;
    }

    this.loadingSearchDetail = true;
    this.systemService.deleteMenu(id, data => {
        if (data['return_code'] === '000000') {
            this.message.create('success', `删除成功！`);

            this.getMenuTree();
            this.clearDataArea();
        } else {
            this.message.create('error', data['return_msg']);
            this.loadingSearchDetail = false;
        }
    });
  }

  // 清除页面显示数据
  clearDataArea() {
    this.validateFormEdit.reset();

    this.delAble = false;
    this.updateType = 'default';

    this.menu = {
      id: null,
      menuPSid: null,
      menuType: null,
      menuName: null,
      menuUrl: null,
      showOnMobile: false,
      menuMobileUrl: null,
      menuUrlImg: null,
      menuSort: null,
      menuDesc: null
    };
    this.parentMenuName = null;
  }

  // 切换PC、手机菜单
  onClickMenuSwitch() {
    this.clearDataArea();

    this.getMenuTree();
  }
  /** 按钮事件 end */

}
