import { Component, OnInit, ViewChild } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import differenceInCalendarDays from 'date-fns/differenceInCalendarDays';
import format from 'date-fns/format';
import { Subject } from 'rxjs';
import { ActivatedRoute, Router } from '@angular/router';
import {
  SFCheckboxWidgetSchema,
  SFComponent,
  SFNumberWidgetSchema,
  SFSchema,
  SFSchemaEnum,
  SFSelectWidgetSchema,
  SFTextareaWidgetSchema,
  SFUISchema
} from '@delon/form';
import { _HttpClient } from '@delon/theme';
import { AmapPoiPickerComponent, AmapService, EACacheService, ShipperBaseService } from '@shared';
import { NzModalService } from 'ng-zorro-antd/modal';
import { of } from 'rxjs';
import { map } from 'rxjs/operators';
import { SupplyManagementService } from '../../services/supply-management.service';
import { SupplyManagementVehicleAssignedCarComponent } from '../assigned-car/assigned-car.component';
import { TranAgreementComponent } from '../tran-agreement/tran-agreement.component';
import { PublishAddressListComponent } from './address-list/address-list.component';
import { PublishSuccessComponent } from './publish-success/publish-success.component';
import { cacheConf } from '@conf/cache.conf';

@Component({
  selector: 'app-publish-goods-onecar-publish',
  templateUrl: './onecar-publish.component.html',
  styleUrls: ['./onecar-publish.component.less']
})
export class SupplyManagementOnecarPublishComponent implements OnInit {
  // 环境信息 appId、tenantId
  envInfo = this.eaCacheSrv.get(cacheConf.env);
  validateForm1: FormGroup;
  limitValues = {
    maxWeight: 99999,
    maxVolume: 99999,
    maxPiece: 99999,
    maxDays: 999,
    intervalDays: 999,
    maxTimes: 5
  };
  sf1data: any; // 货源单设置回显
  sf3data: any; // 货源单设置回显
  sf4data: any; // 货源单设置回显
  sf5data: any; // 货源单设置回显
  sf55data: any; // 货源单设置回显
  sf6data: any; // 货源单设置回显
  sf7data: any; // 货源单设置回显
  creatTime: any; // 货源单设置回显
  loadingTime: any; // 货源单设置回显
  unloadingTime: any; // 货源单设置回显
  totalFees: any; // 总数信息
  totalDistance = 0.0; //总里程
  totalTime = 0.0; //路程总时间
  currentRate = 0; //实时计算的费率
  id = this.route.snapshot.params.id;
  startInfo: any = []; // 发货地数据
  endInfo: any = []; // 卸货地数据
  PageStatus = '';
  shipperName = '';
  changeSub = new Subject<string>();
  envCache: any;
  enterpriseProjectIds: any;
  constructor(
    private http: _HttpClient,
    fb: FormBuilder,
    private router: Router,
    private route: ActivatedRoute,
    private modalService: NzModalService,
    public service: SupplyManagementService,
    private amapService: AmapService,
    public shipperSrv: ShipperBaseService,
    private eaCacheSrv: EACacheService
  ) {
    this.validateForm1 = fb.group({
      loadingTime: [null, [Validators.required]],
      unloadingTime: [null, [Validators.required]]
    });
    this.envCache = this.eaCacheSrv.get(cacheConf.env);
  }
  @ViewChild('sf1', { static: false }) sf1!: SFComponent;
  schema1: SFSchema = {};
  ui1!: SFUISchema;

  @ViewChild('sf2', { static: false }) sf2!: SFComponent;
  schema2: SFSchema = {};
  ui2!: SFUISchema;

  @ViewChild('sf3', { static: false }) sf3!: SFComponent;
  schema3: SFSchema = {};
  ui3!: SFUISchema;

  @ViewChild('sf4', { static: false }) sf4!: SFComponent;
  schema4: SFSchema = {};
  ui4!: SFUISchema;

  @ViewChild('sf5', { static: false }) sf5!: SFComponent;
  schema5: SFSchema = {};
  ui5!: SFUISchema;

  @ViewChild('sf55', { static: false }) sf55!: SFComponent;
  schema55: SFSchema = {};
  ui55!: SFUISchema;

  @ViewChild('sf6', { static: false }) sf6!: SFComponent;
  schema6: SFSchema = {};
  ui6!: SFUISchema;

  @ViewChild('sf7', { static: false }) sf7!: SFComponent;
  schema7: SFSchema = {};
  ui7!: SFUISchema;

  formatterRmb = (value: number): string => {
    if (value === null || value === undefined) {
      return '';
    } else {
      let value2 = Number(value).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
      return `￥${value2}`;
    }
  };
  parserRmb = (value: string): string => value.replace('￥', '').replace(',', '');

