import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { apiConf } from '@conf/api.conf';
import {
  SFCascaderWidgetSchema,
  SFCheckboxWidgetSchema,
  SFComponent,
  SFDateWidgetSchema,
  SFSchema,
  SFSchemaEnum,
  SFTextareaWidgetSchema,
  SFUISchema,
  SFUploadWidgetSchema
} from '@delon/form';
import { NzMessageService } from 'ng-zorro-antd/message';
import { UsermanageService } from 'src/app/routes/usercenter/services/usercenter.service';

const IMAGECONFIG = {
  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'
};

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

@Component({
  selector: 'app-account-components-freight-new',
  templateUrl: './new.component.html',
  styleUrls: ['./new.component.less']
})
export class FreightComponentsListNewComponent implements OnInit {
  @ViewChild('sf', { static: false })
  sf!: SFComponent;
  @ViewChild('sf1', { static: false })
  sf1!: SFComponent;
  schema: SFSchema = this.initOthersSF();
  schema1: SFSchema = this.initBasicInfoSF();
  ui: SFUISchema = {
    '*': {
      spanLabelFixed: 180,
      grid: { span: 24 }
    },
    $title1: {
      spanLabelFixed: 0
    },
    $title99: {
      spanLabelFixed: 0
    },
    $title2: {
      spanLabelFixed: 0
    },
    $registrationCapital: {
      spanLabelFixed: 180,
      grid: { xxl: 13, xl: 18, lg: 24, md: 24 }
    },
    $unit: {
      spanLabelFixed: 100,
      grid: { span: 6 }
    },
    $isLoingDate: {
      spanLabelFixed: 100,
      grid: { span: 6 }
    }
  };

  constructor(private router: Router, private service: UsermanageService) {}
  ngOnInit() {}

  submitForm() {
    const sfVlaue = this.sf.value;
    const params = {};
    Object.assign(
      params,
      { ...this.sf1.value },
      { ...this.sf.value },
      {
        enterpriseAddressCode: this.sf1.value.enterpriseAddressCode[2],
        oftenUsedServices: sfVlaue.oftenUsedServices,
        registerAddress: sfVlaue.registerAddress,
        registerPhone: sfVlaue.registerPhone,
        creditPhoto: sfVlaue.creditPhoto,
        creditPhotoWatermark: sfVlaue.creditPhotoWatermark,
        promotersTelephone: sfVlaue.promotersTelephone,
        networkTransporter: sfVlaue.networkTransporter,
        adminUserInfo: {
          certificateNumber: sfVlaue.certificateNumber,
          certificatePhotoBack: sfVlaue.certificatePhotoBack,
          certificatePhotoBackWatermark: sfVlaue.certificatePhotoBackWatermark,
          certificatePhotoFront: sfVlaue.certificatePhotoFront,
          certificatePhotoFrontWatermark: sfVlaue.certificatePhotoFrontWatermark,
          name: sfVlaue.name
        }
      }
    );
    this.service.request(this.service.$api_save_enterprise_admin, params).subscribe(res => {
      if (res) {
        this.service.msgSrv.success('企业新增成功');
        this.goBack();
      }
    });
  }

  /*
   * 根据地区code查询地区详情
   * code：请求参数
   * type：参数 name：获取省市区名称，fullcode：获取省市区code
   * num：参数 1：第一个地区选择，2：第二个地区选择
   */
  getRegionDetailByCode(regionCode: any) {
    // 根据地区code查询地区详情
    return this.service.request(this.service.$api_get_region_by_code, { regionCode });
  }

  longTime(i: boolean | SFSchemaEnum[], type: string) {
    if (type === 'schema') {
      if (i) {
        // this.sf?.setValue('/validStartTime', Date);
        this.sf?.setValue('/validEndTime', Date);
        // this.sf.getProperty('/validStartTime').schema.readOnly = true;
        this.sf.getProperty('/validEndTime')!.schema.readOnly = true;
      } else {
        // this.sf.getProperty('/validStartTime').schema.readOnly = false;
        this.sf.getProperty('/validEndTime')!.schema.readOnly = false;
      }
    }
    if (type === 'schema1') {
      if (i) {
        // this.sf1?.setValue('/operatingStartTime', Date);
        this.sf1?.setValue('/operatingEndTime', Date);
        // this.sf1.getProperty('/operatingStartTime').schema.readOnly = true;
        this.sf1.getProperty('/operatingEndTime')!.schema.readOnly = true;
      } else {
        // this.sf1.getProperty('/operatingStartTime').schema.readOnly = false;
        this.sf1.getProperty('/operatingEndTime')!.schema.readOnly = false;
      }
    }
    if (type === 'schema11') {
      if (i) {
        // this.sf1?.setValue('/validStartTime', Date);
        this.sf1?.setValue('/validEndTime', Date);
        // this.sf1.getProperty('/validStartTime').schema.readOnly = true;
        this.sf1.getProperty('/validEndTime')!.schema.readOnly = true;
      } else {
        // this.sf1.getProperty('/validStartTime').schema.readOnly = false;
        this.sf1.getProperty('/validEndTime')!.schema.readOnly = false;
      }
    }
  }

