import { Component, OnInit, ViewChild, inject } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { STColumn, STComponent } from '@delon/abc/st';
import { SFComponent, SFSchema } from '@delon/form';
import { ModalHelper, SettingsService, _HttpClient } from '@delon/theme';
import { SHARED_IMPORTS } from '@shared';
import { lastValueFrom } from 'rxjs';
import { AppUtils } from 'src/app/core/utils/app-utils';
import { AppValidators } from 'src/app/core/utils/app-validators';
import { BaseService } from 'src/app/core/utils/base.service';
import { SharedModule } from '@shared';

@Component({
  selector: 'app-sys-psn-manage',
  standalone: true,
  imports: [SharedModule, ...SHARED_IMPORTS],
  templateUrl: './psn-manage.component.html'
})
export class SysPsnManageComponent implements OnInit {
  private readonly http = inject(_HttpClient);
  private readonly modal = inject(ModalHelper);
  private readonly fb = inject(FormBuilder);
  private readonly baseService = inject(BaseService);
  private readonly settings = inject(SettingsService);

  url = `/api/main/psn-info`;
  deptUrl = `/api/main/dept-info`;
  accountSuffix = ''; //账户后缀
  userList: any;

  public deptList: any; //菜单列表
  public currentNode: any;

  @ViewChild('sf') private readonly sf!: SFComponent;
  searchSchema: SFSchema = {
    properties: {
      deptId: {
        type: 'string',
        title: '科室id',
        visable: false,
        ui: {
          hidden: true
        },
        default: ''
      },
      filter: {
        type: 'string',
        title: '关键字过滤'
      }
    }
  };
  @ViewChild('st') private readonly st!: STComponent;
  columns: STColumn[] = [
    {
      title: '操作',
      buttons: [
        { text: '编辑', click: (item: any) => this.editStaff(item) },
        { text: '删除', pop: true, click: (item: any) => this.delete(item) }
      ]
    },
    { title: '人员编码', index: 'psnCodg' },
    { title: '人员姓名', index: 'psnName' },
    {
      title: '性别',
      index: 'gend',
      type: 'enum',
      enum: { 1: '男', 2: '女' }
    },
    {
      title: '出生日期',
      index: 'brdy',
      type: 'date',
      dateFormat: 'yyyy-MM-dd',
      width: 100
    },
    { title: '联系电话', index: 'tel' },
    { title: '证件号码', index: 'certno' }
  ];

  isAdd = false;
  editVisible = false;
  detailTitle = '人员信息详细';
  form!: FormGroup;
  genderList = [
    {
      Code: 1,
      Name: '男'
    },
    {
      Code: 2,
      Name: '女'
    }
  ]; //性别集合
  psnCertTypeList: any; // 证件类型集合
  // 出生日期限制
  disabledEndDate = (endValue: Date): boolean => {
    if (endValue.getTime() <= new Date().getTime()) {
      return false;
    }
    return true;
  };

  ngAfterViewInit(): void {}

  ngOnInit(): void {
    this.createForm();
    this.getUserList();
    this.getDeptList();
  }

  // 检索参数
  get reqParams() {
    if (this.sf) {
      const re = { ...this.sf.value };
      return re;
    }
    return {};
  }

  /**
   * ocean 2023-6-4
   * 获取菜单列表
   */
  getDeptList() {
    const req = {
      organId: this.settings.user['currentOrgan'].id
    };

    this.http.get(this.deptUrl, req).subscribe((res: any) => {
      this.deptList = [];
      res.map((r: { deptCodg: any; deptName: any; id: any; children: any[] }) => {
        this.deptList.push({
          title: `${r.deptCodg} - ${r.deptName}`,
          key: r.id,
          level: 1,
          isLeaf: r.children.length == 0,
          expanded: true,
          children: r.children.map(rr => {
            return {
              title: `${rr.deptCodg} - ${rr.deptName}`,
              key: rr.id,
              level: 2,
              isLeaf: rr.children.length == 0,
              expanded: true,
              children: rr.children.map((rrr: { deptCodg: any; deptName: any; id: any }) => {
                return {
                  title: `${rrr.deptCodg} - ${rrr.deptName}`,
                  key: rrr.id,
                  level: 3,
                  isLeaf: true
                };
              })
            };
          })
        });
      });
      //this.getParentMenuList(res);
    });
  }