  // 页面初始化
  ngOnInit(): void {
    if (this.route.snapshot?.queryParams?.sta === '1') {
      this.PageStatus = '整车修改';
    } else if (this.route.snapshot?.queryParams?.sta === '2') {
      this.PageStatus = '整车下一单';
    }
    this.initSF1();
    this.initSF3();
    this.initSF4();
    this.initSF5();
    this.initSF6();
    this.initSF7();
    this.getLimitvalue();
    this.initdata();
  }
  initSF1() {
    this.schema1 = {
      properties: {
        resourceCode: {
          type: 'string',
          title: '',
          ui: { hidden: true }
        },
        shipperAppUserId: {
          title: '货主',
          type: 'string',
          maxLength: 30,
          readOnly: this.PageStatus == '整车修改' ? true : false,
          ui: {
            widget: 'select',
            // serverSearch: true,
            allowClear: true,
            searchDebounceTime: 300,
            searchLoadingText: '搜索中...',
            onSearch: (q: any) => {
              let str = q?.replace(/^\s+|\s+$/g, '');
              if (str) {
                return this.service
                  .request(this.service.$api_enterpriceList, { enterpriseName: str })
                  .pipe(map(res => (res as any[]).map(i => ({ label: i.enterpriseName, value: i.id } as SFSchemaEnum))))
                  .toPromise();
              } else {
                return of([]);
              }
            },
            change: (q: any, qs: any) => {
              let str = q?.replace(/^\s+|\s+$/g, '');
              if (str) {
                this.getRegionCode(str);
                this.shipperName = qs?.label;
                this.payChange();
              }
            }
          } as SFSelectWidgetSchema
        },
        enterpriseProjectId: {
          type: 'string',
          title: '项目',
          readOnly: this.PageStatus == '整车修改' ? true : false,
          ui: {
            widget: 'select',
            placeholder: '请选择'
          } as SFSelectWidgetSchema
        },
        enterpriseInfoName: {
          type: 'string',
          title: '网络货运人',
          ui: {
            widget: 'text'
          }
        },

        externalResourceCode: {
          type: 'string',
          title: '外部货源号',
          maxLength: 30,
          ui: {
            placeholder: '请输入'
          }
        },
        dispatchName: {
          type: 'string',
          title: '调度员姓名',
          maxLength: 30,
          ui: {
            optionalHelp: '选若未填写，司机直接联系您',
            placeholder: '请输入'
          }
        },
        dispatchPhone: {
          type: 'string',
          title: '调度员手机号',
          maxLength: 30,
          ui: {
            placeholder: '请输入'
          }
        }
        // dispatchId: {
        //   type: 'string',
        //   title: '调度员',
        //   ui: {
        //     widget: 'select',
        //     placeholder: '请选择',
        //     allowClear: true,
        //     optionalHelp: '选择调度员，司机直接联系调度员 ; 不选择，司机直接联系您',
        //     change: (_value: any, data: any) => {
        //       if (data.label) {
        //         const dat = data.label.split('/');
        //         this.sf1.setValue('/dispatchName', dat[0]);
        //         this.sf1.setValue('/dispatchPhone', dat[1]);
        //       }
        //     },
        //     asyncData: () => this.shipperSrv.getStaffList2()
        //   } as SFSelectWidgetSchema
        // },
      },
      required: ['shipperAppUserId', 'enterpriseProjectId']
    };
    this.ui1 = {
      '*': {
        spanLabelFixed: 115,
        grid: { span: 12 }
      },
      $enterpriseInfoName: {
        grid: { span: 12 }
      },
      $shipperAppUserId: {
        grid: { span: 12 }
      },
      $enterpriseProjectId: {
        grid: { span: 12 }
      }
    };
  }
  initSF3() {
    this.schema3 = {
      properties: {
        goodsTips: {
          type: 'string',
          title: '',
          ui: {
            widget: 'custom',
            class: 'goods_Tips_item',
            // visibleIf: {
            //   goodsTypeName: (value: any) => value && value === '其它'
            // }
          }
        },
        goodsTypeId: {
          type: 'string',
          title: '货物名称',
          ui: {
            widget: 'select',
            placeholder: '请选择',
            errors: { required: '请选择货物类型' },
            asyncData: () =>
              this.shipperSrv.loadConfigByKey('goods.name.config.type').pipe(
                map((data: any) => {
                  return data[0].children?.map((m: any) => {
                    return { label: m.name, value: m.id };
                  });
                })
              ),
            change: (value, data: any) => {
              this.changeGoodsType(value, data);
              this.sf3.setValue('/goodsTypeName', data.label);
            }
          } as SFSelectWidgetSchema
        },
        goodsTypeName: {
          type: 'string',
          title: '',
          ui: {
            hidden: true
          }
        },
        goodsNameId: {
          type: 'string',
          title: '',
          ui: {
            widget: 'select',
            placeholder: '请选择',
            errors: { required: '请填写货物名称' },
            change: (_value: any, data: any) => {
              this.sf3.setValue('/goodsName', data.label);
            },
            visibleIf: {
              goodsTypeName: (value: any) => value && value !== '其它'
            }
          }
        },
        goodsName: {
          type: 'string',
          title: '',
          ui: {
            hidden: true,
            visibleIf: {
              goodsTypeName: (value: any) => value && value !== '其它'
            }
          }
        },
        goodsName1: {
          type: 'string',
          title: '',
          maxLength: 20,
          ui: {
            errors: { required: '请填写货物名称' },
            visibleIf: {
              goodsTypeName: (value: any) => value && value === '其它'
            },
            blur: (value: any) => {
              this.checkGoodsName();
            }
          }
        }
      },
      required: ['goodsTypeId', 'goodsName', 'goodsNameId', 'goodsName1']
    };
    this.ui3 = {
      '*': {
        spanLabelFixed: 90,
        grid: { span: 12 }
      },
      $goodsTips: {
        grid: { span: 24 }
      }
    };
  }
  initSF4() {
    this.schema4 = {
      properties: {
        weight: {
          type: 'string',
          title: '货物数量',
          ui: {
            widget: 'custom',
            placeholder: '请输入',
            errors: { required: '必填项' },
            validator: val => this.customValidator(val)
          }
        },
        volume: {
          type: 'string',
          title: '',
          ui: {
            widget: 'custom',
            placeholder: '请输入'
          }
        },
        number: {
          type: 'string',
          title: '',
          ui: {
            widget: 'custom',
            placeholder: '请输入'
          }
        },
        carModel: {
          type: 'string',
          title: '车型/车长',
          ui: {
            widget: 'select',
            mode: 'multiple',
            maxMultipleCount: 3,
            placeholder: '请选择车型',
            errors: { required: '请选择车型' },
            asyncData: () => this.service.getDictOptions({ dictKey: 'car:model' }),
            change: (tag: any, org: any) => {
              if (tag.includes('999')) {
                this.sf4.setValue('/carModel', ['999']);
              }
            }
          }
        },
        carLength: {
          type: 'string',
          title: '',
          ui: {
            widget: 'select',
            mode: 'multiple',
            maxMultipleCount: 3,
            placeholder: '请选择车长',
            errors: { required: '请选择车长' },
            asyncData: () => this.service.getDictOptions({ dictKey: 'car:length' }),
            change: (tag: any, org: any) => {
              if (tag.includes('999')) {
                this.sf4.setValue('/carLength', ['999']);
              }
            }
          }
        },
        hidenField: {
          type: 'string',
          title: '',
          default: ' ',
          ui: {
            widget: 'text'
          }
        },
        insurancePackagedGoods: {
          type: 'string',
          title: '货物包装',
          ui: {
            widget: 'dict-select',
            params: { dictKey: 'insure:packaged:goods' },
            containsAllLabel: false,
            validator: val => {
              if (this.sf5?.value?.insuranceType && this.sf5?.value?.insuranceType !== '3' && this.isEmpty(val)) {
                return [{ keyword: 'required', message: '必填项' }];
              } else {
                return [];
              }
            }
          } as SFSelectWidgetSchema
        },
        goodsValue: {
          type: 'string',
          title: '货物价值',
          ui: {
            widget: 'custom',
            validator: val => {
              if (this.sf5?.value?.insuranceType && this.sf5?.value?.insuranceType !== '3' && this.isEmpty(val)) {
                return [{ keyword: 'required', message: '必填项' }];
              } else {
                return [];
              }
            }
          }
        }
      },
      required: ['weight', 'carModel', 'carLength']
    };
    this.ui4 = {
      '*': {
        spanLabelFixed: 115,
        grid: { span: 8 }
      }
    };
  }


