import { Component } from '@angular/core';
import {FormGroup, NonNullableFormBuilder, ReactiveFormsModule, Validators} from "@angular/forms";
import {NzMessageService} from "ng-zorro-antd/message";
import {NzModalComponent, NzModalModule, NzModalService} from "ng-zorro-antd/modal";
import {DatePipe, NgForOf, NgIf} from "@angular/common";
import {NzButtonComponent} from "ng-zorro-antd/button";
import {NzColDirective, NzRowDirective} from "ng-zorro-antd/grid";
import {NzDividerComponent} from "ng-zorro-antd/divider";
import {NzFlexDirective} from "ng-zorro-antd/flex";
import {NzFormControlComponent, NzFormDirective, NzFormItemComponent, NzFormLabelComponent} from "ng-zorro-antd/form";
import {NzInputDirective} from "ng-zorro-antd/input";
import {
  NzTableCellDirective,
  NzTableComponent, NzTableModule,
  NzTbodyComponent,
  NzTheadComponent,
  NzThMeasureDirective, NzTrDirective
} from "ng-zorro-antd/table";
import {NzTreeComponent} from "ng-zorro-antd/tree";
import {NzOptionComponent, NzSelectComponent} from "ng-zorro-antd/select";
import {NzDropDownModule} from "ng-zorro-antd/dropdown";
import {NzIconDirective} from "ng-zorro-antd/icon";
import {DictionaryPipe} from "../../../pipes/common/dictionary.pipe";
import {Dictionary} from "../../../data/common/dictionary.namespace";
import {SysAccountService} from "../../../services/account/sys-account.service";
import {RoleService} from "../../../services/role/role.service";

@Component({
  selector: 'app-sys-account',
  standalone: true,
  imports: [
    DatePipe,
    NgForOf,
    NgIf,
    NzButtonComponent,
    NzColDirective,
    NzDividerComponent,
    NzFlexDirective,
    NzFormControlComponent,
    NzFormDirective,
    NzFormItemComponent,
    NzFormLabelComponent,
    NzInputDirective,
    NzModalComponent,
    NzRowDirective,
    NzTableCellDirective,
    NzTableComponent,
    NzTbodyComponent,
    NzThMeasureDirective,
    NzTheadComponent,
    NzTrDirective,
    NzTreeComponent,
    ReactiveFormsModule,
    NzTableModule,
    NzModalModule,
    NzSelectComponent,
    NzOptionComponent,
    NzDropDownModule,
    NzIconDirective,
    DictionaryPipe,
  ],
  templateUrl: './sys-account.component.html',
  styleUrl: './sys-account.component.less'
})
export class SysAccountComponent {
  // 表单页数
  tablePageNum = 1;
  // 表单数据
  tableData: any = {
    total: 0,
    list: [],
  };
  accountStatus: Dictionary[] = []
  // 角色数据
  roleData: any = [];
  // 搜索表单
  searchForm: FormGroup;
  // 编辑账户弹出框
  editAccountVisible = false;
  // 编辑账户表单
  editAccountForm: FormGroup;
  // 编辑账户标题
  editAccountTitle = '';

  constructor(private fb: NonNullableFormBuilder,
              private sysAccountService: SysAccountService,
              private roleService: RoleService,
              private message: NzMessageService,
              private modal: NzModalService) {
    // 初始化搜索框
    this.searchForm = this.fb.group({
      userName: [''],
      loginName: [''],
      telephone: [''],
      status: [''],
    });

    // 初始化账户表单
    this.editAccountForm = this.fb.group({
      id: [''],
      userName: ['', [Validators.required]],
      loginName: ['', [Validators.required]],
      telephone: [''],
      roleId: ['', [Validators.required]],
    });
    this.accountStatus = new DictionaryPipe().getDictionaryList("SEC_USER_STATUS");
    this.queryAllRole();
    this.queryData();
  }

  /**
   * 获取角色
   */
  queryAllRole() {
    this.roleService.queryAllRole((data: any) => {
      if (data['return_code'] == '000000') {
        this.roleData = data['return_data'];
      }
    });
  }

