import { Component, ViewChild } from '@angular/core';
import { apiConf } from '@conf/api.conf';
import {
  SFUploadWidgetSchema,
  SFComponent,
  SFSchema,
  SFUISchema,
  SFDateWidgetSchema,
  SFCheckboxWidgetSchema,
  SFTreeSelectWidgetSchema
} from '@delon/form';
import { NzTreeNode } from 'ng-zorro-antd/tree';
import { NzUploadFile } from 'ng-zorro-antd/upload';
import { of, Subscription } from 'rxjs';
import { map } from 'rxjs/operators';

import { PartnerListService } from '../../services/partner-list.service';

const IMAGECONFIG = {
  previewFile: (file: NzUploadFile) => of(file.url),
  action: apiConf.waterFileUpload,
  fileType: 'image/png,image/jpeg,image/jpg,image/gif',
  fileSize: 5120,
  limit: 1,
  limitFileCount: 1,
  resReName: 'data.fullFileWatermarkPath',
  urlReName: 'data.fullFileWatermarkPath',
  widget: 'upload',
  name: 'multipartFile',
  multiple: false,
  listType: 'picture-card'
} as SFUploadWidgetSchema;

const DATECONFIG = {
  grid: { xxl: 13, xl: 18, lg: 24, md: 24 },
  widget: 'date',
  format: 'yyyy-MM-dd',
  placeholder: '请选择'
};

@Component({
  selector: 'app-add-etp-partner',
  templateUrl: './add-etp-partner.component.html',
  styleUrls: ['./add-etp-partner.component.less']
})
export class AddEtpPartnerComponent {
  @ViewChild('sf', { static: false })
  sf!: SFComponent;
  schema: SFSchema = this.initBasicInfoSF();
  ui: SFUISchema = {
    '*': {
      spanLabelFixed: 180,
      grid: { span: 24 }
    },
    $_basicInfoTitle: {
      spanLabelFixed: 0
    },
    $_legalPersontitle: {
      spanLabelFixed: 0
    },
    $_isLoingDate: {
      spanLabelFixed: 100,
      grid: { xxl: 6, xl: 6, lg: 4, md: 6 }
    }
  };

  getIdentityInfoSub = new Subscription();
  loadingIdentityInfoSub = false;

  constructor(public service: PartnerListService) {}

  submitForm() {
    if (!this.sf.valid) {
      this.sf.validator({ emitError: true });
      this.service.msgSrv.warning('请修改填写错误信息');
      return;
    }
    if (this.sf.value.cityCodesList?.length > 3) {
      this.sf.validator({ emitError: true });
      this.service.msgSrv.warning('所属城市不能超过3个');
      return;
    }
    // 校验企业营业期限
    const operatingStartTime = new Date(this.sf.value.operatingStartTime);
    const operatingEndTime = new Date(this.sf.value.operatingEndTime);
    if (operatingStartTime.getTime() > operatingEndTime.getTime()) {
      this.service.msgSrv.warning('营业截止日期不能小于开始日期');
      return;
    }
    // 校验法人证件有效期限
    if (this.sf.value.legalPersonIdentity.validEndTime) {
      const validStartTime = new Date(this.sf.value.legalPersonIdentity.validStartTime);
      const validEndTime = new Date(this.sf.value.legalPersonIdentity.validEndTime);
      if (validStartTime.getTime() > validEndTime.getTime()) {
        this.service.msgSrv.warning('法人证件有效截止日期不能小于开始日期');
        return;
      }
    }
    // 校验管理员证件有效期限
    if (this.sf.value.adminUserInfo.validEndTime) {
      const validStartTime = new Date(this.sf.value.adminUserInfo.validStartTime);
      const validEndTime = new Date(this.sf.value.adminUserInfo.validEndTime);
      if (validStartTime.getTime() > validEndTime.getTime()) {
        this.service.msgSrv.warning('管理员证件有效截止日期小于开始日期');
        return;
      }
    }
    const params = {};
    Object.assign(params, { ...this.sf.value, source: 2 });
    // console.log(params);

    this.service.request(this.service.$api_save_entp_partner, params).subscribe(res => {
      if (res) {
        this.service.msgSrv.success('新增企业合伙人成功');
        this.goBack();
      }
    });
  }

