import { Component } from '@angular/core';
import {
  FormsModule,
  ReactiveFormsModule,
  UntypedFormBuilder,
  UntypedFormControl,
  UntypedFormGroup,
  Validators
} from "@angular/forms";
import {NzOptionComponent, NzSelectComponent} from "ng-zorro-antd/select";
import {
  NzFormControlComponent,
  NzFormDirective,
  NzFormItemComponent,
  NzFormLabelComponent,
  NzFormModule
} from "ng-zorro-antd/form";
import {NzModalComponent, NzModalModule, NzModalService} from "ng-zorro-antd/modal";
import {NzInputDirective, NzInputGroupComponent} from "ng-zorro-antd/input";
import {NzColDirective, NzRowDirective} from "ng-zorro-antd/grid";
import {BreadcrumbComponent} from "../common/breadcrumb/breadcrumb.component";
import {DatePipe, NgForOf, NgIf} from "@angular/common";
import {NzButtonComponent} from "ng-zorro-antd/button";
import {NzIconDirective} from "ng-zorro-antd/icon";
import {
  NzCellFixedDirective,
  NzTableComponent, NzTableModule,
  NzTdAddOnComponent,
  NzThMeasureDirective,
  NzThSelectionComponent
} from "ng-zorro-antd/table";
import {MerStatusPipe} from "../../pipes/mer/mer-status.pipe";
import {CompleteStatusPipe} from "../../pipes/mer/complete-status.pipe";
import {NzDropDownDirective, NzDropdownMenuComponent} from "ng-zorro-antd/dropdown";
import {NzMenuDirective, NzMenuItemComponent, NzSubMenuComponent} from "ng-zorro-antd/menu";
import {Router, RouterLink, RouterOutlet} from "@angular/router";
import {NzTabComponent, NzTabSetComponent} from "ng-zorro-antd/tabs";
import {NzUploadComponent} from "ng-zorro-antd/upload";
import {MerTypePipe} from "../../pipes/mer/mer-type.pipe";
import {NzTooltipDirective} from "ng-zorro-antd/tooltip";
import {LoginService} from "../../services/login.service";
import {NzMessageService} from "ng-zorro-antd/message";
import {CommonsService} from "../../services/commons.service";
import {IconService} from "../../services/icon.service";
import {HttpClient} from "@angular/common/http";
import {ValidatorsService} from "../../services/validators.service";
import {
  ADMIN_INFO_OBJECT,
  CHILDMENUNAME,
  INIT_FLAG,
  MENUNAME, ROLE_TYPE,
  ROUTENAME,
  TOKEN
} from "../../services/local-storage.namespace";
import {environment} from "../../../environments/environment";
import {
  NzContentComponent,
  NzHeaderComponent,
  NzLayoutComponent,
  NzLayoutModule,
  NzSiderComponent
} from "ng-zorro-antd/layout";
import {NzDrawerComponent, NzDrawerModule} from "ng-zorro-antd/drawer";
import {NzSwitchComponent} from "ng-zorro-antd/switch";
import {BrowserStorageService} from "../../utils/localStorage.service";
import {NzSpinModule} from "ng-zorro-antd/spin";
import {NzRadioComponent, NzRadioGroupComponent} from "ng-zorro-antd/radio";
import {NzDatePickerModule} from "ng-zorro-antd/date-picker";

@Component({
  selector: 'app-navigation',
  standalone: true,
  imports: [
    NzOptionComponent,
    NzFormDirective,
    NzModalComponent,
    NzFormItemComponent,
    NzFormLabelComponent,
    NzFormControlComponent,
    NzSelectComponent,
    NzInputDirective,
    NzColDirective,
    BreadcrumbComponent,
    NzRowDirective,
    ReactiveFormsModule,
    NgForOf,
    NzButtonComponent,
    NzIconDirective,
    NzTableComponent,
    NzThMeasureDirective,
    NzThSelectionComponent,
    NzTdAddOnComponent,
    MerStatusPipe,
    CompleteStatusPipe,
    DatePipe,
    NzDropdownMenuComponent,
    NzMenuDirective,
    RouterLink,
    NgIf,
    NzMenuItemComponent,
    NzTabSetComponent,
    NzTabComponent,
    NzUploadComponent,
    MerTypePipe,
    NzCellFixedDirective,
    NzDropDownDirective,
    NzTooltipDirective,
    NzSubMenuComponent,
    NzSiderComponent,
    NzLayoutComponent,
    NzHeaderComponent,
    NzContentComponent,
    RouterOutlet,
    NzDrawerComponent,
    NzSwitchComponent,
    FormsModule,
    NzInputGroupComponent,
    NzModalModule,
    NzTableModule,
    NzFormModule,
    NzSpinModule,
    NzRadioGroupComponent,
    NzRadioComponent,
    NzDatePickerModule,
    NzLayoutModule,
    NzDrawerModule
  ],
  templateUrl: './navigation.component.html',
  styleUrl: './navigation.component.less'
})
export class NavigationComponent {
  visibleUpdatePwd = false;  // 修改密码抽屉
  validateForm: UntypedFormGroup; // 定义表单
  passwordVisible = false;

