import {Component, OnInit} from '@angular/core';
import { BsModalRef } from 'ngx-bootstrap/modal';
import {CookieService} from 'ngx-cookie-service';
import { AjaxService } from '../../../../core/service/ajax.service';
import { MsgService } from '../../../../core/service/msg.service';
import { FrameDetailComponent } from '../../../frame/core/detail/frame.detail';

@Component({
  selector: 'app-weixin-menu-view',
  templateUrl: './weixin-menu-view.component.html',
  styleUrls: ['./weixin-menu-view.component.scss']
})
export class WeixinMenuViewComponent extends FrameDetailComponent implements OnInit {

  menu_json: any;
  menu_id = '';
  matchrule : any;
  matchrule_flag = false;
  serverMenu: any;
  constructor(bsModalRef: BsModalRef, private cookies: CookieService) {
    super(bsModalRef);
    this.matchrule = {};
  }

  ngOnInit() {
  }

  initDefautEntity() {
    this.menu_json = JSON.stringify(this.currentEntity, null, 2);
    console.log(this.serverMenu);
    // if (this.serverMenu !== und)
  }

  uploadMenu() {
    const obj = Object.assign({}, this.currentEntity);
    if (this.matchrule_flag === true) {
      obj.matchrule = this.matchrule;
    }
    const fn = () => {
      AjaxService.request('weixin/menu/upload.htm', {
        wx_id: this.cookies.get('CurrentWxId'),
        json_value: JSON.stringify(obj)
      }, () => {
        MsgService.successAlert('微信菜单已更新到服务器，如微信无变化，请退出该公众中重新进入，部分手机有5分钟延迟');
        this.closeWindow();
      }, {RequestWithLoading: true});
    };

    MsgService.confirmAlert('确定要将微信菜单上传到服务器上吗？将覆盖现有菜单，且实时生效，请谨慎进行此操作！', fn);
  }

  changeJsonValue() {
    this.currentEntity = JSON.parse(this.menu_json);
  }

  chooseMenu($event) {
    if(this.menu_id === '') {
      this.currentEntity = this.serverMenu.menu;
      this.matchrule_flag = false;
    } else {
      for (const m of this.serverMenu.conditionalmenu) {
        if ((m.menuid + '') === (this.menu_id + '')) {
          this.currentEntity = m;
          this.matchrule_flag = true;
          this.matchrule = m.matchrule;
        }
      }
    }
    this.menu_json = JSON.stringify(this.currentEntity, null, 2);
  }

  /*******************
   * 删除个性化菜单
   */
  deleteMenu() {
    MsgService.confirmAlert('确定要删除该个性化菜单吗？不可恢复，请谨慎进行此操作！', () => {
      AjaxService.request('weixin/menu/delete.htm', {
        wx_id: this.cookies.get('CurrentWxId'),
        menu_id: this.menu_id
      }, () => {
        MsgService.successAlert('个性化菜单已删除，如微信无变化，请退出该公众中重新进入，部分手机有5分钟延迟');
        this.closeWindow();
      });
    });
  }

}
