import { Component, OnInit, ViewChild } from '@angular/core';
import { apiConf } from '@conf/api.conf';
import { SFComponent, SFSchema, SFUISchema, SFUploadWidgetSchema } from '@delon/form';
import { _HttpClient } from '@delon/theme';
import { EAEnvironmentService } from '@shared';
import { NzModalRef } from 'ng-zorro-antd/modal';
import { Observable, Observer, Subject } from 'rxjs';
import { UsermanageService } from 'src/app/routes/usercenter/services/usercenter.service';
import { debounceTime } from 'rxjs/operators';


@Component({
  selector: 'app-ctc-add',
  templateUrl: './add.component.html',
  styleUrls: ['./add.component.less']
})
export class CtcCaptatinAddComponent implements OnInit {
  @ViewChild('sf', { static: false })
  sf!: SFComponent;
  record: any = {};
  i: any;
  schema!: SFSchema;
  ui!: SFUISchema;
  readFlag = false;
  changeSub = new Subject<string>();
  detailData: any = {
    bankCardNo: '',
    bankName: '',
    mobile: '',
    remark: '',
    identityInfoDTO: {
      certificatePhotoBackWatermark: '',
      certificatePhotoFrontWatermark: '',
      certificatePhotoFront: '',
      certificatePhotoBack: '',
      certificateNumber: '',
      name: '',
    }
  }

  constructor(
    private modal: NzModalRef,
    private envSrv: EAEnvironmentService,
    public service: UsermanageService
  ) { }

