import { DatePipe } from '@angular/common';
import { Component, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { apiConf } from '@conf/api.conf';
import { STColumn } from '@delon/abc/st';
import { NzModalService } from 'ng-zorro-antd/modal';
import { NzTreeNode, NzTreeNodeOptions } from 'ng-zorro-antd/tree';
import { NzTreeSelectComponent } from 'ng-zorro-antd/tree-select';
import { Subscription, fromEvent } from 'rxjs';

import { PartnerListService } from '../../services/partner-list.service';
import { PartnerAuditModalComponent } from '../partner-audit-modal/partner-audit-modal.component';

@Component({
  selector: 'app-personal-partner-detail',
  templateUrl: './personal-partner-detail.component.html',
  styleUrls: ['./personal-partner-detail.component.less'],
  providers: [DatePipe]
})
export class PersonalPartnerDetailComponent implements OnInit {
  @ViewChild('areaTreeSelect')
  areaTreeSelect!: NzTreeSelectComponent;

  columns: STColumn[] = this.initST();

  detailData: any = { adminUserInfo: { name: '' }, legalPersonIdentity: { name: '' } };
  tempalateData = { ...this.detailData };

  isEdit = false;

  uploadURl = apiConf.waterFileUpload;
  disabledUpload = false;
  enterpriseAddressCode: string[] = [];
  enterpriseDefaultAddressCode: string[] = [];
  enterpriseDefaultCityName: string = '';
  areaList = [];

  constructor(
    public service: PartnerListService,
    public route: ActivatedRoute,
    private nzModalService: NzModalService,
    private datePipe: DatePipe
  ) {}

  ngOnInit() {
    this.initData();
    this.loadlAreaList();
  }

  loadlAreaList() {
    this.service.request(this.service.$api_get_region_by_code, { regionCode: '' }).subscribe(res => {
      if (res) {
        this.areaList = res.map((item: any) => ({
          ...item,
          isLeaf: false,
          title: item.name,
          key: item.regionCode.toString(),
          disabled: true,
          isDisableCheckbox: true
        }));
      }
    });
  }

  initData() {
    this.service
      .request(this.service.$api_get_personal_partner_detail, {
        id: this.route.snapshot.params.id
      })
      .subscribe(res => {
        if (res) {
          this.detailData = res;
          console.log(this.detailData);

          this.tempalateData = { ...this.detailData };
          // 拼接所属城市
          if (this.detailData?.cityCodesList?.length > 0) {
            this.enterpriseAddressCode = (this.detailData?.cityCodesList as any[]).map(city => city.cityCode);
            this.enterpriseDefaultCityName = (this.detailData?.cityCodesList as any[]).map(city => city.cityName).join('、');
            this.enterpriseDefaultAddressCode = [
              ...new Set<string>((this.detailData?.cityCodesList as any[]).map(city => city.provinceCode))
            ];
          }
          if (this.detailData?.channelIdLabel) {
            const channel = (this.detailData.channelIdLabel as string).split('/');
            Object.assign(this.detailData, {
              channelName: channel[0],
              channelMobile: channel[1]
            });
          }
        }
      });
  }

  goBack() {
    window.history.go(-1);
  }
  /**
   * 冻结
   */
  freezeOrResume(type: number) {
    this.service.http
      .post(this.service.$api_lock_freight, {
        appUserId: [this.detailData.appUserId],
        freezeOrResume: !!type,
        pageName: '合伙人详情',
        telephone: this.detailData.adminUserInfo.mobile
      })
      .subscribe(res => {
        if (res.data === true) {
          if (type === 0) {
            this.service.msgSrv.success(`启用成功！`);
          } else {
            this.service.msgSrv.success(`冻结成功！`);
          }
          this.initData();
        } else {
          this.service.msgSrv.error(res.msg || '操作失败！');
        }
      });
  }

  auditPartner(isPass: boolean) {
    const modal = this.nzModalService.create({
      nzTitle: '审核',
      nzContent: PartnerAuditModalComponent,
      nzComponentParams: {
        info: { ...this.detailData, isPass, enterpriseName: this.detailData.adminUserInfo?.name },
        sourcePage: '合伙人审核详情'
      },
      nzFooter: null
    });

    modal.afterClose.subscribe(res => {
      if (res) {
        this.initData();
      }
    });
  }

  ratify() {
    this.isEdit = true;
    // 搜索展开省份并选中节点
    setTimeout(() => {
      if (this.enterpriseDefaultAddressCode?.length > 0 && this.areaTreeSelect) {
        this.enterpriseDefaultAddressCode.forEach(code => {
          const node = this.areaTreeSelect.getTreeNodeByKey(code);
          if (node) {
            node.setExpanded(true);
            this.onExpandChange(node);
          }
        });
      }
    }, 500);
  }

  deleteImg(data: any, key: string, key2: string) {
    this.nzModalService.warning({
      nzTitle: '是否确认删除该图片',
      nzOnOk: () => {
        this.disabledUpload = true;
        data[key] = '';
        data[key2] = '';
        setTimeout(() => {
          this.disabledUpload = false;
        }, 100);
      }
    });
  }
  changeUpload({ file, fileList, type }: any, data: any, key: string, key2: string, id: string) {
    if (type === 'success') {
      data[key] = file.response.data?.fullFileWatermarkPath;
      data[key2] = file.response.data?.fullFilePath;
      if (id === 'legalFront' || id === 'legalBack') {
        this.checkIdCard(file.response.data?.fullFilePath, id === 'legalFront' ? 'front' : 'back');
      }
    }
  }

  onExpandChange(node: NzTreeNode | null | undefined): void {
    if (node && node.getChildren().length === 0 && node.isExpanded) {
      this.loadRegionData(node).then(data => {
        node.addChildren(data);
        // 更新选中数据
        this.areaTreeSelect.updateSelectedNodes(true);
        // 修改子节点选中状态
        const children = node.getChildren();
        if (children?.length > 0) {
          children.forEach(childNode => {
            if (this.enterpriseAddressCode.find(area => area === childNode.key)) {
              childNode.setChecked(true);
            }
          });
        }
      });
    }
  }

  /**
   * 级联获取地区数据
   *
   * @param node 节点
   * @param index 层级
   * @returns
   */
  loadRegionData(node: NzTreeNode): Promise<NzTreeNodeOptions[]> {
    let rs: any[] = [];
    return new Promise(resolve => {
      this.service.request(this.service.$api_get_region_by_code, { regionCode: node?.origin.regionCode || '' }).subscribe(
        res => {
          rs = res.map((item: any) => ({
            ...item,
            isLeaf: true,
            title: item.name,
            key: item.regionCode.toString(),
            isSelectable: true,
            isSelected: true,
            isChecked: true
          }));
        },
        _ => {},
        () => {
          resolve(rs);
        }
      );
    });
  }

  reset() {
    this.detailData = { ...this.tempalateData };
    this.isEdit = false;
  }

  save() {
    if (this.enterpriseAddressCode?.length > 3) {
      this.service.msgSrv.warning('所属城市不能超过3个');
      return;
    }
    const dateil = { ...this.detailData, cityCodesList: this.enterpriseAddressCode };
    Object.assign(dateil.adminUserInfo, {
      validStartTime: this.datePipe.transform(dateil.adminUserInfo.validStartTime, 'yyyy-MM-dd'),
      validEndTime: this.datePipe.transform(dateil.adminUserInfo.validEndTime, 'yyyy-MM-dd')
    });

    this.service.request(this.service.$api_save_personal_partner, dateil).subscribe(res => {
      if (res) {
        this.service.msgSrv.success('个人合伙人修改成功');
        this.initData();
        this.isEdit = false;
      }
    });
  }

  // 识别身份证 参数isFront：front-正面、back-背面；type：0-申请人身份证，1-法定代表人身份证
  checkIdCard(imgurl: any, isFront: string) {
    const params = {
      idCardUrl: imgurl,
      side: isFront
    };
    this.service.request(this.service.$api_ocr_recognize_id_card, params).subscribe(res => {
      if (res) {
        // 企业管理员证件照
        if (isFront === 'front') {
          // 正面
          if (res.name) {
            this.detailData.adminUserInfo.name = res.name;
          }
          if (res.number) {
            this.detailData.adminUserInfo.certificateNumber = res.number;
          }
        }
        if (isFront === 'back') {
          // 背面
          if (res.validFrom) {
            this.detailData.adminUserInfo.validStartTime = res.validFrom;
          }
          if (res.validTo) {
            this.detailData.adminUserInfo.validEndTime = res.validTo;
          }
        }
      }
    });
  }

  private initST(): STColumn[] {
    return [
      { title: '修改后渠道销售', index: 'newChannelIdLabel', width: 180 },
      { title: '修改前渠道销售', index: 'originalChannelIdLabel', width: 160 },
      { title: '转移客户数', index: 'quantity', className: 'text-center', width: 130 },
      { title: '生效节点', index: 'effectiveNode', width: 150, type: 'enum', enum: { 1: '立即生效', 2: 'CRM审核后生效' } },
      { title: '备注', index: 'remark', className: 'text-center', width: 150 },
      { title: '修改时间', index: 'effectiveTime', className: 'text-center', width: 180, type: 'date' },
      { title: '操作人', index: 'modifyUserIdLabel', width: 180 },
      {
        title: '操作',
        fixed: 'right',
        width: '140px',
        buttons: [
          {
            text: '详情',
            click: item => this.service.showChangeDetail(item.id)
          }
        ]
      }
    ];
  }
}