  /*
   * 根据地区code查询地区列表
   */
  getRegionDetailByCode(regionCode: any) {
    return this.service.request(this.service.$api_get_region_by_code, { regionCode });
  }

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

  // 识别营业执照
  checkBusinessLicense(imgurl: any) {
    this.service.request(this.service.$api_ocr_recognize_business_license, { businessLicenseUrl: imgurl }).subscribe(res => {
      if (res) {
        if (res.registrationNumber) {
          this.sf.setValue('/unifiedSocialCreditCode', res.registrationNumber);
        }
        if (res.name) {
          this.sf.setValue('/enterpriseName', res.name);
        }
        if (res.businessTermStartDate) {
          this.sf.setValue('/operatingStartTime', res.businessTermStartDate);
        }
        if (res.businessTermEndDate) {
          this.sf.setValue('/operatingEndTime', res.businessTermEndDate);
          this.sf.setValue('/_isLoingDate', false);
        } else {
          this.sf.setValue('/_isLoingDate', true);
        }
      }
    });
  }

  goBack() {
    window.history.go(-1);
  }

  private initBasicInfoSF(): SFSchema {
    return {
      properties: {
        // 企业基本信息
        _basicInfoTitle: { title: '', type: 'string', ui: { widget: 'custom' } },
        _licenseTips: { title: '营业执照', type: 'string', ui: { widget: 'custom' }, default: true },
        licensePhoto: { title: '', type: 'string', ui: { hidden: true } },
        licensePhotoWatermark: {
          type: 'string',
          title: '',
          ui: {
            ...IMAGECONFIG,
            descriptionI18n: '图片支持jpg、jpeg、png、gif格式，大小不超过5M',
            change: args => {
              if (args.type === 'success') {
                this.sf.setValue('/licensePhoto', args.fileList[0].response.data.fullFilePath);
                this.checkBusinessLicense(args.fileList[0].response.data.fullFilePath);
              }
            }
          } as SFUploadWidgetSchema
        },
        unifiedSocialCreditCode: {
          title: '统一社会信用代码',
          type: 'string',
          minLength: 1,
          maxLength: 30,
          ui: {
            grid: { xxl: 13, xl: 18, lg: 24, md: 24 },
            optionalHelp:
              '为了企业用户的使用体验，若公司代码即统一社会信用代码已在本应用其他关联平台注册，则此处填写的公司资料将同步更新至对应已注册的平台',
            placeholder: '请输入营业执照上的统一社会信用代码',
            errors: {
              required: '请输入18位公司代码'
            }
          }
        },
        enterpriseName: {
          title: '公司名称',
          type: 'string',
          minLength: 1,
          maxLength: 100,
          ui: {
            grid: { xxl: 13, xl: 18, lg: 24, md: 24 },
            placeholder: '请输入营业执照上的统一社会信用代码',
            errors: {
              required: '请输入公司名称'
            }
          }
        },
        operatingStartTime: {
          title: '营业期限',
          type: 'string',
          ui: {
            ...DATECONFIG,
            grid: { xxl: 13, xl: 18, lg: 24, md: 24 },
            errors: {
              required: '请选择开始日期'
            }
          } as SFDateWidgetSchema
        },
        operatingEndTime: {
          title: '',
          type: 'string',
          ui: {
            ...DATECONFIG,
            grid: { xxl: 13, xl: 18, lg: 20, md: 18 },
            errors: {
              required: '请选择截止日期'
            },
            change: i => {
              this.sf?.setValue('/_isLoingDate', false);
            }
          } as SFDateWidgetSchema
        },
        _isLoingDate: {
          title: '长期',
          type: 'boolean',
          ui: {
            class: 'input-back',
            widget: 'checkbox',
            change: i => this.sf?.setValue('/operatingEndTime', null)
          } as SFCheckboxWidgetSchema
        },

        // 法人信息
        legalPersonIdentity: {
          type: 'object',
          properties: {
            _legalPersontitle: { title: '', type: 'string', ui: { widget: 'custom' } },
            _certificatePhototips: { title: '法定代表人证件照', type: 'string', ui: { widget: 'custom' }, default: true },
            _certificatePhotoExmplateA: { title: '', type: 'string', ui: { widget: 'custom', offsetControl: 6 } },
            certificatePhotoFrontWatermark: {
              type: 'string',
              title: '',
              ui: {
                ...IMAGECONFIG,
                descriptionI18n: '图片支持jpg、jpeg、png、gif格式，大小不超过5M',
                change: args => {
                  if (args.type === 'success') {
                    this.sf.setValue('/legalPersonIdentity/certificatePhotoFront', args.fileList[0].response.data.fullFilePath);
                    this.checkIdCard(args.fileList[0].response.data.fullFilePath, 'front', 1);
                  }
                }
              } as SFUploadWidgetSchema
            },
            _certificatePhotoExmplateB: { title: '', type: 'string', ui: { widget: 'custom', offsetControl: 6 } },
            certificatePhotoFront: { title: '', type: 'string', ui: { hidden: true } },
            certificatePhotoBack: { title: '', type: 'string', ui: { hidden: true } },
            certificatePhotoBackWatermark: {
              type: 'string',
              title: '',
              ui: {
                ...IMAGECONFIG,
                descriptionI18n: '图片支持jpg、jpeg、png、gif格式，大小不超过5M',
                change: args => {
                  if (args.type === 'success') {
                    this.sf.setValue('/legalPersonIdentity/certificatePhotoBack', args.fileList[0].response.data.fullFilePath);
                    this.checkIdCard(args.fileList[0].response.data.fullFilePath, 'back', 1);
                  }
                }
              } as SFUploadWidgetSchema
            },
            name: {
              title: '法人代表姓名',
              type: 'string',
              maxLength: 8,
              ui: {
                grid: { xxl: 13, xl: 18, lg: 24, md: 24 },
                placeholder: '请输入营业执照上的法人姓名'
              }
            },
            certificateType: {
              type: 'string',
              title: '法人证件类型',
              enum: [
                { label: '大陆身份证', value: 0 },
                { label: '港澳居民通行证', value: 1 },
                { label: '香港居民通行证', value: 2 }
              ],
              default: 0,
              ui: {
                grid: { xxl: 13, xl: 18, lg: 24, md: 24 },
                widget: 'select'
              }
            },
            certificateNumber: {
              title: ' 法定代表人证件号',
              type: 'string',
              format: 'id-card',
              minLength: 1,
              maxLength: 18,
              ui: {
                grid: { xxl: 13, xl: 18, lg: 24, md: 24 },
                placeholder: '请输入法定代表人证件号'
              }
            },
            validStartTime: {
              title: '法人证件有效开始日期',
              type: 'string',
              ui: {
                grid: { xxl: 13, xl: 18, lg: 24, md: 24 },
                widget: 'date',
                format: 'yyyy-MM-dd',
                placeholder: '请选择',
                errors: {
                  required: '请选择开始日期'
                }
              } as SFDateWidgetSchema
            },
            validEndTime: {
              title: '法人证件有效截止日期',
              type: 'string',
              ui: {
                grid: { xxl: 13, xl: 18, lg: 24, md: 24 },
                widget: 'date',
                format: 'yyyy-MM-dd',
                placeholder: '请选择',
                errors: {
                  required: '请选择截止日期'
                },
                change: i => {
                  this.sf?.setValue('/legalPersonIdentity/_isLoingDate', false);
                }
              } as SFDateWidgetSchema
            },
            _isLoingDate: {
              title: '长期',
              type: 'boolean',
              ui: {
                spanLabelFixed: 100,
                grid: { span: 6 },
                class: 'input-back',
                widget: 'checkbox',
                change: i => this.sf?.setValue('/legalPersonIdentity/validEndTime', null)
              } as SFCheckboxWidgetSchema
            }
          },
          required: [
            '_certificatePhototips',
            'certificatePhotoFront',
            'certificatePhotoBack',
            'name',
            'certificateType',
            'certificateNumber',
            'validStartTime'
          ]
        },
        _adminTitle: { title: '', type: 'string', ui: { widget: 'custom' } },
        adminMobile: {
          title: ' 企业管理员手机号',
          type: 'string',
          minLength: 1,
          format: 'mobile',
          maxLength: 11,
          ui: {
            grid: { xxl: 13, xl: 18, lg: 24, md: 24 },
            placeholder: '请输入企业管理员手机号',
            errors: { required: '请输入企业管理员手机号', format: '手机号格式错误' },
            change: (mobile: any) => {
              // 根据手机号获取实名信息
              if (mobile?.length === 11) {
                if (this.loadingIdentityInfoSub) {
                  this.getIdentityInfoSub.unsubscribe();
                }
                this.loadingIdentityInfoSub = true;
                this.getIdentityInfoSub = this.service.request(this.service.$api_get_identityInfo_by_mobile, { mobile }).subscribe(
                  res => {
                    if (res) {
                      this.setInfo(res);
                      this.sf.setValue('/adminUserInfo/id', res.id);
                      this.sf.setValue('/adminUserInfo/userId', res.userId);
                    }
                    this.loadingIdentityInfoSub = false;
                  },
                  _ => {},
                  () => (this.loadingIdentityInfoSub = false)
                );
              }
            }
          }
        },
        // 企业管理员信息
        adminUserInfo: {
          type: 'object',
          properties: {
            _adminCertificatePhotoTipsA: {
              title: '企业管理员证件照',
              type: 'string',
              ui: {
                widget: 'custom'
              },
              default: true
            },
            id: { title: '', type: 'string', ui: { hidden: true } },
            userId: { title: '', type: 'string', ui: { hidden: true } },
            certificatePhotoFront: { title: '', type: 'string', ui: { hidden: true } },
            certificatePhotoBack: { title: '', type: 'string', ui: { hidden: true } },
            certificatePhotoFrontWatermark: {
              type: 'string',
              title: '',
              ui: {
                ...IMAGECONFIG,
                descriptionI18n: '图片支持jpg、jpeg、png、gif格式，大小不超过5M',
                change: args => {
                  if (args.type === 'success') {
                    this.sf.setValue('/adminUserInfo/certificatePhotoFront', args.fileList[0].response.data.fullFilePath);
                    this.checkIdCard(args.fileList[0].response.data.fullFilePath, 'front', 0);
                  }
                }
              } as SFUploadWidgetSchema
            },
            _adminCertificatePhotoTipsB: {
              title: '',
              type: 'string',
              ui: {
                widget: 'custom',
                offsetControl: 6
              }
            },
            certificatePhotoBackWatermark: {
              type: 'string',
              title: '',
              ui: {
                ...IMAGECONFIG,
                descriptionI18n: '图片支持jpg、jpeg、png、gif格式，大小不超过5M',
                change: args => {
                  if (args.type === 'success') {
                    this.sf.setValue('/adminUserInfo/certificatePhotoBack', args.fileList[0].response.data.fullFilePath);
                    this.checkIdCard(args.fileList[0].response.data.fullFilePath, 'back', 0);
                  }
                }
              } as SFUploadWidgetSchema
            },
            name: {
              title: '企业管理员姓名',
              type: 'string',
              maxLength: 8,
              ui: {
                grid: { xxl: 13, xl: 18, lg: 24, md: 24 },
                placeholder: '请输入企业管理员姓名'
              }
            },
            certificateNumber: {
              title: '企业管理员身份证号',
              type: 'string',
              format: 'id-card',
              minLength: 1,
              maxLength: 18,
              ui: {
                grid: { xxl: 13, xl: 18, lg: 24, md: 24 },
                placeholder: '请输入企业管理员身份证号'
              }
            },
            validStartTime: {
              title: '身份证有效开始日期',
              type: 'string',
              ui: {
                ...DATECONFIG,
                grid: { xxl: 13, xl: 18, lg: 24, md: 24 },
                errors: {
                  required: '请选择开始日期'
                }
              } as SFDateWidgetSchema
            },
            validEndTime: {
              title: '身份证有效截止日期',
              type: 'string',
              ui: {
                ...DATECONFIG,
                grid: { xxl: 13, xl: 18, lg: 20, md: 18 },
                errors: {
                  required: '请选择截止日期'
                },
                change: i => {
                  this.sf?.setValue('/adminUserInfo/_isLoingDate', false);
                }
              } as SFDateWidgetSchema
            },
            _isLoingDate: {
              title: '长期',
              type: 'boolean',
              ui: {
                spanLabelFixed: 100,
                grid: { span: 6 },
                class: 'input-back',
                widget: 'checkbox',
                change: i => this.sf?.setValue('/adminUserInfo/validEndTime', null)
              } as SFCheckboxWidgetSchema
            }
          },
          required: ['_adminCertificatePhotoTipsA', 'name', 'certificateNumber', 'operatingStartTime']
        },
        // 所属城市
        _addressTitle: { title: '', type: 'string', ui: { widget: 'custom' } },
        cityCodesList: {
          type: 'string',
          title: '所属城市',
          ui: {
            widget: 'tree-select',
            grid: { xxl: 13, xl: 18, lg: 24, md: 24 },
            placeholder: '请选择城市(最多3个)',
            checkable: true,
            class: 'city-tree-select',
            asyncData: () =>
              this.getRegionDetailByCode('').pipe(
                map((res: any) =>
                  res.map((item: any) => ({ ...item, title: item.name, key: item.regionCode, disabled: true, isDisableCheckbox: true }))
                )
              ),
            expandChange: ({ node }: { node: NzTreeNode }) =>
              this.getRegionDetailByCode(node.key).pipe(
                map((res: any) => res.map((item: any) => ({ ...item, title: item.name, key: item.regionCode, isLeaf: true })))
              )
          } as SFTreeSelectWidgetSchema
        },
        // 渠道销售
        _channelTitle: { title: '', type: 'string', ui: { widget: 'custom' } },
        invitationCode: {
          title: '渠道销售邀请码',
          type: 'string',
          minLength: 1,
          maxLength: 100,
          ui: {
            grid: { xxl: 13, xl: 18, lg: 24, md: 24 },
            placeholder: '请输入渠道销售邀请码',
            errors: {
              required: '请输入渠道销售邀请码'
            }
          }
        }
      },
      required: [
        '_licenseTips',
        'licensePhotoWatermark',
        'unifiedSocialCreditCode',
        'enterpriseName',
        'operatingStartTime',
        'cityCodesList',
        'adminMobile',
        'invitationCode'
      ]
    };
  }