  checkIdCard(imgurl: any, isFront: number, type: number) {
    // 识别身份证 参数isFront：0-正面、1-背面；type：0-申请人身份证，1-法定代表人身份证
    const params = {
      idCardImagePath: imgurl,
      isFront
    };
    // this.service.request(this.service.$api_checkIdCard, params).subscribe((res) => {
    //   if (res) {
    //     if (type === 0) {
    //       // 申请人身份证
    //       if (isFront === 0) {
    //         // 正面
    //         if (res.name) {
    //           this.sf.setValue('/name', res.name);
    //         }
    //         if (res.idCardNumber) {
    //           this.sf.setValue('/certificateNumber', res.idCardNumber);
    //         }
    //       }
    //       if (isFront === 1) {
    //         // 背面
    //         if (res.validFrom) {
    //           this.sf.setValue('/validStartTime', res.validFrom);
    //         }
    //         if (res.validTo) {
    //           this.sf.setValue('/validEndTime', res.validTo);
    //         }
    //       }
    //     }
    //     if (type === 1) {
    //       // 法定代表人身份证
    //       if (isFront === 0) {
    //         // 正面
    //         if (res.name) {
    //           this.sf1.setValue('/name', res.name);
    //         }
    //         if (res.idCardNumber) {
    //           this.sf1.setValue('/certificateNumber', res.idCardNumber);
    //         }
    //       }
    //       if (isFront === 1) {
    //         // 背面
    //         if (res.validFrom) {
    //           this.sf1.setValue('/validStartTime', res.validFrom);
    //         }
    //         if (res.validTo) {
    //           this.sf1.setValue('/validEndTime', res.validTo);
    //         }
    //       }
    //     }
    //   }
    // });
  }
  checkBusinessLicense(imgurl: any) {
    // 识别营业执照
    const params = {
      licenseImagePath: imgurl
    };
    // this.service.request(this.service.$api_checkBusinessLicense, params).subscribe((res) => {
    //   if (res) {
    //     if (res.unifiedSocialCreditCode) {
    //       this.sf1.setValue('/unifiedSocialCreditCode', res.unifiedSocialCreditCode);
    //     }
    //     if (res.enterpriseName) {
    //       this.sf1.setValue('/enterpriseName', res.enterpriseName);
    //     }
    //     if (res.enterpriseType) {
    //       this.sf1.setValue('/enterpriseType', res.enterpriseType);
    //     }
    //     if (res.addressRegionCodes) {
    //       this.sf1.setValue('/region', res.addressRegionCodes);
    //     }
    //     if (res.address) {
    //       this.sf1.setValue('/enterpriseAddress', res.address);
    //     }
    //     if (res.foundDate) {
    //       this.sf1.setValue('/enterpriseRegistrationTime', res.foundDate);
    //     }
    //     if (res.registeredCapital) {
    //       this.sf1.setValue('/registrationCapital', res.registeredCapital);
    //     }
    //     if (res.businessTermStartDate) {
    //       this.sf1.setValue('/operatingStartTime', res.businessTermStartDate);
    //     }
    //     if (res.businessTermEndDate) {
    //       this.sf1.setValue('/operatingEndTime', res.businessTermEndDate);
    //     }
    //     if (res.businessScope) {
    //       this.sf1.setValue('/businessScope', res.businessScope);
    //     }
    //     const len = res.addressRegionCodes.length - 1;
    //     this.enterpriseAddressCode = res.addressRegionCodes[len];
    //     this.enterpriseAddressCodeStr = res.addressRegionNames;
    //     if (!res.businessTermEndDate) {
    //       this.sf1.setValue('/dateType', true);
    //     }
    //   }
    // });
  }

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