  initSF5() {
    this.schema5 = {
      properties: {
        insuranceType: {
          type: 'string',
          title: '服务包',
          ui: {
            widget: 'select',
            asyncData: () => {
              return this.service.request(this.service.$api_getDictValue, { dictKey: 'bill:insurance:type' }).pipe(
                map((res: any) => {
                  return [...res];
                })
              )
            },
            change: (tag: any, org: any) => {
              if (tag === '3') {
                this.sf5.setValue('/insurancePremium', null);
                this.sf5.setValue('/insuranceRate', null);
              } else {
                this.getInsurersPrice(tag);
              }
            }
          },
          default: '3'
        },
        type1: {
          type: 'string',
          title: '',
          ui: {
            widget: 'custom',
            visibleIf: { insuranceType: (value: string) => value === '0' }
          },
        },
        type2: {
          type: 'string',
          title: '',
          ui: {
            widget: 'custom',
            visibleIf: { insuranceType: (value: string) => value === '1' }
          }
        },
        insurancePremium: {
          type: 'string',
          title: '服务包费用',
          readOnly: true,
          ui: {
            visibleIf: { insuranceType: (value: string) => value !== '3' }
          }
        },
        insuranceRate: {
          type: 'string',
          title: '保险费率',
          ui: {
            hidden: true
          }
        },
        freeInsurance1: {
          type: 'string',
          title: '预投基本险',
          ui: {
            widget: 'custom',
            visibleIf: { insuranceType: (value: string) => value === '0' }
          }
        },
        freeInsurance2: {
          type: 'string',
          title: '预投综合险',
          ui: {
            widget: 'custom',
            visibleIf: { insuranceType: (value: string) => value === '1' }
          }
        },
      },
      required: ['insurancePremium']
    };
    this.ui5 = {
      '*': {
        spanLabelFixed: 115,
        grid: { span: 12 }
      },
      $type1: {
        grid: { span: 24 }
      },
      $type2: {
        grid: { span: 24 }
      },
      $freeInsurance1: {
        grid: { span: 24 }
      },
      $freeInsurance2: {
        grid: { span: 24 }
      }
    };
  }

  /**
   * 自定义校验数据
   * @param val
   */
  customValidator(val: number) {
    if (this.isEmpty(val)) {
      return [{ keyword: 'required', message: '不能为空' }];
    } else {
      if (val <= 0) {
        return [{ keyword: 'required', message: '数值需大于0' }];
      }
      return [];
    }
  }
  isEmpty(val: any) {
    return val === undefined || val === null || val.toString().trim() === '';
  }
  initSF6() {
    this.schema6 = {
      properties: {
        stateReceipt: {
          type: 'string',
          title: '是否回单',
          enum: [
            { label: '需要', value: true },
            { label: '不需要', value: false }
          ],
          ui: {
            widget: 'select',
            errors: { required: '请选择' },
            placeholder: '请选择'
          }
        },
        receiptType: {
          type: 'string',
          title: '回单类型',
          ui: {
            widget: 'dict-select',
            params: { dictKey: 'receipt:type' },
            containsAllLabel: false,
            placeholder: '请选择',
            errors: { required: '请选择' },
            visibleIf: {
              stateReceipt: value => value === true
            }
          }
        },
        receiptUserName: {
          type: 'string',
          title: '联系人',
          maxLength: 15,
          ui: {
            visibleIf: {
              receiptType: value => value === '2'
            }
          }
        },
        receiptUserPhone: {
          type: 'string',
          title: '联系电话',
          maxLength: 11,
          ui: {
            visibleIf: {
              receiptType: value => value === '2'
            }
          }
        },
        receiptAddressArea: {
          type: 'string',
          title: '所在地区',
          maxLength: 30,
          ui: {
            visibleIf: {
              receiptType: value => value === '2'
            }
          }
        },
        receiptAddress: {
          type: 'string',
          title: '详细地址',
          maxLength: 30,
          ui: {
            visibleIf: {
              receiptType: value => value === '2'
            }
          }
        },
        remarks: {
          type: 'string',
          title: '备注',
          maxLength: 200,
          ui: {
            widget: 'textarea',
            placeholder: '请输入',
            autosize: { minRows: 3, maxRows: 3 }
          } as SFTextareaWidgetSchema
        }
      },
      required: ['stateReceipt', 'receiptType', 'receiptUserName', 'receiptUserPhone', 'receiptAddressArea', 'receiptAddress']
    };
    this.ui6 = {
      '*': {
        spanLabelFixed: 90,
        grid: { span: 24 }
      }
    };
  }

