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';
import { NzSelectModule } from 'ng-zorro-antd/select';
import { MatButtonModule } from '@angular/material/button';
import { provinces } from '../../../services/provinces';
import { NzModalService } from 'ng-zorro-antd/modal';
import { Observable, of } from 'rxjs';
@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,
    NzSelectModule,
    MatButtonModule,
  ],
  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> = [];
  userJson: any = {
    //user编辑数据
    email: '',
    phone: '',
    name: '',
    username: '',
  };
  profileJson: any = {
    //身份编辑数据
    identity: '',
    telephone: '',
    province: '',
    departmentName: '',
    postName: '',
    majorSubject: '',
  };
  userType: Array<string> = ['教师', '评审专家', '高校联系人', '工作联系人'];
  provinces: Array<string> = provinces.options; //省份
  depTitle: string = ''; //关联部门标题
  radio: string = '';

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

  goUserList() {
    switch (this.tbookSer.profile.identity) {
      case '国家级管理员':
        this.router.navigate(['/nav-admin/manage/user'], {
          queryParams: { page: this.route.snapshot.queryParamMap.get('page') },
        });
        break;
      default:
        history.back();
        break;
    }
  }
  ngOnInit() {
    // window.onbeforeunload = (event) => {
    //   (event || window.event).returnValue = '还未保存是否离开';
    // };
    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);
        this.userJson = this.user.toJSON();

        let queryProfile = new Parse.Query('Profile');
        queryProfile.equalTo('user', id);
        this.profile = await queryProfile.first();
        this.profileJson = this.profile.toJSON();
        this.userJson.email = this.profileJson.email;
        this.userDataJson = {
          companyType: this.profile?.get('companyType'),
          department: {
            id: this.user.get('department')?.id,
            name: this.user.get('department')?.get('name'),
            branch: this.user.get('department')?.get('branch'),
          },
          node: await this.tbookSer.formatNode(this.user.get('department')?.id),
        };
      }
      await this.getUnitTypes();
      let arr = ['教师', '评审专家', '高校联系人'];
      if (this.tbookSer.profile.identity == '国家级管理员') {
        this.edit = true;
      } else if (
        this.tbookSer.profile.identity == '工作联系人' &&
        arr.includes(this.profile.get('identity'))
      ) {
        if (
          this.tbookSer.profile.companyType == '省级教育行政部门' ||
          this.tbookSer.profile.companyType == '有关部门（单位）教育司（局）'
        ) {
          this.userType = ['教师', '评审专家', '高校联系人'];
        } else {
          this.userType = ['教师', '评审专家'];
        }
        this.edit = true;
      } else if (
        this.tbookSer.profile.identity == '高校联系人' &&
        this.profile.get('identity') == '教师'
      ) {
        this.userType = ['教师'];
        this.edit = true;
      }
    });
  }
  async updateUser(type: string) {
    console.log(type);
    if (!this.edit) {
      this.message.warning('同级身份暂无权限操作');
      return;
    }
    this.modal.confirm({
      nzTitle: '操作提示',
      nzContent: `确定${type}吗？`,
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: type == '删除' ? true : false,
      nzOnOk: async () => {
        switch (type) {
          case '已认证':
            if (!this.user?.get('department')?.id) {
              this.message.warning('该用户暂未绑定所属单位');
              return;
            }
            if (this.profile?.get('identity') == '工作联系人') {
              let auth = await this.tbookSer.updateProfileSubmitted(
                this.profile?.id,
                'save',
                this.user.get('department').id,
                this.message
              );
              if (!auth) return;
            }
            this.user.set('accountState', '已认证');
            Parse.Cloud.run('aliSmsSend', {
              mobileList: [this.user?.get('phone')],
              templateCode: 'SMS_468870790',
              params: {},
              signName: '普通高等教育教材网',
            });
            await this.user.save();
            break;
          case '已禁用':
            this.user.set('accountState', '已禁用');
            await this.user.save();
            break;
          case '删除':
            await this.profile.destroy();
            await this.user.destroy();
            this.goUserList();
            break;
        }
        this.ngOnInit();
      },
      nzCancelText: '取消',
      nzOnCancel: () => console.log('Cancel'),
    });
  }
  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;
  }
  //切换单位类型
  onChangeType() {
    this.userDataJson.department = null;
    this.depTitle = '';
    this.radio = '';
  }
  //选择部门
  async showModalDepart() {
    if (!this.edit) {
      this.message.warning('同级身份暂无权限操作');
      return;
    }
    this.depTitle = this.userDataJson.department.name;
    this.radio = this.userDataJson.department.id;
    if (this.unitTypes.length == 0) {
      await this.getUnitTypes();
    }
    this.parentMap = await this.tbookSer.formatNode(
      this.user?.get('department')?.id
    );
    let index = this.parentMap.findIndex(
      (item) => this.tbookSer.profile.user.department?.objectId == item.key
    );
    if (index != -1) {
      this.parentMap.forEach((item, i) => {
        if (i >= index) {
          this.parentMap[i].verify = true;
        }
      });
    }
    this.getDepart(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 getDepart(parent?: string, val?: string) {
    let query = new Parse.Query('Department');
    query.equalTo(
      'parent',
      val
        ? this.parentMap[this.parentMap.length - 1]?.key
        : parent
        ? parent
        : this.tbookSer.profile.identity != '国家级管理员'
        ? this.tbookSer.profile.user.department?.objectId
        : null
    );
    query.select('code', 'name', 'branch', 'parent', 'type', 'hasChildren');
    query.limit(100);
    query.descending('createdAt');
    query.notEqualTo('isDeleted', true);
    val && query.contains('name', val);
    let res = await query.find();
    let nodes: any = [];
    res.forEach((item) => {
      nodes.push({
        title: item.get('name'),
        key: item.id,
        id: item.id,
        branch: item.get('branch'),
        parent: item.get('parent')?.id, //上级
        isLeaf: !item.get('hasChildren'), //是否是最下级
        type: item.get('type'),
      });
    });
    this.parentList = nodes;
  }
  async onPre(data?: any, index?: number) {
    if (!data) {
      this.userDataJson.department = undefined;
      this.depTitle = '';
      this.radio = '';
      await this.getDepart();
      this.parentMap = [];
      return;
    }
    if (index == this.parentMap.length - 1) {
      if (this.parentList.length == 0) await this.getDepart(data?.key);
      return;
    }
    this.parentMap.splice((index || 0) + 1);
    this.userDataJson.department = undefined;
    this.depTitle = '';
    this.radio = '';
    await this.getDepart(data?.key);
  }
  //选择部门
  async onCheckedDepart(e: any, checked?: boolean) {
    console.log(e, checked);
    this.userDataJson.department = null;
    this.depTitle = '';
    this.parentMap = await this.tbookSer.formatNode(e.id);
    if (this.tbookSer.profile.identity != '国家级管理员') {
      let index = this.parentMap.findIndex(
        (item) => this.tbookSer.profile.user.department?.objectId == item.key
      );
      if (index != -1) {
        this.parentMap.forEach((item, i) => {
          if (i >= index) {
            this.parentMap[i].verify = true;
          }
        });
      }
    }
    if (checked && e.branch) {
      this.pushValue(e);
      return;
    }
    if (e.isLeaf) {
      return;
    }
    this.radio = '';
    await this.getDepart(e?.key);
  }
  pushValue(e: any) {
    this.userDataJson.department = {
      name: e.title,
      branch: e.branch,
      title: e.title,
      id: e.key,
    };
    this.depTitle = e.title;
    console.log(this.depTitle);
    this.radio = e.key;
    if (this.tbookSer.profile.identity == '国家级管理员') {
      this.userType = this.unitTypes.some((item) => e.parent == item.id)
        ? !e.type
          ? ['工作联系人']
          : ['评审专家', '工作联系人', '教师']
        : e.type == '单位'
        ? ['评审专家', '高校联系人', '教师']
        : ['评审专家', '教师'];
    } else if (this.tbookSer.profile.identity == '工作联系人') {
      this.userType = this.unitTypes.some((item) => e.parent == item.id)
        ? !e.type
          ? ['评审专家', '教师', '高校联系人']
          : ['评审专家', '教师']
        : e.type == '单位'
        ? ['评审专家', '高校联系人', '教师']
        : ['评审专家', '教师'];
    }
  }

  async handleCancel() {
    this.userDataJson = {
      companyType: this.profile?.get('companyType'),
      department: {
        id: this.user.get('department')?.id,
        name: this.user.get('department')?.get('name'),
        branch: this.user.get('department')?.get('branch'),
      },
      node: await this.tbookSer.formatNode(this.user.get('department')?.id),
    };
    this.depTitle = '';
    this.radio = '';
    this.isShowModal = false;
  }
  async completeChange(): Promise<void> {
    if (!this.userDataJson.department?.id) {
      this.message.warning('请选择部门');
      return;
    }
    this.userDataJson.companyType = this.userDataJson.department?.branch;
    this.profile?.set('companyType', this.userDataJson.companyType);
    await this.profile?.save();
    this.user?.set('department', {
      __type: 'Pointer',
      className: 'Department',
      objectId: this.userDataJson.department?.id,
    });
    await this.user?.save();
    this.ngOnInit();
    this.isShowModal = false;
  }
  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 });
    }
  }
  /* 修改账号 */
  loading: boolean = false;
  async submitForm(type: string) {
    if (this.loading) return;
    this.loading = true;
    if (type == 'save') {
      this.updateUserJson();
    } else {
      this.userJson = this.user.toJSON();
      this.profileJson = this.profile.toJSON();
      this.userDataJson = {
        companyType: this.profile?.get('companyType'),
        department: {
          id: this.user.get('department')?.id,
          name: this.user.get('department')?.get('name'),
          branch: this.user.get('department')?.get('branch'),
        },
        node: await this.tbookSer.formatNode(this.user.get('department')?.id),
      };
      this.depTitle = this.user.get('department')?.get('name');
      this.radio = this.user.get('department')?.id;
      this.loading = false;
    }
  }
  async updateUserJson() {
    //修改用户数据
    console.log(this.userJson);
    console.log(this.profileJson);
    this.userJson.username = this.userJson?.username?.trim();
    this.userJson.email = this.userJson?.email?.trim();
    this.userJson.phone = this.userJson?.phone?.trim();
    this.userJson.name = this.userJson?.name?.trim();
    if (!(await this.authVrifly())) {
      this.loading = false;
      return;
    }
    try {
      this.user?.set('username', this.userJson?.username);
      this.user?.set('name', this.userJson?.name);
      this.user?.set('phone', this.userJson?.phone);
      this.userJson?.email && this.user?.set('email', this.userJson?.email);
      await this.user.save();

      this.profile?.set('companyType', this.userDataJson.companyType);
      this.profile?.set('email', this.userJson.email);
      this.profile?.set('identity', this.profileJson.identity);

      this.profile?.set('telephone', this.profileJson.telephone);
      this.profile?.set('province', this.profileJson.province);
      this.profile?.set('departmentName', this.profileJson.departmentName);
      this.profile?.set('postName', this.profileJson.postName);
      this.profile?.set('majorSubject', this.profileJson.majorSubject);

      await this.profile?.save();
      this.loading = false;
      this.modal.success({
        nzTitle: '修改成功',
        nzContent: '',
        nzOnOk: () => {},
      });
    } catch (err: any) {
      console.warn('添加用户错误', err);
      this.loading = false;
      this.message.error(
        err?.Error || '错误：请检查用户或邮箱及手机号是否已存在'
      );
      return;
    }
  }

  async authVrifly(): Promise<boolean | undefined> {
    this.userJson.username = this.userJson?.username?.trim();
    this.userJson.email = this.userJson?.email?.trim();
    this.userJson.phone = this.userJson?.phone?.trim();
    this.userJson.name = this.userJson?.name?.trim();
    if (
      !this.userJson?.username ||
      !this.userJson?.name ||
      !this.userJson.phone ||
      !this.userJson?.email
    ) {
      this.message.warning('请填写必填项');
      return;
    }
    if (!this.userDataJson?.department) {
      this.message.error('请选择所属部门');
      return;
    }
    if (!this.profileJson.identity) {
      this.message.error('请选择人员类型');
      return;
    }
    let a = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/;
    if (this.userJson.phone && !String(this.userJson.phone).match(a)) {
      this.message.error('请填写正确手机号');
      return;
    }
    let m =
      /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    if (!String(this.userJson.email).match(m)) {
      this.message.error('邮箱格式有误');
      return;
    }
    if (
      this.userJson.phone != this.user.get('phone') &&
      !(await this.tbookSer.userFind(this.userJson.phone))
    ) {
      this.message.error('手机号已存在');
      return;
    }
    return true;
  }
  //页面数据变化时
  vrifly: boolean = false;
  moduleChange(): Observable<boolean> {
    let a =
      this.userJson.username != this.user.get('username') ||
      this.userJson.name != this.user.get('name') ||
      this.userJson.email != this.profile.get('email') ||
      this.userJson.phone != this.user.get('phone');
    let b =
      this.profileJson.identity != this.profile.get('identity') ||
      this.profileJson.telephone != this.profile.get('telephone') ||
      this.profileJson.province != this.profile.get('province') ||
      this.profileJson.departmentName != this.profile.get('departmentName') ||
      this.profileJson.postName != this.profile.get('postName') ||
      this.profileJson.majorSubject != this.profile.get('majorSubject');
    console.log(a, b);
    if (
      a ||
      b ||
      this.userDataJson.companyType != this.profile?.get('companyType')
    ) {
      if (this.vrifly) return of(this.vrifly);
      this.updateCanDeActivate();
      return of(false);
    }
    return of(true);
  }
  //提示保存
  updateCanDeActivate() {
    new Promise((result) => {
      this.modal.confirm({
        nzTitle: '离开当前页面?',
        nzContent: '<p>当前编辑未保存，是否保存？</p>',
        nzOkText: '保存',
        nzOkType: 'primary',
        nzOkDanger: true,
        nzClosable: false,
        nzMaskClosable: false,
        nzOnOk: async () => {
          await this.updateUserJson();
          this.goUserList();
          result(true);
        },
        nzCancelText: '取消',
        nzOnCancel: () => {
          this.vrifly = true;
          this.goUserList();
        },
      });
    });
  }
}
