import { Component, OnInit, ViewChild } from '@angular/core';
import { apiConf } from '@conf/api.conf';
import { cacheConf } from '@conf/cache.conf';
import { SFComponent, SFUISchema, SFSchema, SFUploadWidgetSchema, SFDateWidgetSchema } from '@delon/form';
import { _HttpClient } from '@delon/theme';
import { EACacheService, EAEnvironmentService } from '@shared';
import { AnyRecord } from 'dns';
import { NzModalRef } from 'ng-zorro-antd/modal';
import { NzUploadFile } from 'ng-zorro-antd/upload';
import { Observable, Observer, of } from 'rxjs';
import { map } from 'rxjs/operators';
import { SupplyManagementService } from '../../services/supply-management.service';
@Component({
  selector: 'app-car-add-driver',
  templateUrl: './add-driver.component.html',
  styleUrls: ['./add-driver.component.less']
})
export class CarAddDriverComponent implements OnInit {
  @ViewChild('sf', { static: false }) sf!: SFComponent;
  @ViewChild('sf1', { static: false }) sf1!: SFComponent;
  @ViewChild('sf2', { static: false }) sf2!: SFComponent;
  record: any = {};
  i: any;
  ui: SFUISchema = {};
  ui2: SFUISchema = {};
  ui3: SFUISchema = {};
  schema: SFSchema = {};
  schema1: SFSchema = {};
  schema2: SFSchema = {};
  showCardFlag = false;
  showJopFlag = false;
  detailData: any = {
    identityInfoDTO: {},
    userDriverLicenseDTO: {},
    userPracticeSeniorityDTO: {}
  };
  companyData: any = {};
  mobile = ''
  checked = false
  constructor(
    private modal: NzModalRef,
    public service: SupplyManagementService,
    private envSrv: EAEnvironmentService,
    private eaCacheSrv: EACacheService,
  ) { }