  initSF7() {
    this.schema7 = {
      properties: {
        prePay: {
          type: 'number',
          title: '预付',
          ui: { widget: 'custom' }
        },
        toPay: {
          type: 'number',
          title: '到付',
          ui: { widget: 'custom' }
        },
        receiptPay: {
          type: 'number',
          title: '回单付',
          ui: { widget: 'custom' }
        },
        subtotal: { type: 'number', title: '小计', default: 0, ui: { widget: 'custom' } as SFNumberWidgetSchema },
        appendFee: { type: 'number', title: '附加费', default: 0, ui: { widget: 'custom' } as SFNumberWidgetSchema },
        total: { type: 'number', title: '总费用', default: 0, ui: { widget: 'custom' } as SFNumberWidgetSchema },
        paymentDays: {
          type: 'string',
          title: '到货后',
          ui: {
            widget: 'custom',
            errors: { required: '请输入付款承诺天数' }
          }
        }
      },
      required: ['paymentDays']
    };
    this.ui7 = {
      '*': {
        spanLabelFixed: 115,
        grid: { span: 24 }
      }
    };
  }
  getRegionCode(regionCode: any) {
    return this.service
      .request(this.service.$api_get_enterprise_project, { id: regionCode })
      .pipe(
        map(res =>
          res.map((item: any) => ({
            label: item.projectName,
            value: item.id
          }))
        )
      )
      .subscribe(res => {
        this.sf1.getProperty('/enterpriseProjectId')!.schema.enum = res;
        this.sf1.getProperty('/enterpriseProjectId')!.widget.reset(res);
        if (this.enterpriseProjectIds) {
          this.sf1.setValue('/enterpriseProjectId', this.enterpriseProjectIds);
        }
      });
  }
  payChange() {
    const prePay = this.sf7.value.prePay || 0;
    const toPay = this.sf7.value.toPay || 0;
    const receiptPay = this.sf7.value.receiptPay || 0;
    const oilCardPay = 0;
    const subtotal = prePay + toPay + receiptPay;
    const params = {
      shipperId: this?.sf1?.value?.shipperAppUserId,
      enterpriseInfoId: this?.sf1data?.enterpriseInfoId || '',
      totalFreight: subtotal,
      fuelCardAmount: oilCardPay,
      resourcetype: '1'
    };
    this.service.request(this.service.$api_getCalculatedSurcharge, params).subscribe(res => {
      if (res) {
        this.sf7.setValue('/appendFee', res.surcharge);
        this.sf7.setValue('/subtotal', subtotal);
        this.sf7.setValue('/total', subtotal + res.surcharge);
        let items = this?.sf1data?.enterpriseInfoId || '';
        this.service
          .request(
            this.service.$api_getAdditionalRate +
            `?shipperId=${this?.sf1?.value?.shipperAppUserId || ''}&enterpriseInfoId=${items}&resourcetype='1'`
          )
          .subscribe(res => {
            if (res) {
              this.currentRate = res.rate * 100;
            }
          });
      } else {
        this.service.msgSrv.error(res.msg);
      }
    });
  }
  addStartInfo() {
    if (this.startInfo.length < this.limitValues.maxTimes) {
      const controlId = this.startInfo.length;
      this.startInfo.push({
        detailedAddress: '',
        appUserName: '',
        contractTelephone: '',
        latitude: '',
        longitude: '',
        province: '',
        city: '',
        area: '',
        type: '1'
      });
      this.validateForm1.addControl(`loadAddress${controlId}`, new FormControl(null, Validators.required));
      this.validateForm1.addControl(`loadName${controlId}`, new FormControl(null, Validators.required));
      this.validateForm1.addControl(`loadPhone${controlId}`, new FormControl(null, [Validators.required, Validators.pattern('^[0-9]*$')]));
    }
  }