  private setInfo(info: any) {
    if (info.name) {
      this.sf.setValue('/adminUserInfo/name', info.name);
    }
    if (info.certificatePhotoFront) {
      this.sf.setValue('/adminUserInfo/certificatePhotoFront', info.certificatePhotoFront);
    }
    if (info.certificatePhotoFrontWatermark) {
      console.log(this.sf.getProperty('/adminUserInfo/certificatePhotoFrontWatermark'));

      this.sf.setValue('/adminUserInfo/certificatePhotoFrontWatermark', [
        {
          uid: -1,
          name: '文件',
          status: 'done',
          url: info.certificatePhotoFrontWatermark,
          response: info.certificatePhotoFrontWatermark
        }
      ]);
    }
    if (info.certificatePhotoBack) {
      this.sf.setValue('/adminUserInfo/certificatePhotoBack', info.certificatePhotoBack);
    }
    if (info.certificatePhotoBackWatermark) {
      this.sf.setValue('/adminUserInfo/certificatePhotoBackWatermark', [
        {
          uid: -1,
          name: '文件',
          status: 'done',
          url: info.certificatePhotoBackWatermark,
          response: info.certificatePhotoBackWatermark
        }
      ]);
    }
    if (info.certificateNumber) {
      this.sf.setValue('/adminUserInfo/certificateNumber', info.certificateNumber);
    }
    if (info.validStartTime) {
      this.sf.setValue('/adminUserInfo/validStartTime', info.validStartTime);
    }
    if (info.validEndTime) {
      this.sf.setValue('/adminUserInfo/validEndTime', info.validEndTime);
      this.sf.setValue('/adminUserInfo/_isLoingDate', false);
    } else {
      this.sf.setValue('/adminUserInfo/_isLoingDate', true);
    }
  }
}