  ngOnInit(): void {
    this.initData()
    this.initSF();
    this.changeEndKmAction();
  }
  initData() {
    if (this.i && this.i.id) {
      this.service.request(this.service.$api_captainrDetail, { id: this.i.id }).subscribe(res => {
        if (res) {
          this.detailData = res
          this.detailData.identityInfoDTO.certificatePhotoFrontWatermark = [
            {
              uid: -1,
              name: 'LOGO',
              status: 'done',
              url: this.detailData.identityInfoDTO.certificatePhotoFrontWatermark,
              response: this.detailData.identityInfoDTO.certificatePhotoFrontWatermark,
            },
          ];
          this.detailData.identityInfoDTO.certificatePhotoBackWatermark = [
            {
              uid: -1,
              name: 'LOGO',
              status: 'done',
              url: this.detailData.identityInfoDTO.certificatePhotoBackWatermark,
              response: this.detailData.identityInfoDTO.certificatePhotoBackWatermark,
            },
          ];
          this.initSF();
        }
      })
    }

  }
  initSF() {
    this.schema = {
      properties: {
        mobile: {
          title: '手机号',
          type: 'string',
          format: 'mobile',
          maxLength: 11,
          ui: {
            widget: this.i.id ? 'text' : '',
            placeholder: '请输入手机号',
            blur: () => {
              if(!this.sf.value.mobile) {
                return
              }
              this.service.request(this.service.$api_getByMobile, { mobile: this.sf.value.mobile }).subscribe(res => {
                if (res.certificateNumber) {
                  this.readFlag = true
                  this.detailData = {
                    mobile: this.sf.value.mobile,
                    bankName: this.sf.value.bankName,
                    bankCardNo: this.sf.value.bankCardNo,
                    remark: this.sf.value.remark,
                    identityInfoDTO: {
                      certificatePhotoFrontWatermark: [
                        {
                          uid: -1,
                          name: 'LOGO',
                          status: 'done',
                          url: res.certificatePhotoFrontWatermark,
                          response: res.certificatePhotoFrontWatermark,
                        }],
                      certificatePhotoBackWatermark: [
                        {
                          uid: -1,
                          name: 'LOGO',
                          status: 'done',
                          url: res.certificatePhotoBackWatermark,
                          response: res.certificatePhotoBackWatermark,
                        }],
                      name: res.name,
                      certificateNumber: res.certificateNumber,
                      certificatePhotoFront: res.certificatePhotoFront,
                      certificatePhotoBack: res.certificatePhotoBack,
                    }
                  }
                  this.initSF()
                } else {
                  this.readFlag = false
                  this.detailData = {
                    mobile: this.sf.value.mobile,
                    bankName: this.sf.value.bankName,
                    bankCardNo: this.sf.value.bankCardNo,
                    remark: this.sf.value.remark,
                    identityInfoDTO: {
                      certificatePhotoFrontWatermark: '',
                      certificatePhotoBackWatermark: '',
                      name: '',
                      certificateNumber: '',
                      certificatePhotoFront: '',
                      certificatePhotoBack: '',
                    }
                  }
                  this.initSF()
                }
              })
            }
          },
          default: this.detailData.mobile
        },
        name: {
          title: '姓名',
          type: 'string',
          ui: {
            widget: this.i.id && (this.i.driverLicenseStatus === 10 || this.i.driverLicenseStatus === 20) ? 'text' : '',
            placeholder: '请输入姓名',
          },
          readOnly: this.readFlag,
          default: this.detailData.identityInfoDTO.name
        },
        bankCardNo: {
          title: '银行卡号',
          type: 'string',
          ui: {
            widget: '',
            placeholder: '请输入银行卡号',
            change: (val: any) => {
              const value = val.replace(/\D/g, '')
              this.sf.setValue('/bankCardNo', value)
            },
            errors: {
              required: '请输入银行账号',
            },
          },
          default: this.detailData.bankCardNo
        },
        bankName: {
          title: '开户行',
          type: 'string',
          ui: {
            widget: '',
            placeholder: '请输入开户行',
          },
          default: this.detailData.bankName
        },
        showName: {
          title: '身份证照片',
          type: 'string',
          readOnly: true,
          ui: {
            widget: 'textarea',
            showRequired: true,
            borderless: true,
          },
          default: '请上传身份证原件的高清照片，若上传复印件，则需加盖公司印章及法人签字；上传后系统会自动识别并填写',
        },
        tipsA: {
          title: '',
          type: 'string',
          ui: {
            widget: 'custom',
            offsetControl: 6,
          },
        },
        certificatePhotoFrontWatermark: {
          type: 'string',
          title: '',
          readOnly: (this.i.id && (this.i.driverLicenseStatus === 10 || this.i.driverLicenseStatus === 20)) || this.readFlag,
          ui: {
            offsetControl: 6,
            action: apiConf.fileUpload,
            accept: 'image/png,image/jpeg,image/jpg,image/gif',
            limit: 1,
            limitFileCount: 1,
            resReName: 'data.fullFileWatermarkPath',
            urlReName: 'data.fullFileWatermarkPath',
            widget: 'upload',
            descriptionI18n: '图片支持jpg、jpeg、png、gif格式，大小不超过2M',
            data: {
              appId: this.envSrv.env.appId,
            },
            name: 'multipartFile',
            multiple: false,
            listType: 'picture-card',
            change: (args: any) => {
              if (args.type === 'success') {
                this.detailData.identityInfoDTO.certificatePhotoFront = args.file.response.data.fullFilePath
                this.checkIdCard(args.file.response.data.fullFilePath, 'front');
              } else {
                this.detailData.identityInfoDTO.certificatePhotoFront = ''
              }
            },
            beforeUpload: (file: any, _fileList: any) => {
              return new Observable((observer: Observer<boolean>) => {
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isLt2M) {
                  this.service.msgSrv.warning('图片大小超过2M!');
                  observer.complete();
                  return;
                }
                observer.next(isLt2M);
                observer.complete();
              });
            },
            previewFile: (file: any) => { }
          },
          default: this.detailData.identityInfoDTO.certificatePhotoFrontWatermark
        },
        tipsB: {
          title: '',
          type: 'string',
          ui: {
            widget: 'custom',
            offsetControl: 6,
          },
        },
        certificatePhotoBackWatermark: {
          type: 'string',
          title: '',
          readOnly: (this.i.id && (this.i.driverLicenseStatus === 10 || this.i.driverLicenseStatus === 20)) || this.readFlag,
          ui: {
            offsetControl: 6,
            action: apiConf.fileUpload,
            accept: 'image/png,image/jpeg,image/jpg,image/gif',
            limit: 1,
            limitFileCount: 1,
            resReName: 'data.fullFileWatermarkPath',
            urlReName: 'data.fullFileWatermarkPath',
            widget: 'upload',
            descriptionI18n: '图片支持jpg、jpeg、png、gif格式，大小不超过2M',
            data: {
              appId: this.envSrv.env.appId,
            },
            name: 'multipartFile',
            multiple: false,
            listType: 'picture-card',
            change: (args: any) => {
              if (args.type === 'success') {
                this.detailData.identityInfoDTO.certificatePhotoBack = args.file.response.data.fullFilePath
              } else {
                this.detailData.identityInfoDTO.certificatePhotoBack = ''
              }
            },
            beforeUpload: (file: any, _fileList: any) => {
              return new Observable((observer: Observer<boolean>) => {
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isLt2M) {
                  this.service.msgSrv.warning('图片大小超过2M!');
                  observer.complete();
                  return;
                }
                observer.next(isLt2M);
                observer.complete();
              });
            },
            previewFile: (file: any) => { }
          },
          default: this.detailData.identityInfoDTO.certificatePhotoBackWatermark
        },
        certificateNumber: {
          title: '身份证号',
          type: 'string',
          readOnly: (this.i.id && (this.i.driverLicenseStatus === 10 || this.i.driverLicenseStatus === 20)) || this.readFlag,
          ui: {
            widget: this.i.id && (this.i.driverLicenseStatus !== 10 && this.i.driverLicenseStatus !== 20) ? 'text' : '',
            placeholder: '请输入身份证号',
          },
          default: this.detailData.identityInfoDTO.certificateNumber
        },
        remark: {
          title: '备注',
          type: 'string',
          maxLength: 100,
          ui: {
            widget: 'textarea',
            placeholder: '请输入备注',
            autosize: { minRows: 2, maxRows: 6 },
          },
          default: this.detailData.remark
        },
      },
      required: ['name', 'mobile', 'bankCardNo', 'certificateNumber', 'certificatePhotoBackWatermark', 'certificatePhotoFrontWatermark'],
    };
    this.ui = {
      '*': {
        spanLabelFixed: 120,
        grid: { span: 24 },
      },
    };
    // setTimeout(() => {
    //   if (this.readFlag) {
    //     this.detailData.identityInfoDTO.certificatePhotoFrontWatermark = [
    //       {
    //         uid: -1,
    //         name: 'LOGO',
    //         status: 'done',
    //         url: this.detailData.certificatePhotoFrontWatermark,
    //         response: this.detailData.certificatePhotoFrontWatermark,
    //       },
    //     ];
    //     this.detailData.identityInfoDTO.certificatePhotoBackWatermark = [
    //       {
    //         uid: -1,
    //         name: 'LOGO',
    //         status: 'done',
    //         url: this.detailData.certificatePhotoBackWatermark,
    //         response: this.detailData.certificatePhotoBackWatermark,
    //       },
    //     ];
    //     this.sf.setValue('/mobile', this.detailData.mobile)
    //     this.sf.setValue('/name', this.detailData.name)
    //     this.sf.setValue('/certificateNumber', this.detailData.certificateNumber)
    //     this.sf.setValue('/certificatePhotoFrontWatermark', this.detailData.identityInfoDTO.certificatePhotoFrontWatermark)
    //     this.sf.setValue('/certificatePhotoBackWatermark', this.detailData.identityInfoDTO.certificatePhotoBackWatermark)
    //   }
    // }, 500)

  }

  checkIdCard(imgurl: any, side: any) {
    // 识别身份证 参数side：0-正面、1-背面；type：0-申请人身份证，1-法定代表人身份证
    const params = {
      idCardUrl: imgurl,
      side,
    };
    this.service.request(this.service.$api_checkIdCard, params).subscribe((res) => {
      if (res) {
        this.sf.setValue('/name', res.name);
        this.sf.setValue('/certificateNumber', res.number);
      }
    });
  }
  close(): void {
    this.modal.destroy();
  }
  changeEndKmAction() {
    this.changeSub.pipe(debounceTime(500)).subscribe((res: string) => {
      if (res) {
        const params: any = {
          bankCardNo: this.sf.value.bankCardNo,
          bankName: this.sf.value.bankName,
          mobile: this.sf.value.mobile,
          remark: this.sf.value.remark,
          identityInfoDTO: {
            certificatePhotoBackWatermark: this.sf.value?.certificatePhotoBackWatermark?.data?.fullFilePath || this.sf.value?.certificatePhotoBackWatermark,
            certificatePhotoFrontWatermark: this.sf.value?.certificatePhotoFrontWatermark?.data?.fullFilePath ||this.sf.value?.certificatePhotoFrontWatermark,
            certificatePhotoFront: this.detailData.certificatePhotoFront,
            certificatePhotoBack: this.detailData.certificatePhotoBack,
            certificateNumber: this.sf.value.certificateNumber,
            name: this.sf.value.name,
          }
        }
        if (this.i.id) {
          params.id = this.i.id
        }
        delete params.showName
        this.service.request(this.service.$api_saveCaptainr_new, params).subscribe(res => {
          if (res) {
            this.service.msgSrv.success('保存成功')
            this.modal.close(true)
          }
        })
      }
    });
  }
  sure() {
    this.changeSub.next('500');
  }
}