  getLimitvalue() {
    // 货物核载信息最大值
    // 货物运输费（小计）最大值
    const getlimitvaluesParms = [
      this.service?.limitKeys?.weight,
      this.service?.limitKeys?.volume,
      this.service?.limitKeys?.piece,
      this.service?.limitKeys?.maxDays,
      this.service?.limitKeys?.intervalDays,
      this.service?.limitKeys?.maxTimes
    ];
    this.service.request(this.service.$api_findItemValueByItemKeys, getlimitvaluesParms).subscribe(res => {
      const maxWeight = res.filter((item: any) => item.itemKey === this.service.limitKeys?.weight)[0].itemValue;
      const maxVolume = res.filter((item: any) => item.itemKey === this.service.limitKeys?.volume)[0].itemValue;
      const maxPiece = res.filter((item: any) => item.itemKey === this.service.limitKeys?.piece)[0].itemValue;
      const maxDays = res.filter((item: any) => item.itemKey === this.service.limitKeys?.maxDays)[0].itemValue;
      const intervalDays = res.filter((item: any) => item.itemKey === this.service.limitKeys?.intervalDays)[0].itemValue;
      const maxTimes = res.filter((item: any) => item.itemKey === this.service.limitKeys?.maxTimes)[0].itemValue;
      this.limitValues = {
        maxWeight: Number(maxWeight),
        maxVolume: Number(maxVolume),
        maxPiece: Number(maxPiece),
        maxDays: Number(maxDays),
        intervalDays: Number(intervalDays),
        maxTimes: Number(maxTimes)
      };
    });
  }
  subStartInfo(event: any, index: number) {
    this.startInfo.splice(index, 1);
    this.validateForm1.removeControl(`loadAddress${index}`);
    this.validateForm1.removeControl(`loadName${index}`);
    this.validateForm1.removeControl(`loadPhone${index}`);
  }
  addEndInfo() {
    if (this.endInfo.length < this.limitValues.maxTimes) {
      const controlId = this.endInfo.length;
      this.endInfo.push({
        detailedAddress: '',
        appUserName: '',
        contractTelephone: '',
        latitude: '',
        longitude: '',
        province: '',
        city: '',
        area: '',
        type: '2'
      });
      this.validateForm1.addControl(`unloadAddress${controlId}`, new FormControl(null, Validators.required));
      this.validateForm1.addControl(`unloadName${controlId}`, new FormControl(null, Validators.required));
      this.validateForm1.addControl(
        `unloadPhone${controlId}`,
        new FormControl(null, [Validators.required, Validators.pattern('^[0-9]*$')])
      );
    }
  }
  subEndInfo(event: any, index: number) {
    this.endInfo.splice(index, 1);
    this.validateForm1.removeControl(`unloadAddress${index}`);
    this.validateForm1.removeControl(`unloadName${index}`);
    this.validateForm1.removeControl(`unloadPhone${index}`);
  }
  changeGoodsType(value: string, data: any) {
    if (data.label === '其它') return;
    const params = {
      pageIndex: 1,
      pageSize: 100,
      configId: value
    };
    this.service
      .request(this.service.$api_get_config_item_page, params)
      .pipe(
        map(data => {
          return data.records?.map((m: any) => {
            return { label: m.name, value: m.id };
          });
        })
      )
      .subscribe(res => {
        if (res) {
          this.sf3.getProperty('/goodsNameId')!.schema.enum = res;
          this.sf3.getProperty('/goodsNameId')!.widget.reset(res);
          if (this.sf3data.goodsNameId) {
            this.sf3.setValue('/goodsNameId', this.sf3data.goodsNameId);
          }
        } else {
          this.service.msgSrv.error(res.msg);
        }
      });
  }
  //指派熟车
  chooseFamifiar(item: any) {
    const modalRef = this.modalService.create({
      nzTitle: '指派熟车',
      nzContent: SupplyManagementVehicleAssignedCarComponent,
      nzWidth: 1200,
      nzComponentParams: {
        status: 'new',
        url: this.service.$api_save_assign_whole,
        params: item
      },
      nzFooter: null
    });
    modalRef.afterClose.subscribe(result => {
      if (result) {
        this.openFinishPage(result);
      }
    });
  }
  // 打开下单完成页面
  openFinishPage(resourceObj: any = null, change?: any) {
    this.modalService.create({
      nzTitle: '',
      nzContent: PublishSuccessComponent,
      nzWidth: 900,
      nzFooter: null,
      nzComponentParams: { type: 'onecar', resourceObj, change: change }
    });
  }
  // 提交前确认，委托运输协议弹窗
  submitConfirm(submitType?: string) {
    Object.keys(this.validateForm1.controls).forEach(key => {
      this.validateForm1.controls[key].markAsDirty();
      this.validateForm1.controls[key].updateValueAndValidity();
    });
    this.sf3.validator({ emitError: true });
    this.sf4.validator({ emitError: true });
    this.sf5.validator({ emitError: true });
    this.sf6.validator({ emitError: true });
    this.sf7.validator({ emitError: true });
    if (
      this.validateForm1.invalid ||
      !this.sf3.valid ||
      !this.sf1.valid ||
      !this.sf4.valid ||
      !this.sf5.valid ||
      !this.sf6.valid ||
      !this.sf7.valid
    ) {
      this.service.msgSrv.warning('请完善必填项！');
      return;
    }
    if (this.totalDistance <= 0) {
      this.service.msgSrv.warning('起终点相同，请重新选择装卸货地址！');
      return;
    }
    let date1 = this.validateForm1.value.loadingTime
    let date2 = new Date()
    let min = date1.getMinutes()
    date1.setMinutes(min+10)
    if (date1 < date2 ) {
      this.service.msgSrv.warning('装货时间必须大于当前时间！');
      return;
    }
    
    if (this.validateForm1.value.loadingTime > this.validateForm1.value.unloadingTime) {
      this.service.msgSrv.warning('装货时间不能大于卸货时间！');
      return;
    }
    if (this.sf7.value.total <= 0) {
      this.service.msgSrv.warning('总费用不能为0！');
      return;
    }
    const num = (Number(this.validateForm1.value.unloadingTime) - Number(this.validateForm1.value.loadingTime)) / (24 * 60 * 60 * 1000);
    if (num > this.limitValues.maxDays) {
      this.service.msgSrv.error(`当前计划装卸货时间间隔已超出限定值【${this.limitValues?.maxDays}天】`);
      return;
    }
    if (
      this.sf4.value?.weight > this.limitValues?.maxWeight ||
      this.sf4.value?.volume > this.limitValues?.maxVolume ||
      this.sf4.value?.number > this.limitValues?.maxPiece
    ) {
      this.service.msgSrv.error(
        `当前货物核载信息已超出限定值【${this.limitValues?.maxWeight}吨、${this.limitValues?.maxVolume}方、${this.limitValues?.maxPiece}件】`
      );
      return;
    }

    const getFreightParms = { carLengthKeys: this.sf4.value.carLength, km: this.totalDistance };
    this.service.request(this.service.$api_getFreight, getFreightParms).subscribe(res => {
      if (this.sf7.value.subtotal > res.maxPrice) {
        this.service.msgSrv.error(`运费过高，请调整录入`);
        return;
      } else if (this.sf7.value.subtotal > res.ewPrice) {
        this.modalService.confirm({
          nzTitle: '',
          nzContent: `您的录入的运费过高，可能会影响支付，请仔细确认`,
          nzOkText: '继续',
          nzCancelText: '取消',
          nzOnOk: () => {
            this.agreementConfirm(submitType);
          }
        });
      } else {
        this.agreementConfirm(submitType);
      }
    });
  }
  // 提交前协议弹窗
  agreementConfirm(submitType?: string) {
    //装卸货信息
    const LoadingList = this.startInfo.concat(this.endInfo);

    // 货物信息
    const sf3Values = { ...this.sf3.value };
    if (sf3Values.goodsTypeName === '其它') {
      sf3Values.goodsName = sf3Values.goodsName1;
      delete sf3Values.goodsName1;
    }
    if (this.sf4.value.carModel.includes('999')) {
      this.sf4.value.carModel = ['999'];
    }
    if (this.sf4.value.carLength.includes('999')) {
      this.sf4.value.carLength = ['999'];
    }
    const goodsInfoVOList = [
      {
        ...sf3Values,
        ...this.sf4.value,
        carModel: this.sf4.value.carModel.join(','),
        carLength: this.sf4.value.carLength.join(',')
      }
    ];
    // 运费信息
    const expenseList = [
      { expenseCode: 'PRE', expenseName: '预付', price: this.sf7.value.prePay || 0, id: this.sf7data?.prePayId || '', resourceId: this.sf7data?.PREresourceId || '' },
      { expenseCode: 'RECE', expenseName: '到付', price: this.sf7.value.toPay || 0, id: this.sf7data?.toPayId || '', resourceId: this.sf7data?.RECEresourceId || '' },
      { expenseCode: 'BACK', expenseName: '回单付', price: this.sf7.value.receiptPay || 0, id: this.sf7data?.receiptPayId || '', resourceId: this.sf7data?.BACKresourceId || '' }
    ];
    // 从“再下一单”过来，将所有的子参数内的id都删除
    if (this.PageStatus === '整车下一单') {
      delete this.sf1.value.resourceCode;

      LoadingList.forEach((ele: any) => {
        delete ele.id;
      });
      goodsInfoVOList.forEach((ele: any) => {
        delete ele.id;
      });
      expenseList.forEach((ele: any) => {
        delete ele.id;
      });
    }
    const params = {
      id: '',
      ...this.sf1.value,
      unLoadingPlaceDTOList: LoadingList,
      unloadingTime: format(this.validateForm1.value.unloadingTime, 'yyyy-MM-dd HH:mm:ss'),
      loadingTime: format(this.validateForm1.value.loadingTime, 'yyyy-MM-dd HH:mm:ss'),
      goodsInfoDTOList: goodsInfoVOList,
      ...this.sf5.value,
      ...this.sf6.value,
      expenseDTOList: expenseList,
      paymentDays: this.sf7.value.paymentDays,
      estimatedKilometers: this.totalDistance,
      estimatedTravelTime: this.totalTime,
      subtotal: this.sf7.value.subtotal,
      total: this.sf7.value.total,
      insurancePackagedGoods: this.sf4.value.insurancePackagedGoods,
      goodsValue: this.sf4.value.goodsValue
    };
    const modalRef = this.modalService.create({
      nzTitle: '运输协议',
      nzContent: TranAgreementComponent,
      nzWidth: 900,
      nzFooter: null,
      nzComponentParams: { object: params, shipperName: this.shipperName, type: 'onecar' }
    });
    modalRef.afterClose.subscribe(result => {
      if (result) {
        this.submit(submitType, params);
      }
    });
  }
  // 提交
  submit(submitType?: string, params?: any): void {
    if (submitType) {
      if (submitType == 'assign') {
        this.chooseFamifiar(params);
        return;
      }
    }
    if (this.PageStatus === '整车修改') {
      this.requests(this.service.$api_set_WholeModify, params, 1);
    } else if (this.PageStatus === '整车下一单') {
      this.requests(this.service.$api_set_saveAnotherWholeOrder, params, 2);
    }
  }
  // 补0函数
  addPreZero(num: any) {
    if (num < 10) {
      return '0' + num;
    } else {
      return num;
    }
  }
  // 下单成功提示弹窗
  requests(url: any, params: any, change?: any) {
    this.service.request(url, params).subscribe((res: any) => {
      if (res) {
        this.modalService.create({
          nzTitle: '',
          nzContent: PublishSuccessComponent,
          nzWidth: 900,
          nzFooter: null,
          nzComponentParams: { type: 'onecar', change: change }
        });
      }
    });
  }
  // 打开地图
  openMap(type: string, index: number) {
    console.log(type);
    console.log(index);
    const modalRef = this.modalService.create({
      nzTitle: '',
      nzContent: AmapPoiPickerComponent,
      nzWidth: 900,
      nzOnOk: item => {
        console.log(item);
        if (item?.poi) {
          const poi = item.poi;
          const locList = poi.pois;
          switch (type) {
            case 'start':
              this.startInfo[index].detailedAddress = poi.formattedAddress;
              this.startInfo[index].longitude = locList[0];
              this.startInfo[index].latitude = locList[1];
              this.startInfo[index].province = poi.addressComponent.province;
              this.startInfo[index].city = poi.addressComponent.city;
              this.startInfo[index].area = poi.addressComponent.district;
              this.startInfo[index].address = poi.formattedAddress;
              break;
            case 'end':
              this.endInfo[index].detailedAddress = poi.formattedAddress;
              this.endInfo[index].longitude = locList[0];
              this.endInfo[index].latitude = locList[1];
              this.endInfo[index].province = poi.addressComponent.province;
              this.endInfo[index].city = poi.addressComponent.city;
              this.endInfo[index].area = poi.addressComponent.district;
              this.endInfo[index].address = poi.formattedAddress;
              break;
            default:
              break;
          }

          if (this.startInfo[0]?.area && this.endInfo[0]?.area) {
            this.amapService.drivingCompute([...this.startInfo], [...this.endInfo]).subscribe((res: any) => {
              this.totalDistance = res.distance;
              this.totalTime = res.time;
              this.getInsurersPrice(); // 计算保费金额
            });
          }
          return true
        } else {
          this.service.msgSrv.warning('请重新手动选择地址！')
          return false
        }
      }
    });
  }
  // 返回上一页
  goBack() {
    window.history.go(-1);
  }
  // 初始化赋值信息
  initdata() {
    this.service.request(`${this.service.$api_get_getCompleteVehicleDetail}`, { id: this.id }).subscribe(res => {
      this.dataR(res);
    });
  }
  // 初始化赋值信息函数
  dataR(res: any) {
    if (res?.shipperAppUserName) {
      this.shipperName = res?.shipperAppUserName;
      const List: any = [];
      this.service.request(this.service.$api_enterpriceList, { enterpriseName: res?.shipperAppUserName }).subscribe(rs => {
        rs?.forEach((element: any) => {
          List.push({ label: element.enterpriseName, value: element.id });
        });
        this.sf1.getProperty('/shipperAppUserId')!.schema.enum = List;
        this.sf1.getProperty('/shipperAppUserId')!.widget.reset(List);
        if (res?.shipperAppUserId) {
          this.sf1.setValue('/shipperAppUserId', res?.shipperAppUserId);
          this.getRegionCode(res?.shipperAppUserId);
        }
      });
    }
    if (res?.enterpriseProjectId) {
      this.enterpriseProjectIds = res.enterpriseProjectId;
    }
    this.totalDistance = res?.estimatedKilometers;
    this.totalTime = res?.estimatedTravelTime;
    this.sf1data = {
      resourceCode: res?.resourceCode || '',
      enterpriseInfoName: res?.enterpriseInfoName,
      enterpriseInfoId: res?.enterpriseInfoId,
      dispatchPhone: res?.dispatchPhone,
      dispatchName: res?.dispatchName,
      externalResourceCode: res?.externalResourceCode
    };
    if (this.PageStatus === '整车修改') {
      this.sf1data.id = res?.id;
    }
    res?.unLoadingPlaceVOList.forEach((element: any) => {
      if (element.type === 1 || element.type === '1') {
        const controlId = this.startInfo.length;
        if (this.PageStatus === '整车修改') {
          this.startInfo.push({
            detailedAddress: element.detailedAddress,
            appUserName: element.appUserName,
            contractTelephone: element.contractTelephone,
            latitude: element.latitude,
            longitude: element.longitude,
            province: element.province,
            city: element.city,
            area: element.area,
            type: element.type,
            id: element.id
          });
        } else {
          this.startInfo.push({
            detailedAddress: element.detailedAddress,
            appUserName: element.appUserName,
            contractTelephone: element.contractTelephone,
            latitude: element.latitude,
            longitude: element.longitude,
            province: element.province,
            city: element.city,
            area: element.area,
            type: element.type
          });
        }

        this.validateForm1.addControl(`loadAddress${controlId}`, new FormControl(null, Validators.required));
        this.validateForm1.addControl(`loadName${controlId}`, new FormControl(null, Validators.required));
        this.validateForm1.addControl(`loadPhone${controlId}`, new FormControl(null, Validators.required));
      } else if (element.type === 2 || element.type === '2') {
        const controlId = this.endInfo.length;
        if (this.PageStatus === '整车修改') {
          this.endInfo.push({
            detailedAddress: element?.detailedAddress,
            appUserName: element?.appUserName,
            contractTelephone: element?.contractTelephone,
            latitude: element.latitude,
            longitude: element.longitude,
            province: element.province,
            city: element.city,
            area: element.area,
            type: element.type,
            id: element.id
          });
        } else {
          this.endInfo.push({
            detailedAddress: element?.detailedAddress,
            appUserName: element?.appUserName,
            contractTelephone: element?.contractTelephone,
            latitude: element.latitude,
            longitude: element.longitude,
            province: element.province,
            city: element.city,
            area: element.area,
            type: element.type
          });
        }
        this.validateForm1.addControl(`unloadAddress${controlId}`, new FormControl(null, Validators.required));
        this.validateForm1.addControl(`unloadName${controlId}`, new FormControl(null, Validators.required));
        this.validateForm1.addControl(`unloadPhone${controlId}`, new FormControl(null, Validators.required));
      }

      // 计算里程，时间
      if (this.startInfo[0]?.detailedAddress && this.endInfo[0]?.detailedAddress) {
        this.amapService.drivingCompute([...this.startInfo], [...this.endInfo]).subscribe(res => {
          this.totalDistance = res.distance;
          this.totalTime = res.time;
          this.getInsurersPrice(); //计算保费金额
        });
      }
    });

    this.sf3data = {
      goodsTypeId: res?.goodsInfoVOList[0]?.goodsTypeId || '',
      goodsTypeName: res?.goodsInfoVOList[0]?.goodsTypeName || '',
      goodsNameId: res?.goodsInfoVOList[0]?.goodsNameId || '',
      goodsName: res?.goodsInfoVOList[0]?.goodsName || ''
    };
    if (this.sf3data.goodsTypeName === '其它') {
      this.sf3data.goodsName1 = res?.goodsInfoVOList[0]?.goodsName || '';
    }
    this.changeGoodsType(this.sf3data.goodsTypeId, { label: this.sf3data.goodsTypeName, value: this.sf3data.goodsTypeId });

    if (res?.loadingTime) {
      this.loadingTime = res?.loadingTime;
    }
    if (res?.unloadingTime) {
      this.unloadingTime = res?.unloadingTime;
    }
    this.validateForm1.patchValue(
      {
        loadingTime: new Date(Date.parse(res?.loadingTime.replace(/-/g, '/'))),
        unloadingTime: new Date(Date.parse(res?.unloadingTime.replace(/-/g, '/')))
      },
      { onlySelf: true }
    );
    this.sf4data = {
      weight: res?.goodsInfoVOList[0]?.weight || '',
      volume: res?.goodsInfoVOList[0]?.volume || '',
      number: res?.goodsInfoVOList[0]?.number || '',
      carModel: res?.goodsInfoVOList[0]?.carModel?.split(',') || [],
      carLength: res?.goodsInfoVOList[0]?.carLength?.split(',') || [],
      goodsValue: res?.goodsValue || '',
      insurancePackagedGoods: res?.insurancePackagedGoods || ''
    };
    if (this.PageStatus === '整车修改') {
      this.sf4data.id = res?.goodsInfoVOList[0]?.id;
    }
    this.totalFees = res?.shippingInformationVO?.totalFee || '0';
    this.sf5data = {
      insuranceType: res?.insuranceType || '',
      insurancePremium: res?.insurancePremium || '',
      insuranceRate: res?.insuranceRate || ''
    };
    this.sf6data = {
      stateReceipt: res?.stateReceipt,
      receiptType: res?.receiptType || '',
      receiptUserName: res?.supplementaryInformationVO?.receiptUserName || '',
      receiptAddressArea: res?.supplementaryInformationVO?.area || '',
      receiptUserPhone: res?.supplementaryInformationVO?.phon || '',
      receiptAddress: res?.supplementaryInformationVO.address || '',
      remarks: res?.supplementaryInformationVO?.remarks || ''
    };
    // this.sf7data = {
    //   prePay: res?.shippingInformationVO?.prePay,
    //   toPay: res?.shippingInformationVO?.toPay,
    //   // oilCardPay: 0,
    //   receiptPay: res?.shippingInformationVO?.receiptPay,
    //   total: res?.shippingInformationVO?.totalFee,
    //   appendFee: res?.shippingInformationVO?.appendFee,
    //   paymentDays: res?.paymentDays
    // };
    this.sf7data = {
      prePay: res?.expenseVOList?.filter((data: any) => data.expenseCode === 'PRE')[0]?.price || null,
      toPay: res?.expenseVOList?.filter((data: any) => data.expenseCode === 'RECE')[0]?.price || null,
      receiptPay: res?.expenseVOList?.filter((data: any) => data.expenseCode === 'BACK')[0]?.price || null,
      appendFee: res?.expenseVOList?.filter((data: any) => data.expenseCode === 'ATT')[0]?.price || 0,
      paymentDays: res?.paymentDays || '',
      prePayId: res?.expenseVOList?.filter((data: any) => data.expenseCode === 'PRE')[0]?.id || '',
      PREresourceId: res?.expenseVOList?.filter((data: any) => data.expenseCode === 'PRE')[0]?.resourceId || '',
      RECEresourceId: res?.expenseVOList?.filter((data: any) => data.expenseCode === 'RECE')[0]?.resourceId || '',
      BACKresourceId: res?.expenseVOList?.filter((data: any) => data.expenseCode === 'BACK')[0]?.resourceId || '',
      toPayId: res?.expenseVOList?.filter((data: any) => data.expenseCode === 'RECE')[0]?.id || '',
      receiptPayId: res?.expenseVOList?.filter((data: any) => data.expenseCode === 'BACK')[0]?.id || '',
      appendFeeId: res?.expenseVOList?.filter((data: any) => data.expenseCode === 'ATT')[0]?.id || ''
    };
    this.sf7.setValue('/prePay', this.sf7data.prePay);
    this.sf7.setValue('/toPay', this.sf7data.toPay);
    this.sf7.setValue('/receiptPay', this.sf7data.receiptPay);
    this.payChange();
  }