  ngOnInit(): void {
    this.companyData = this.eaCacheSrv.get(cacheConf.env)
    this.initSF()
  }
  initSF() {
    this.schema = {
      properties: {
        titleA: {
          title: '司机信息(必填）',
          type: 'string',
          ui: {
            widget: 'text',
          },
          default: '照片上传后会自动识别文字并填充下列内容栏'
        },
        mobile: {
          title: '手机号',
          type: 'string',
          maxLength: 11,
          ui: {
            widget: '', 
          },
          default: this.mobile
        },
        showName: {
          title: '身份证照片',
          type: 'string',
          readOnly: true,
          ui: {
            widget: 'textarea',
            borderless:true,
            showRequired: true,
          },
          default: '请上传身份证原件的高清照片，若上传复印件，则需加盖公司印章及法人签字；上传后系统会自动识别并填写',
        },
        tipsA: {
          title: '',
          type: 'string',
          ui: {
            widget: 'custom',
            offsetControl: 6,
          },
        },
        certificatePhotoFrontWatermark: {
          type: 'string',
          title: '',
          ui: {
            offsetControl: 6,
            action: apiConf.waterFileUpload,
            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') {
                const avatar = [
                  {
                    uid: -1,
                    name: 'LOGO',
                    status: 'done',
                    url: args.file.response.data.fullFileWatermarkPath,
                    response: {
                      url: args.file.response.data.fullFileWatermarkPath,
                    },
                  },
                ];
                this.sf?.setValue('/certificatePhotoFrontWatermark', avatar);
                this.detailData.certificatePhotoFront = args.file.response.data.fullFilePath
                this.checkIdCard(args.file.response.data.fullFilePath, 'front', 0);
              } else {
                this.detailData.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: NzUploadFile) => of(file.url),
          },
        },
        tipsB: {
          title: '',
          type: 'string',
          ui: {
            widget: 'custom',
            offsetControl: 6,
          },
        },
        certificatePhotoBackWatermark: {
          type: 'string',
          title: '',
          ui: {
            offsetControl: 6,
            action: apiConf.waterFileUpload,
            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') {
                const avatar = [
                  {
                    uid: -1,
                    name: 'LOGO',
                    status: 'done',
                    url: args.file.response.data.fullFileWatermarkPath,
                    response: {
                      url: args.file.response.data.fullFileWatermarkPath,
                    },
                  },
                ];
                this.sf?.setValue('/certificatePhotoBackWatermark', avatar);
                this.detailData.certificatePhotoBack = args.file.response.data.fullFilePath
                this.checkIdCard(args.file.response.data.fullFilePath, 'back', 0);
              } else {
                this.detailData.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: NzUploadFile) => of(file.url),}
        },
        name: {
          title: '姓名',
          type: 'string',
          maxLength: 32,
          ui: {
            widget: '',
            placeholder: '请输入姓名',
          },
        },
        certificateNumber: {
          title: '身份证号',
          type: 'string',
          format: 'id-card',
          minLength: 1,
          maxLength: 18,
          ui: {
            widget: '',
            placeholder: '请输入法定代表人证件号',
            errors: {
              required: '请输入18位身份证号码',
            },
          },
        },
      },
      required: [
        'certificatePhotoFrontWatermark',
        'certificatePhotoBackWatermark',
        'name',
        'certificateNumber'
      ],
    };
    this.schema1 = {
      properties: {
        titleB: {
          title: '驾驶证信息(必填）',
          type: 'string',
          ui: {
            widget: 'text',
          },
          default: '照片上传后会自动识别文字并填充下列内容栏'
        },
        certificatePhotoWatermark: {
          type: 'string',
          title: '驾驶证照片',
          ui: {
            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、PNG格式，文件小于5M。照片信息缺失、拼凑、过度PS、模糊不清，都不会通过审核。',
            data: {
              appId: this.envSrv.env.appId,
            },
            name: 'multipartFile',
            multiple: false,
            listType: 'picture-card',
            change: (args: any) => {
              if (args.type === 'success') {
                this.detailData.userDriverLicenseDTO.certificatePhoto = args.file.response.data.fullFilePath
                this.checkDriverCard(args.file.response.data.fullFilePath, 'front', 0);
              } else {
                this.detailData.userDriverLicenseDTO.certificatePhoto = ''
              }
            },
            beforeUpload: (file: any, _fileList: any) => {
              return new Observable((observer: Observer<boolean>) => {
                const isLt4M = file.size / 1024 / 1024 < 5;
                if (!isLt4M) {
                  this.service.msgSrv.warning('图片大小超过5M!');
                  observer.complete();
                  return;
                }
                observer.next(isLt4M);
                observer.complete();
              });
            },
           previewFile: (file: NzUploadFile) => of(file.url),}
        },
        roadImg: {
          title: '',
          type: 'boolean',
          // enum: [{ label: '长期', value: true }],
          ui: {
            widget: 'custom',
          }
        },
        licenseNo: {
          title: '驾驶证号',
          type: 'string',
          ui: {
           // widget: 'text',
           placeholder: '请输入',
          },
          // default: this.ar.snapshot.queryParams.licenseNo
        },
        driverModel: {
          title: '准驾车型',
          type: 'string',
          ui: {
            widget: 'select',
            mode: 'multiple',
            containsAllLabel: false,
            placeholder: '请选择准驾车型',  
            asyncData: () => 
              this.service.request(this.service.$api_getDictValue, { dictKey: 'driverModel' }).pipe(
                map((data: any) => {
                  return data.map((m: any) => {
                    return { label: m.label, value: m.label };
                  });
                }),
              ),        
          },
        },
        validStartTime: {
          title: '有效期起',
          type: 'string',
          ui: {
            widget: 'date',
            format: 'yyyy-MM-dd',
            placeholder: '请选择',
            errors: {
              required: '请选择起始日期',
            },
            change: (i) => { },
          } as SFDateWidgetSchema,
        },
        validEndTime: {
          title: '有效期止',
          type: 'string',
          ui: {
            widget: 'date',
            format: 'yyyy-MM-dd',
            placeholder: '请选择',
            errors: {
              required: '请选择终止日期',
            },
            change: (i) => { },
          } as SFDateWidgetSchema,
        },
        signingOrganization: {
          title: '签发机关',
          type: 'string',
          maxLength: 30,
          ui: {
            // widget: this.detailData.commitFlag !== 0 ? 'text' : '',
            placeholder: '请输入',
          },
        },
      },
      required: [
        'certificatePhotoWatermark',
        'licenseNo',
        'driverModel',
        'validStartTime',
        'validEndTime',
      ],
    };
    this.schema2 = {
      properties: {
        titleC: {
          title: '从业资格证(选填）',
          type: 'string',
          ui: {
            widget: 'text',
          },
          default: '照片上传后会自动识别文字并填充下列内容栏',
        },
        certificatePhotoWatermark: {
          type: 'string',
          title: '',
          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格式，大小不超过5M',
            data: {
              appId: this.envSrv.env.appId,
            },
            name: 'multipartFile',
            multiple: false,
            listType: 'picture-card',
            change: (args: any) => {
              if (args.type === 'success') {
                this.detailData.userPracticeSeniorityDTO.certificatePhoto = args.file.response.data.fullFilePath
                this.checkQualificationCertificate(args.file.response.data.fullFilePath);
              } else{
                this.detailData.userPracticeSeniorityDTO.certificatePhoto = ''
              }
            },
            beforeUpload: (file: any, _fileList: any) => {
              return new Observable((observer: Observer<boolean>) => {
                const isLt2M = file.size / 1024 / 1024 < 5;
                if (!isLt2M) {
                  this.service.msgSrv.warning('图片大小超过5M!');
                  observer.complete();
                  return;
                }
                observer.next(isLt2M);
                observer.complete();
              });
            },
           previewFile: (file: NzUploadFile) => of(file.url),}
        },
        agreeImg: {
          title: '',
          type: 'boolean',
          // enum: [{ label: '长期', value: true }],
          ui: {
            widget: 'custom',
          }
        },
        licenseNo: {
          title: '从业资格证号',
          type: 'string',
          maxLength: 30,
          ui: {
            // widget: this.detailData.commitFlag !== 0 ? 'text' : '',
            placeholder: '请输入',
          },
        },
        regionCode: {
          title: '签发省份',
          type: 'string',
          ui: {
            widget: 'select',
            placeholder: '请选择',
            asyncData: () => this.getProvinceData(),
          } as SFDateWidgetSchema,
        },
        validStartTime: {
          title: '发证日期',
          type: 'string',
          ui: {
            widget: 'date',
            format: 'yyyy-MM-dd',
            placeholder: '请选择',
            errors: {
              required: '请选择起始日期',
            },
            change: (i) => { },
          } as SFDateWidgetSchema,
        },
        validEndTime: {
          title: '有效期止',
          type: 'string',
          ui: {
            widget: 'date',
            format: 'yyyy-MM-dd',
            placeholder: '请选择',
            errors: {
              required: '请选择终止日期',
            },
            change: (i) => { },
          } as SFDateWidgetSchema,
        },
      },
      required: [
        
      ],
    };
    this.ui = {
      '*': {
        spanLabelFixed: 180,
        grid: { span: 24 },
        width: 700,
      },
    };
    this.ui2 = {
      '*': {
        spanLabelFixed: 180,
        grid: { span: 18 },
        width: 600,
      },
      $titleB:{
        grid: { span: 24 },
      },
      $certificatePhotoWatermark: {
        grid: { span: 12 },
      },
      $roadImg: {
        grid: { span: 4 },
        class: 'setCustom'
      },
    };
    this.ui3 = {
      '*': {
        spanLabelFixed: 180,
        grid: { span: 18 },
        width: 600,
      },
      $titleC:{
        grid: { span: 24 },
      },
      $certificatePhotoWatermark: {
        grid: { span: 12 },
      },
      $agreeImg: {
        grid: { span: 4 },
        class: 'setCustom'
      },
    };
  }
  checkQualificationCertificate(imgurl: any) {
    // 识别从业资格证 参数side：0-正面、1-背面；type：0-申请人身份证，1-法定代表人身份证
    const params = {
      qualificationCertificateUrl: imgurl,
    };
    this.service.request(this.service.$api_recognizeQualificationCertificate, params).subscribe((res: any) => {
      if (res) {
        this.sf2.setValue('/licenseNo', res.certificateNumber);
        this.sf2.setValue('/regionCode', res.addressRegionCodes[0]);
        res.qualificationCategoryList.forEach((item: any) => {
          console.log(item.category.indexOf('道路货物运输驾驶员') !== -1)
          if (item.category.indexOf('道路货物运输驾驶员') !== -1) {
            this.sf2.setValue('/validStartTime', item.initialIssueDate.split(' ')[0]);
            this.sf2.setValue('/validEndTime', item.expiryDate.split(' ')[0]);
          }
        })
        
      }
    });
  }
  getProvinceData() {
    return this.service.request(this.service.$api_getRegionByCode, { regionCode: '' }).pipe(
      map((res: any) => {
        const result: any = []
        if (res) {
          res.map((m: any) => {
            const item = { label: m.name, value: m.regionCode }
            result.push(item)
          });
        }
        return result
      })
    );
  }
  checkIdCard(imgurl: any, side: any, type: any) {
    // 识别身份证 参数side：0-正面、1-背面；type：0-申请人身份证，1-法定代表人身份证
    const params = {
      idCardUrl: imgurl,
      side,
    };
    this.service.request(this.service.$api_checkIdCard, params).subscribe((res: any)=> {
      if (res) {
        if (type === 0) {
          // 法定代表人身份证
          if (side === 'front') {
            // 正面
            this.sf.setValue('/name', res.name);
            this.sf.setValue('/certificateNumber', res.number);
          }
        }
      }
    });
  }
  checkDriverCard(imgurl: any, side: any, type: any) {
    // 识别身份证 参数side：0-正面、1-背面；type：0-申请人身份证，1-法定代表人身份证
    const params = {
      driverLicenseUrl: imgurl,
      side,
    };
    this.service.request(this.service.$api_recognizeDriverLicense, params).subscribe((res: any) => {
      if (res) {
        if (type === 0) {
          // 法定代表人身份证
          if (side === 'front') {
            // 正面
            this.sf1.setValue('/licenseNo', res.number);
            this.sf1.setValue('/driverModel', [(res.classType).toUpperCase()]);
            this.sf1.setValue('/validStartTime', res.validFrom);
            this.sf1.setValue('/validEndTime', res.validTo);
            this.sf1.setValue('/signingOrganization', res.issuingAuthority);
          }
        }
      }
    });
  }
  close(): void {
    this.modal.destroy();
  }
  showExample(){
    this.showCardFlag = !this.showCardFlag
  }
  showJopExample(){
    this.showJopFlag = !this.showJopFlag
  }
  submitForm(){
    const params:any = {
      source: 1,
      mobile: this.sf.value.mobile,
      identityInfoDTO:{
        ...this.sf.value,
        certificatePhotoFront: this.detailData.certificatePhotoFront,
        certificatePhotoBack: this.detailData.certificatePhotoBack,
      },
      userDriverLicenseDTO: {
        ...this.sf1.value,
        certificatePhoto: this.detailData.userDriverLicenseDTO.certificatePhoto,
      },
      userPracticeSeniorityDTO: {
        ...this.sf2.value,
        certificatePhoto: this.detailData.userPracticeSeniorityDTO.certificatePhoto,
      },
    };
    if(params.userPracticeSeniorityDTO.certificatePhoto === '' || params.userPracticeSeniorityDTO.certificatePhotoWatermark === '') {
      delete params.userPracticeSeniorityDTO.certificatePhotoWatermark
      delete params.userPracticeSeniorityDTO.certificatePhoto
    }
    params.userDriverLicenseDTO.driverModel = params.userDriverLicenseDTO.driverModel.join(',')
    delete params.identityInfoDTO.showName;
    delete params.identityInfoDTO.titleA;
    delete params.userDriverLicenseDTO.titleB;
    delete params.userPracticeSeniorityDTO.titleC;
    delete params.userDriverLicenseDTO.tipsA;
    delete params.userPracticeSeniorityDTO.tipsC;
    if(JSON.stringify(params.userPracticeSeniorityDTO) === '{}') {
      params.userPracticeSeniorityDTO = null
    }
    this.checked = true
    this.service.request(this.service.$api_enterpriseVehicleSave, params).subscribe((res: any) => {
      this.checked = false
      if(res){
        this.service.msgSrv.success('添加成功')
        this.modal.close(true)
      }
    })
  }
}