  /**
   * 获取数据
   */
  queryData() {
    this.searchForm.value.pageNum = this.tablePageNum;
    this.searchForm.value.pageSize = 10;
    this.searchForm.value.objectType = 1;
    this.searchForm.value.time = new Date().getTime();
    this.sysAccountService.queryList(this.searchForm.value, (data: any) => {
      if (data['return_code'] == '000000') {
        this.tableData = data['return_data'];
      }
    });
  }

  /**
   * 搜索表单提交
   */
  searchFormSubmit(): void {
    this.tablePageNum = 1;
    this.queryData();
  }

  /**
   * 搜索表单重置
   */
  searchFormReset(): void {
    this.searchForm.reset();
  }

  /**
   * 打开编辑账户模态框
   * @param edit 编辑荒唐 true:增加  false:修改
   * @param data
   */
  showEditAccount(edit: boolean, data: any) {
    if (edit) {
      this.editAccountTitle = '创建账户';
    } else {
      this.editAccountTitle = '修改账户';
      data['roleId'] = ""+data['roleId']
      this.editAccountForm.patchValue(data);
    }
    this.editAccountVisible = true;
  }

  /**
   * 提交表单
   */
  submitEditAccountForm() {
    if (this.editAccountForm.valid) {
      this.sysAccountService.editUser(this.editAccountForm.value, (data: any) => {
        if (data['return_code'] == '000000') {
          // 刷新数据
          this.queryData();

          this.message.create('success', '操作成功');

          // 关闭弹窗
          this.closeEditAccount();
        } else {
          this.message.create('error', data['return_msg']);
        }
      });
    } else {
      Object.values(this.editAccountForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }

  /**
   * 关闭编辑账户模态框
   */
  closeEditAccount() {
    this.editAccountForm.reset();
    this.editAccountVisible = false;
  }

  /**
   * 打开禁用账户确认框
   */
  showRestore(dataId: number) {
    this.modal.confirm({
      nzTitle: '提示',
      nzContent: '确定恢复账户状态?',
      nzOnOk: () => this.restore(dataId)
    });
  }

  /**
   * 恢复
   */
  restore(dataId: number) {
    const param = {
      userId: dataId
    }
    this.sysAccountService.restore(param, (data: any) => {
      if (data['return_code'] == '000000') {
        // 刷新数据
        this.queryData();
        this.message.success("操作成功");
      } else {
        this.message.create('error', data['return_msg']);
      }
    });
  }

  /**
   * 打开禁用账户确认框
   */
  showDisable(dataId: number) {
    this.modal.confirm({
      nzTitle: '提示',
      nzContent: '确定禁用账户吗?禁用后无法登录!',
      nzOnOk: () => this.disable(dataId)
    });
  }

  /**
   * 禁用
   */
  disable(dataId: number) {
    const param = {
      userId: dataId
    }
    this.sysAccountService.disable(param, (data: any) => {
      if (data['return_code'] == '000000') {
        // 刷新数据
        this.queryData();
        this.message.success("操作成功");
      } else {
        this.message.create('error', data['return_msg']);
      }
    });
  }

  /**
   * 打开密码重置确认框
   */
  showResetPwd(dataId: number) {
    this.modal.confirm({
      nzTitle: '提示',
      nzContent: '确定重置账户登录密码吗?',
      nzOnOk: () => this.resetPwd(dataId)
    });
  }

  /**
   * 密码重置
   */
  resetPwd(dataId: number) {
    const param = {
      userId: dataId
    }
    this.sysAccountService.resetPwd(param, (data: any) => {
      if (data['return_code'] == '000000') {
        // 刷新数据
        this.queryData();
        this.modal.success({
          nzTitle: '提示',
          nzContent: '密码重置成功,新密码:123456'
        });
      } else {
        this.message.create('error', data['return_msg']);
      }
    });
  }

  /**
   * 展示删除数据
   */
  showDelData(dataId: number) {
    this.modal.confirm({
      nzTitle: '提示',
      nzContent: '确定删除该账户数据?',
      nzOnOk: () => this.delData(dataId)
    });
  }

  /**
   * 删除数据
   */
  delData(dataId: number) {
    const param = {
      userId: dataId
    }
    this.sysAccountService.delete(param, (data: any) => {
      if (data['return_code'] == '000000') {
        // 刷新数据
        this.queryData();
        this.message.create('success', '操作成功');
      } else {
        this.message.create('error', data['return_msg']);
      }
    });
  }
}