import { Component, Input, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { NzSpaceModule } from 'ng-zorro-antd/space';
import { CommonCompModule } from '../../../services/common.modules';
import { NzTabsModule } from 'ng-zorro-antd/tabs';
import { ActivatedRoute, Router } from '@angular/router';
import { NzAvatarModule } from 'ng-zorro-antd/avatar';
import { NzDropDownModule } from 'ng-zorro-antd/dropdown';
import { NzPopoverModule } from 'ng-zorro-antd/popover';
import { NzTagModule } from 'ng-zorro-antd/tag';
import { NzModalModule } from 'ng-zorro-antd/modal';
import { NzMessageService } from 'ng-zorro-antd/message';
import { textbookServer } from '../../../services/textbook';
import { NzRadioModule } from 'ng-zorro-antd/radio';
import Parse from 'parse';
import { NzImageService } from 'ng-zorro-antd/image';
import { NzImageModule } from 'ng-zorro-antd/image';

@Component({
  selector: 'app-user-edit',
  templateUrl: './user-edit.component.html',
  styleUrls: ['./user-edit.component.scss'],
  imports: [
    CommonModule,
    NzSpaceModule,
    CommonCompModule,
    NzTabsModule,
    NzAvatarModule,
    NzDropDownModule,
    NzPopoverModule,
    NzTagModule,
    NzModalModule,
    NzRadioModule,NzImageModule
  ],
  standalone: true,
})
export class UserEditComponent implements OnInit {
  inputValue: string = `
  async function pipe(user, context, callback) {
    if (context.connection === "weibo") {
      return callback(new Error("当前系统禁止使用微博登录！"))
    }
    callback(null, user, context)
  }`;
  isVisible: boolean = false;
  user: Parse.Object | any;
  profile: Parse.Object | any;
  password: string = '';
  edit: boolean = false; //编辑权限

  //可编辑
  userDataJson: any = {
    companyType: '',
    department: null,
  };
  parentMap: Array<any> = [];
  parentList: Array<any> = []; //单位列表
  isShowModal: boolean = false;
  searchValue: string = ''; //搜索部门内容
  unitTypes: Array<any> = [];

  constructor(
    public tbookSer: textbookServer,
    private activeRoute: ActivatedRoute,
    private router: Router,
    private message: NzMessageService,
    private nzImageService: NzImageService
  ) {}

  ngOnInit() {
    this.activeRoute.paramMap.subscribe(async (params) => {
      let id = params.get('id');
      console.log(id);
      if (id) {
        let query = new Parse.Query('_User');
        query.include('department');
        this.user = await query.get(id);
        let queryProfile = new Parse.Query('Profile');
        queryProfile.equalTo('user', id);
        this.profile = await queryProfile.first();
        this.userDataJson = {
          companyType: this.profile?.get('companyType'),
          department: this.user.get('department'),
        };
      }
      let arr = ['教师', '评审专家', '高校联系人'];
      if (
        this.tbookSer.profile.identity == '国家级管理员' ||
        (this.tbookSer.profile.identity == '工作联系人' &&
          arr.includes(this.profile.identity)) ||
        (this.tbookSer.profile.identity == '高校联系人' &&
          this.profile.identity == '教师')
      ) {
        this.edit = true;
      }
    });
  }
  async updateUser(type: string) {
    console.log(type);
    if (!this.edit) {
      this.message.warning('同级身份暂无权限操作');
      return;
    }
    switch (type) {
      case '已认证':
        this.user.set('accountState', '已认证');
        Parse.Cloud.run('aliSmsSend',{
          "mobileList": [this.user?.get('phone')],"templateCode":"SMS_468870790","params":{},"signName":"普通高等教育教材网"
        })
        break;
      case '已禁用':
        this.user.set('accountState', '已禁用');
        break;
      case '删除':
        this.user.set('isDeleted', true);
        break;
    }
    await this.user.save();
    this.ngOnInit();
  }
  async handleOk() {
    if (!this.edit) {
      this.message.warning('同级身份暂无权限操作');
      return;
    }
    this.password = this.password.trim();
    if (!this.password) {
      this.message.warning('密码格式错误');
      return;
    }
    try {
      this.user.set('password', this.password);
      await this.user.save();
      this.ngOnInit();
    } catch (err) {
      this.message.warning('保存出错，请注意密码格式');
    }
    this.isVisible = false;
  }
  //选择部门
  async showModalDepart() {
    if (!this.edit) {
      this.message.warning('同级身份暂无权限操作');
      return;
    }
    if(this.unitTypes.length == 0){
     await this.getUnitTypes()
    }
    let parent = this.unitTypes.find(
      (item) => item.name == this.userDataJson.companyType
    );
    if (parent?.id) {
      this.parentMap = await this.formatNode(parent.id);
    }
    this.provinceChange(this.parentMap[this.parentMap.length - 1]?.id);
    this.isShowModal = true;
  }
  async getUnitTypes() {
    let query = new Parse.Query('Department');
    query.equalTo('branch', undefined);
    query.equalTo('parent', undefined);
    query.notEqualTo('isDeleted', true);
    query.select('name');
    let r = await query.find();
    r.forEach((item) => {
      this.unitTypes.push({ id: item.id, name: item.get('name') });
    });
  }
  //根据所选单位类型获取对应单位
  async provinceChange(id?: string, val?: string) {
    let query = new Parse.Query('Department');
    query.select('name', 'branch', 'parent');
    if (this.tbookSer.profile.identity != '国家级管理员') {
      query.equalTo(
        'objectId',
        this.tbookSer.profile?.user.department?.objectId
      );
    }
    if (this.tbookSer.profile.identity == '国家级管理员' || id) {
      query.equalTo('parent', id ? id : null);
    }
    query.limit(100);
    val && query.contains('name', val);
    let r = await query.find();
    this.parentList = r;
  }

  async formatNode(id: string): Promise<Array<any>> {
    let arr = [];
    if (id) {
      let query = new Parse.Query('Department');
      query.equalTo('objectId', id);
      query.select('parent', 'name');
      let r = await query.first();
      arr.push({
        title: r?.get('name'),
        id: r?.id,
      });
      if (r?.get('parent')) {
        arr.unshift(...(await this.formatNode(r?.get('parent')?.id)));
      }
    }
    return arr;
  }
  onCheck(e: any) {
    console.log(e);
    this.userDataJson.department = undefined
    this.provinceChange();
  }
  parent:string = '' //搜索时传入的id
  //选择部门
  async onCheckedDepart(e: any) {
    console.log(e);
    if (e?.get('parent')?.id) {
      this.userDataJson.department = e;
      this.parent = e?.get('parent')?.id
    } else {
      this.provinceChange(e.id);
      this.parent = e?.id
    }
    this.parentMap = await this.formatNode(e.id);
  }
  handleCancel(): void {
    console.log('Button cancel clicked!');
    this.userDataJson = {
      companyType: this.profile?.get('companyType'),
      department: this.user.get('department'),
    };
    this.isShowModal = false;
    this.parent = ''
  }
  async completeChange(): Promise<void> {
    if(!this.userDataJson.department?.id){
      this.message.warning('请选择部门')
      return
    }
    this.userDataJson.companyType = this.userDataJson.department.get('branch');
    this.profile?.set('companyType', this.userDataJson.companyType)
    await this.profile?.save()
    this.user?.set('department', this.userDataJson.department?.toPointer())
    await this.user?.save()
    this.ngOnInit()
    this.isShowModal = false;
    this.parent = ''
  }
  openUrl(url:string){
    if (!/\.(jpg|jpeg|png|GIF|JPG|PNG)$/.test(url)) {
      window.open(url);
    } else {
      let images = [
        {
          src: url,
          width: '200px',
          height: '200px',
          alt: 'ng-zorro'
        },
      ]
      this.nzImageService.preview(images, { nzZoom: 1.5, nzRotate: 0 });
    }
  }
}