  // 选择地址
  chooseAddress(index: number, type: string) {
    const modalRef = this.modalService.create({
      nzTitle: '选择地址',
      nzContent: PublishAddressListComponent,
      nzWidth: 900,
      nzComponentParams: { spuStatus: '1' },
      nzOnOk: item => {
        const data = item.seleteData;
        if (JSON.stringify(data) === '{}') return;
        switch (type) {
          case 'start':
            this.startInfo[index] = {
              detailedAddress: data.detailedAddress,
              appUserName: data.contactName,
              contractTelephone: data.contactTelephone,
              latitude: data.contactTelephone,
              longitude: data.latitude,
              province: data.province,
              city: data.city,
              area: data.area,
              type: '1'
            };
            break;
          case 'end':
            this.endInfo[index] = {
              detailedAddress: data.detailedAddress,
              appUserName: data.contactName,
              contractTelephone: data.contactTelephone,
              latitude: data.contactTelephone,
              longitude: data.latitude,
              province: data.province,
              city: data.city,
              area: data.area,
              type: '2'
            };
            break;
          default:
            break;
        }
        // 计算里程，时间
        if (this.startInfo[0]?.detailedAddress && this.endInfo[0]?.detailedAddress) {
          this.amapService.drivingCompute([...this.startInfo], [...this.endInfo]).subscribe(res => {
            this.totalDistance = res.distance;
            this.totalTime = res.time;
            this.getInsurersPrice(); //计算保费金额
          });
        }
      }
    });
  }
  // 不可选择的时间
  disabledDateStart = (current: Date): boolean => {
    let d = new Date();
    let year = d.getFullYear();
    let month = d.getMonth();
    let date = d.getDate();
    let hours = d.getHours();
    let mydate = new Date(year, month, date + this.limitValues.maxDays, hours + 1);
    return differenceInCalendarDays(new Date(), current) > 0 || new Date(current) > mydate;
  };
  // 装卸货地址互换
  swapAddress() {
    this.startInfo.forEach((element: any, index: any) => {
      this.validateForm1.removeControl(`loadAddress${index}`);
      this.validateForm1.removeControl(`loadName${index}`);
      this.validateForm1.removeControl(`loadPhone${index}`);
    });
    this.endInfo.forEach((element: any, index: any) => {
      this.validateForm1.removeControl(`unloadAddress${index}`);
      this.validateForm1.removeControl(`unloadName${index}`);
      this.validateForm1.removeControl(`unloadPhone${index}`);
    });

    let item = this.startInfo;
    this.startInfo = this.endInfo;
    this.endInfo = item;

    this.startInfo.forEach((element: any, index: any) => {
      element.type = '1';
      this.validateForm1.addControl(`loadAddress${index}`, new FormControl(null, Validators.required));
      this.validateForm1.addControl(`loadName${index}`, new FormControl(null, Validators.required));
      this.validateForm1.addControl(`loadPhone${index}`, new FormControl(null, [Validators.required, Validators.pattern('^[0-9]*$')]));
    });
    this.endInfo.forEach((element: any, index: any) => {
      element.type = '2';
      this.validateForm1.addControl(`unloadAddress${index}`, new FormControl(null, Validators.required));
      this.validateForm1.addControl(`unloadName${index}`, new FormControl(null, Validators.required));
      this.validateForm1.addControl(`unloadPhone${index}`, new FormControl(null, [Validators.required, Validators.pattern('^[0-9]*$')]));
    });
    // 计算里程，时间
    if (this.startInfo[0]?.detailedAddress && this.endInfo[0]?.detailedAddress) {
      this.amapService.drivingCompute([...this.startInfo], [...this.endInfo]).subscribe(res => {
        this.totalDistance = res.distance;
        this.totalTime = res.time;
        this.getInsurersPrice(); //计算保费金额
      });
    }
  }
  // 计算保价费金额
  getInsurersPrice(insuranceType = this.sf5.value.insuranceType) {
    console.log(this.totalDistance);
    if (insuranceType !== '3' && this.totalDistance > 0) {
      const params = {
        insuranceType,
        goodsValue: this.sf4.value.goodsValue,
        km: this.totalDistance
      };
      this.service.request(this.service.$api_getWholeInsuranceInfo, params).subscribe(res => {
        if (res) {
          this.sf5.setValue('/insurancePremium', res.insurancePremium);
          this.sf5.setValue('/insuranceRate', res.insuranceRate);
        } else {
          this.sf5.setValue('/insurancePremium', null);
          this.sf5.setValue('/insuranceRate', null);
        }
      });
    }
  }
  // 运费信息价格变更
  priceChange(event: any, i: any) {
    i.setValue(event);
    if (event >= 99999) {
      this.modalService.warning({
        nzTitle: '可输入的最大金额为99999元',
      });
    }
    this.payChange()
  }

  checkGoodsName() {
    const name = this.sf3.getValue('/goodsName1');
    if (!name || name.trim().length === 0) {
      return;
    }
    this.service.request(this.service.$api_checkGoodsName, name).subscribe(res => {
      if (res === false) {
        const modalRef = this.modalService.error({
          nzTitle: '货物名称含有违禁词，请重新输入！',
        });
        modalRef.afterClose.subscribe(result => {
          // this.sf3.setValue('/goodsName1', null);
        });
      }
    });
  }
}