  private initBasicInfoSF(): SFSchema {
    return {
      properties: {
        title1: { title: '', type: 'string', ui: { widget: 'custom' } },
        tips: { title: '', type: 'string', ui: { widget: 'custom', offsetControl: 6 } },
        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.sf1.setValue('/licensePhoto', args.fileList[0].response.data.fullFilePath);
                this.checkBusinessLicense(args.fileList[0].response.data.fullFileWatermarkPath);
              }
            }
          } as SFUploadWidgetSchema
        },
        unifiedSocialCreditCode: {
          title: '统一社会信用代码',
          type: 'string',
          minLength: 1,
          maxLength: 18,
          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: '请输入公司名称'
            }
          }
        },
        enterpriseType: {
          title: '公司类型',
          type: 'string',
          minLength: 1,
          maxLength: 30,
          ui: {
            grid: { xxl: 13, xl: 18, lg: 24, md: 24 },
            placeholder: '请输入公司类型',
            errors: {
              required: '请输入公司类型'
            }
          }
        },
        enterpriseAddressCode: {
          type: 'number',
          title: '营业执照所在地',
          ui: {
            grid: { xxl: 13, xl: 18, lg: 24, md: 24 },
            widget: 'cascader',
            valueProperty: 'regionCode',
            labelProperty: 'name',
            asyncData: (node: any, index: any) => {
              return new Promise(resolve => {
                this.getRegionDetailByCode(node?.regionCode || '').subscribe(
                  res => {
                    node.children = res.map((item: any) => ({ ...item, isLeaf: index === 1 }));
                  },
                  _ => {},
                  () => {
                    resolve();
                  }
                );
              });
            }
          } as SFCascaderWidgetSchema
        },
        enterpriseAddress: {
          title: '营业执照详细地址',
          type: 'string',
          minLength: 1,
          maxLength: 240,
          ui: {
            grid: { xxl: 13, xl: 18, lg: 24, md: 24 },
            widget: 'textarea',
            autosize: { minRows: 2, maxRows: 5 },
            placeholder: '请输入营业执照上的完整详细地址',
            errors: {
              required: '请输入营业执照上的完整详细地址'
            }
          } as SFTextareaWidgetSchema
        },
        registrationCapital: {
          title: '注册资本',
          type: 'number',
          minimum: 1,
          maximum: 99999999999999999999,
          ui: {
            grid: { xxl: 13, xl: 18, lg: 24, md: 24 },
            placeholder: '请输入营业执照上的注册资本',
            errors: {
              required: '请输入营业执照上的注册资本'
            },
            precision: 0
          }
        },
        unit: { title: '', type: 'string', ui: { widget: 'text', class: 'input-back' }, default: '万元' },
        enterpriseRegistrationTime: {
          title: '成立日期',
          type: 'string',
          ui: {
            ...DATECONFIG,
            errors: {
              required: '请选择开始日期'
            }
          } as SFDateWidgetSchema
        },
        operatingEndTime: {
          title: '营业期限',
          type: 'string',
          ui: {
            ...DATECONFIG,
            errors: {
              required: '请选择截止日期'
            },
            change: i => {
              this.sf1?.setValue('/isLoingDate', false);
            }
          } as SFDateWidgetSchema
        },
        isLoingDate: {
          title: '长期',
          type: 'boolean',
          ui: { class: 'input-back', widget: 'checkbox', change: i => this.longTime(i, 'schema11') } as SFCheckboxWidgetSchema
        },
        businessScope: {
          title: '经营范围',
          type: 'string',
          minLength: 1,
          maxLength: 240,
          ui: {
            grid: { xxl: 13, xl: 18, lg: 24, md: 24 },
            widget: 'textarea',
            autosize: { minRows: 3, maxRows: 5 },
            placeholder: '请输入营业执照上的营经营范围',
            errors: {
              required: '请输入营业执照上的营经营范围'
            }
          } as SFTextareaWidgetSchema
        },
        taxAuthority: {
          title: '税务机关',
          type: 'string',
          minLength: 1,
          maxLength: 30,
          ui: {
            grid: { xxl: 13, xl: 18, lg: 24, md: 24 },
            placeholder: '请输入营业执照上的税务机关',
            errors: {
              required: '请输入营业执照上的税务机关'
            }
          }
        },

        legalPersonIdentityDTO: {
          type: 'object',
          properties: {
            title2: { title: '', type: 'string', ui: { widget: 'custom' } },
            tipsC: { title: '法定代表人证件照', type: 'string', ui: { widget: 'custom' } },
            tipsA: { 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.sf1.setValue('/legalPersonIdentityDTO/certificatePhotoFront', args.fileList[0].response.data.fullFilePath);
                    this.checkIdCard(args.fileList[0].response.data.fullFileWatermarkPath, 0, 1);
                  }
                }
              } as SFUploadWidgetSchema
            },
            tipsB: { 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.sf1.setValue('/legalPersonIdentityDTO/certificatePhotoBack', args.fileList[0].response.data.fullFilePath);
                    this.checkIdCard(args.fileList[0].response.data.fullFileWatermarkPath, 0, 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.sf1?.setValue('/isLoingDate', false);
                }
              } as SFDateWidgetSchema
            },
            isLoingDate: {
              title: '长期',
              type: 'boolean',
              ui: {
                spanLabelFixed: 100,
                grid: { span: 6 },
                class: 'input-back',
                widget: 'checkbox',
                change: i => this.longTime(i, 'schema11')
              } as SFCheckboxWidgetSchema
            }
          },
          required: [
            'tipsC',
            'certificatePhotoFront',
            'certificatePhotoBack',
            'name',
            'certificateType',
            'certificateNumber',
            'validStartTime',
            'validEndTime'
          ]
        }
      },
      required: [
        'licensePhotoWatermark',
        'unifiedSocialCreditCode',
        'enterpriseName',
        'enterpriseType',
        'enterpriseAddressCode',
        'enterpriseAddress',
        'registrationCapital',
        'enterpriseRegistrationTime',
        'operatingEndTime',
        'operatingStartTime',
        'businessScope'
      ]
    };
  }

  private initOthersSF(): SFSchema {
    return {
      properties: {
        title1: { title: '', type: 'string', ui: { widget: 'custom' } },
        createBank: {
          title: '开户银行',
          type: 'string',
          ui: { grid: { xxl: 13, xl: 18, lg: 24, md: 24 }, placeholder: '请输入银行账号' }
        },
        bankAccount: {
          title: '银行账号',
          type: 'string',
          ui: { grid: { xxl: 13, xl: 18, lg: 24, md: 24 }, placeholder: '请输入银行账号' }
        },
        registerAddress: {
          title: ' 注册地址',
          type: 'string',
          ui: { grid: { xxl: 13, xl: 18, lg: 24, md: 24 }, placeholder: '请输入注册地址' }
        },
        registerPhone: {
          title: ' 注册电话',
          type: 'string',
          ui: { grid: { xxl: 13, xl: 18, lg: 24, md: 24 }, placeholder: '请输入注册电话' }
        },

        title99: { title: '', type: 'string', ui: { widget: 'custom' } },
        adminMobile: {
          title: ' 企业管理员手机号',
          type: 'string',
          ui: { grid: { xxl: 13, xl: 18, lg: 24, md: 24 }, placeholder: '请输入业务员电话' }
        },
        tipsA: {
          title: '企业管理员证件照',
          type: 'string',
          ui: {
            widget: 'custom'
          }
        },
        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('/certificatePhotoFront', args.fileList[0].response.data.fullFilePath);
                this.checkIdCard(args.fileList[0].response.data.fullFileWatermarkPath, 0, 1);
              }
            }
          } as SFUploadWidgetSchema
        },
        tipsB: {
          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('/certificatePhotoBack', args.fileList[0].response.data.fullFilePath);
                this.checkIdCard(args.fileList[0].response.data.fullFileWatermarkPath, 0, 1);
              }
            }
          } 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: '请输入法定代表人身份证号码'
          }
        },
        tipsD: { title: '企业授权函', type: 'string', ui: { widget: 'custom' }, default: 1 },
        creditPhoto: { title: '', type: 'string', ui: { hidden: true } },
        creditPhotoWatermark: {
          type: 'string',
          title: '',
          ui: {
            ...IMAGECONFIG,
            descriptionI18n: '图片支持jpg、jpeg、png、gif格式，大小不超过5M',
            change: args => {
              if (args.type === 'success') {
                this.sf.setValue('/creditPhoto', args.fileList[0].response.data.fullFilePath);
                this.checkIdCard(args.fileList[0].response.data.fullFileWatermarkPath, 0, 1);
              }
            }
          } as SFUploadWidgetSchema
        },
        oftenUsedServices: {
          type: 'string',
          title: '常用服务',
          enum: [
            { label: '整车发货', value: 10 },
            { label: '大宗发货', value: 20 }
          ],
          default: '',
          ui: {
            grid: { xxl: 13, xl: 18, lg: 24, md: 24 },
            widget: 'select',
            visibleIf: {
              expand: (value: boolean) => value
            }
          }
        },
        promotersTelephone: {
          title: '推广业务员手机号',
          type: 'string',
          minLength: 1,
          maxLength: 32,
          ui: {
            grid: { xxl: 13, xl: 18, lg: 24, md: 24 },
            placeholder: '请输入您的真实姓名',
            errors: {
              required: '请输入您的真实姓名'
            }
          }
        },
        networkTransporter: {
          type: 'string',
          title: '网络货运人',
          enum: [
            { label: '全部', value: 0 },
            { label: '大宗发货', value: 20 }
          ],
          default: 0,
          ui: {
            grid: { xxl: 13, xl: 18, lg: 24, md: 24 },
            widget: 'select',
            visibleIf: {
              expand: (value: boolean) => value
            }
          }
        }
      },
      required: ['createBank', '银行账号', 'adminMobile', 'name', 'certificateNumber', 'tipsD', 'creditPhoto']
    };
  }
}