  // /**
  //  * ocean 2024-1-19
  //  * 获取科室列表
  // */
  // getDeptList() {
  //   this.http.get('/api/main/dept-info', { organId: this.settings.user['currentOrgan'].id }).subscribe(res => {
  //     const deptIdProperty = this.sf.getProperty('/deptId')!;
  //     deptIdProperty.schema.enum = res.map(r => {
  //       return {
  //         value: r.deptCodg,
  //         label: r.deptName,
  //       }
  //     });
  //     deptIdProperty.widget.reset('');
  //   })
  // }

  /**
   * 创建Form
   */
  createForm() {
    this.form = this.fb.group({
      id: [],
      // 人员编号
      psnCodg: [, AppValidators.required('E0001', '人员编号')],
      // 姓名
      psnName: [, AppValidators.required('E0001', '姓名')],
      // 性别
      gend: [, AppValidators.required('E0001', '性别')],
      // 出生日期
      brdy: [],
      // 证件类型
      psnCertTypeValue: [],
      // 证件号码
      certno: [],
      // 职业代码
      pracPsnCode: [],
      // 职称
      profttlName: [],
      // 拼音码
      pinYinCode: [],
      // 用户Id
      userId: [],

      deptId: [],
      // 电话
      tel: []
    });

    // 姓名转变成拼音码
    this.form.get('pinYinCode')?.disable();
    this.form.get('userName')?.disable();
    this.form.get('pracPsnName')?.valueChanges.subscribe(m => {
      setTimeout(() => {
        //const result = AppUtils.convertToPinyin(m, ENUM_PINYIN_STYLE.FIRST_LETTER);
        //this.form.patchValue({ pinYinCode: result });
      });
    });
    this.form.get('pracPsnNo')?.valueChanges.subscribe(m => {
      if (m) {
        this.form.patchValue({ userName: m + this.accountSuffix });
      }
    });
  }

  /**
   * ocean 2023-8-30
   * 新增
   */
  add(): void {
    if (this.currentNode) {
      this.form.reset({
        deptId: this.currentNode.key
      });
      this.form.get('pracPsnNo')?.enable();
      this.isAdd = true;
      this.editVisible = true;
    }
  }

  /**
   *
   */
  getUserList() {
    this.http.get(`/api/identity/users`).subscribe(res => {
      this.userList = res.items;
    });
  }

  /**
   * 2023-8-18
   * 人员编辑
   */
  editStaff(item: any, isReadonly = false) {
    this.isAdd = false;
    this.form.get('pracPsnNo')?.disable();
    this.form.patchValue(item);
    this.editVisible = true;
  }

  /**
   * 人员信息删除
   */
  async delete(data: any) {
    await lastValueFrom(this.http.delete(`${this.url}/${data.id}`));
    this.st.reload();
  }

  /**
   * ocean 2023-8-21
   * 保存员工信息
   */
  save() {
    // 画面输入的验证
    if (this.baseService.hasError(this.form)) {
      return;
    }
    const req = this.form.getRawValue();
    if (req.id) {
      this.http.put(`${this.url}/${req.id}`, req).subscribe(res => {
        this.editVisible = false;
        this.st.reload();
      });
    } else {
      this.http.post(this.url, req).subscribe(res => {
        this.editVisible = false;
        this.st.reload();
      });
    }
  }

  /**
   * ocean 2023-6-4
   * 科室选择
   */
  deptChange(e: any): void {
    if ((e.eventName = 'click')) {
      this.currentNode = e.node;
      //const deptId = this.searchSchema.properties?.['deptId'];
      this.sf.setValue('/deptId', e.node.key);
      const filter = this.sf.getValue('/filter');
      //deptId?.['widget'].reset(e.node.key);
      this.st.reset({ deptId: e.node.key, filter });
    }
  }

  close() {
    this.editVisible = false;
  }
}