  isCollapsed = false;
  userInfo: any;
  menuList: any;
  routeName: string;
  switchValue = false;
  constructor(
    private storage: BrowserStorageService,
    private loginService: LoginService,
    private message: NzMessageService,
    private commonsService: CommonsService,
    private iconService: IconService,
    private http: HttpClient, // http请求
    private modal: NzModalService,
    private fb: UntypedFormBuilder, // 表单
    private router: Router,
  ) { }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      oldPassword: [null, [Validators.required, ValidatorsService.minLength(6), ValidatorsService.maxLength(16)]],
      newPassword: [null, [Validators.required, ValidatorsService.minLength(6), ValidatorsService.maxLength(16)]],
      checkNewPassword: [null, [Validators.required, this.checkPwd]],
    });
    this.routeName = this.storage.get(ROUTENAME) == null ? 'index' : this.storage.get(ROUTENAME);
    this.userInfo = this.storage.get(ADMIN_INFO_OBJECT);
    this.menuList = this.storage.get(ADMIN_INFO_OBJECT)['menuList']; // 定义菜单数据
  }

  public activeLi(routeName): void {
    this.routeName = routeName;
    this.storage.set(ROUTENAME, routeName);
  }

  // 菜单姓名
  public getRouteName(menuName , childMenuName): void {
    this.storage.set(MENUNAME, menuName);
    this.storage.set(CHILDMENUNAME, childMenuName);
  }

  // 登出
  public loginOut(): void {
    this.loginService.loginOut(data => {
      if (data.return_code === '000000') {
        this.storage.set(ADMIN_INFO_OBJECT, null);
        this.storage.set(INIT_FLAG, false);
        this.storage.set(TOKEN, null);

        const roleType = this.storage.get(ROLE_TYPE);
        this.router.navigateByUrl('/login').then();
        /*        if (roleType === 0) {
                  this.router.navigateByUrl('/login/admin').then();
                } else if (roleType === 2) {
                  this.router.navigateByUrl('/login/agent').then();
                } else if (roleType === 3) {
                  this.router.navigateByUrl('/login/salesman').then();
                } else if (roleType === 4) {
                  this.router.navigateByUrl('/login/merchant').then();
                } else {
                  this.router.navigateByUrl('/login/store').then();
                }*/
        this.storage.set(ROLE_TYPE, null);
      } else {
        this.message.warning(data.return_msg);
      }
    });
  }

  // 返回
  public getBack(): void {
    history.back();
  }

  clickSwitch(): void {
    this.switchValue = !this.switchValue;
    this.commonsService.updateDictionary('RECHARGE' , this.switchValue === true ? '1' : '0' , data => {
      if (data['return_code'] === '000000') {
        this.message.success(data['return_data']);
      } else {
        this.message.error(data['return_msg']);
      }
    });
  }


  // 打开抽屉
  openUpdatePwd(): void {
    this.visibleUpdatePwd = true;
  }

  // 关闭抽屉
  closeUser(): void {
    this.visibleUpdatePwd = false;
  }

  // 提交表单
  submitForm(value): void {
    // 表单验证
    // tslint:disable-next-line:forin
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    if (this.validateForm.status == null || this.validateForm.status !== 'VALID') {
      this.modal.info({
        nzTitle: '提示',
        nzContent: '请正确填写必填信息',
      });
      return;
    }
    const timeNum = new Date().getTime();
    const signStr = 'userId=' + this.storage.get(ADMIN_INFO_OBJECT)['secUser'].id + '&newPassword=' + value.newPassword + '&nonceStr=' + timeNum;
    // 定义请求数据
    const params = {
      userId: this.storage.get(ADMIN_INFO_OBJECT)['secUser'].id,
      oldPassword: value.oldPassword,
      password: value.newPassword,
      nonceStr: timeNum,
      //sign: String(Md5.hashStr(signStr)).toLocaleUpperCase(),
    };
    this.http.post(environment.baseUrl + '/secUser/sendUserPass', params).subscribe(data => {
      if (data['return_code'] === '000000') {
        this.modal.success({
          nzTitle: '提示',
          nzContent: '密码修改成功',
          nzOkText: '重新登录',
          nzOkType: 'primary',
          nzOnOk: () => this.loginOut()
        });
      } else {
        this.modal.warning({
          nzTitle: '提示',
          nzContent: data['return_msg'],
          nzOkText: '取消',
          nzOkType: 'primary',
        });
      }
      setTimeout(() => {
      }, 1000);
    }, error => {
      this.message.create('error', `未知错误！`);
    });
  }

  /**
   * 新密码校验两次密码是否一致
   * @param control
   */
  checkPwd = (control: UntypedFormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return { required: true };
    } else if (control.value !== this.validateForm.controls['newPassword'].value) {
      return { confirm: true, error: true };
    }
    return {};
  }
}
