import { Component, OnInit, ViewChild } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import {
  SFComponent,
  SFNumberWidgetSchema,
  SFSchema,
  SFSchemaEnum,
  SFSelectWidgetSchema,
  SFTextareaWidgetSchema,
  SFUISchema
} from '@delon/form';
import { _HttpClient } from '@delon/theme';
import { AmapPoiPickerComponent, AmapService, ShipperBaseService } from '@shared';
import { NzModalService } from 'ng-zorro-antd/modal';
import { PublishGoodsChooseFamifiarComponent } from '../choose-famifiar/choose-famifiar.component';
import { SupplyManagementService } from '../../services/supply-management.service';
import { map } from 'rxjs/operators';
import { of } from 'rxjs';
import { PublishSuccessComponent } from '../onecar-publish/publish-success/publish-success.component';
import { PublishAddressListComponent } from '../onecar-publish/address-list/address-list.component';
import { TranAgreementComponent } from '../tran-agreement/tran-agreement.component';
import differenceInCalendarDays from 'date-fns/differenceInCalendarDays';
import { SupplyManagementQrcodePageComponent } from '../qrcode-page/qrcode-page.component';
@Component({
  selector: 'app-publish-goods-bulk-publish',
  templateUrl: './bulk-publish.component.html',
  styleUrls: ['./bulk-publish.component.less']
})
export class SupplyManagementBulkPublishComponent implements OnInit {
  validateForm1: FormGroup;
  sf1data: any; // 货源单设置回显
  sf3data: any; // 货源单设置回显
  sf4data: any; // 货源单设置回显
  sf5data: any; // 货源单设置回显
  sf7data: any; // 货源单设置回显
  creatTime: any; // 货源单设置回显
  modifyTime: any; // 货源单设置回显
  totalFees: any; // 总数信息
  totalDistance = 0.0; //总里程
  totalTime = 0.0; //路程总时间
  currentGoodsTypeName: any;
  enterpriseProjectIds: any;
  freightTypeOptions: any;
  ruleOptions: any;
  id = this.route.snapshot.params.id; // 传参id
  // // 单位
  startInfo: any = [];
  endInfo: any = [];
  PageStatus = '';
  shipperName = '';
  limitValues = {
    maxMonth: 99,
    maxWeight: 99999,
    maxVolume: 99999,
    maxTrainNumber: 99999,
    maxFreight: 9999999
  };
  constructor(
    private http: _HttpClient,
    fb: FormBuilder,
    private router: Router,
    private route: ActivatedRoute,
    private modalService: NzModalService,
    public service: SupplyManagementService,
    private amapService: AmapService,
    public shipperSrv: ShipperBaseService
  ) {
    this.validateForm1 = fb.group({
      loadAddress0: [null, [Validators.required]],
      loadName0: [null, [Validators.required]],
      loadPhone0: [null, [Validators.required, Validators.pattern('^[0-9]*$')]],
      unloadAddress0: [null, [Validators.required]],
      unloadName0: [null, [Validators.required]],
      unloadPhone0: [null, [Validators.required, Validators.pattern('^[0-9]*$')]]
    });
  }
  @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('sf7', { static: false }) sf7!: SFComponent;
  schema7: SFSchema = {};
  ui7!: SFUISchema;
  // 初始化
  ngOnInit(): void {
    if (this.route.snapshot?.queryParams?.sta === '3') {
      this.PageStatus = '大宗修改';
    } else if (this.route.snapshot?.queryParams?.sta === '4') {
      this.PageStatus = '大宗下一单';
    }
    this.initSF1();
    this.initSF3();
    this.initSF4();
    this.initSF6();
    this.initdata();
    this.initDict();
    this.getLimitvalue();
  }
  initSF1() {
    this.schema1 = {
      properties: {
        shipperAppUserId: {
          title: '货主',
          type: 'string',
          maxLength: 30,
          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;
              }
            }
          } as SFSelectWidgetSchema
        },
        enterpriseProjectId: {
          type: 'string',
          title: '项目',
          ui: {
            widget: 'select',
            placeholder: '请选择'
          } as SFSelectWidgetSchema
        },
        enterpriseInfoName: {
          type: 'string',
          title: '网络货运人',
          ui: {
            widget: 'text'
          }
        },
        deadlineTime: {
          title: '有效期',
          type: 'string',
          format: 'date-time',
          ui: {
            placeholder: '请输入',
            format: 'yyyy-MM-dd HH:mm:ss',
            validator: val => {
              let d = new Date();
              let year = d.getFullYear();
              let month = d.getMonth();
              let date = d.getDate();
              let mydate = new Date(year, month + this.limitValues.maxMonth, date);
              if (new Date(val) < new Date()) {
                return [{ keyword: 'validTime', message: '有效期时间需大于当前时间' }];
              }
              if (new Date(val) > mydate) {
                return [{ keyword: 'validTime2', message: `有效期最长为${this.limitValues.maxMonth}个月` }];
              }
              return [];
            }
          }
        },
        dispatchName: {
          type: 'string',
          title: '调度员姓名',
          maxLength: 30,
          ui: {
            optionalHelp: '选若未填写，司机直接联系您',
            placeholder: '请输入'
          }
        },
        dispatchPhone: {
          type: 'string',
          title: '调度员手机号',
          maxLength: 30,
          ui: {
            placeholder: '请输入'
          }
        }
      },
      required: ['shipperAppUserId', 'enterpriseProjectId', 'enterpriseInfoName', 'deadlineTime']
    };
    this.ui1 = {
      '*': {
        spanLabelFixed: 115,
        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: {
        freightPrice: {
          type: 'string',
          title: '运费单价',
          ui: {
            errors: { required: '请选择运费单价' },
            widget: 'custom',
            placeholder: '请输入'
          }
        },
        freightType: {
          type: 'string',
          title: '',
          ui: {
            hidden: true
          },
          default: '1'
        },
        rule: {
          type: 'string',
          title: '',
          ui: {
            widget: 'custom',
            errors: { required: '请选择运费取整规则' }
          }
        },
        settlementBasis: {
          type: 'string',
          title: '',
          enum: [
            { label: '以收货为准', value: '1' },
            { label: '以发货为准', value: '2' }
          ],
          ui: {
            widget: 'select',
            placeholder: '结算依据',
            errors: { required: '请选择结算依据' }
          } as SFSelectWidgetSchema
        },
        weight: {
          type: 'string',
          title: '货物数量',
          ui: {
            widget: 'custom',
            placeholder: '请输入',
            errors: { required: '请填写总重量' }
          }
        },
        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('/carModel', ['999']);
              }
            }
          }
        }
      },
      required: ['weight', 'carModel', 'carLength', 'freightPrice', 'rule', 'settlementBasis']
    };
    this.ui4 = {
      '*': {
        spanLabelFixed: 90,
        grid: { span: 24 }
      },
      $freightPrice: {
        grid: { span: 8 }
      },
      $rule: {
        grid: { span: 8 }
      },
      $settlementBasis: {
        grid: { span: 8 }
      },
      $weight: {
        grid: { lg: 8, md: 12, sm: 12, xs: 24 }
      },
      $volume: {
        grid: { lg: 8, md: 12, sm: 12, xs: 24 }
      },
      $number: {
        grid: { lg: 8, md: 12, sm: 12, xs: 24 }
      },
      $carModel: {
        spanLabelFixed: 120,
        grid: { span: 8 }
      },
      $carLength: {
        grid: { span: 8 }
      }
    };
  }
  initSF6() {
    this.schema7 = {
      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'
            }
          }
        },
        paymentDays: {
          type: 'string',
          title: '到货后',
          ui: {
            widget: 'custom',
            placeholder: '请输入',
            errors: { required: '请输入付款承诺天数' }
          }
        },
        remarks: {
          type: 'string',
          title: '备注',
          maxLength: 200,
          ui: {
            widget: 'textarea',
            placeholder: '请输入',
            autosize: { minRows: 3, maxRows: 3 }
          } as SFTextareaWidgetSchema
        }
      },
      required: [
        'stateReceipt',
        'receiptType',
        'receiptUserName',
        'receiptUserPhone',
        'receiptAddressArea',
        'receiptAddress',
        'paymentDays'
      ]
    };
    this.ui7 = {
      '*': {
        spanLabelFixed: 90,
        grid: { span: 24 }
      }
    };
  }
  changeValue() {
    this.totalFees =
      Number(this.sf7?.value?.appendFee) +
      Number(this.sf7?.value?.oilCardPay) +
      Number(this.sf7?.value?.prePay) +
      Number(this.sf7?.value?.receiptPay) +
      Number(this.sf7?.value?.toPay);
  }
  initDict() {
    this.service.getDictByKey('freight:type').subscribe(res => {
      this.freightTypeOptions = res;
    });
    this.service.getDictByKey('goodresource:rounding:rules').subscribe(res => {
      this.ruleOptions = res;
    });
  }
  // 获取城市列表
  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);
        }
      });
  }
  addStartInfo(event: any) {
    if (this.startInfo.length < 5) {
      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));
    }
  }
  subStartInfo(event: any, index: number, id?: any) {
    if (id) {
      this.service.request(this.service.$api_delete_Wholedeletebatch, [id]).subscribe(res => { });
    }
    this.startInfo.splice(index, 1);
    this.validateForm1.removeControl(`loadAddress${index}`);
    this.validateForm1.removeControl(`loadName${index}`);
    this.validateForm1.removeControl(`loadPhone${index}`);
  }
  addEndInfo(event: any) {
    if (this.addEndInfo.length < 5) {
      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));
    }
  }
  subEndInfo(event: any, index: number, id?: any) {
    if (id) {
      this.service.request(this.service.$api_delete_Wholedeletebatch, [id]).subscribe(res => { });
    }
    this.endInfo.splice(index, 1);
    this.validateForm1.removeControl(`unloadAddress${index}`);
    this.validateForm1.removeControl(`unloadName${index}`);
    this.validateForm1.removeControl(`unloadPhone${index}`);
  }
  // 指派熟车
  chooseFamifiar(item: any) {
    const modalRef = this.modalService.create({
      nzTitle: '指派熟车',
      nzContent: PublishGoodsChooseFamifiarComponent,
      nzComponentParams: {
        submitParams: item,
        submitUrl: this.service.$api_save_bulk_assign
      },
      nzWidth: 1300
    });
    modalRef.afterClose.subscribe(result => {
      if (result) {
        this.openFinishPage(result);
      }
    });
  }
  // 打开下单完成页面
  openFinishPage(resourceObj: any = null) {
    this.modalService.create({
      nzTitle: '',
      nzContent: PublishSuccessComponent,
      nzWidth: 900,
      nzFooter: null,
      nzComponentParams: { type: 'bulk' }
    });
  }
  // 提交前确认，委托运输协议弹窗
  submitConfirm(submitType?: any) {
    Object.keys(this.validateForm1.controls).forEach(key => {
      this.validateForm1.controls[key].markAsDirty();
      this.validateForm1.controls[key].updateValueAndValidity();
    });
    this.sf1.validator({ emitError: true });
    this.sf3.validator({ emitError: true });
    this.sf4.validator({ emitError: true });
    if (this.validateForm1.invalid || !this.sf1.valid || !this.sf3.valid || !this.sf4.valid) {
      this.service.msgSrv.warning('请完善必填项！');
      return;
    }
    if (this.totalDistance <= 0) {
      this.service.msgSrv.warning('起终点相同，请重新选择装卸货地址！');
      return;
    }
    // 校验各个输入限定值
    if (
      this.sf4.value?.weight > this.limitValues?.maxWeight ||
      this.sf4.value?.volume > this.limitValues?.maxVolume ||
      this.sf4.value?.number > this.limitValues?.maxTrainNumber
    ) {
      this.service.msgSrv.error(
        `当前货物核载信息已超出限定值【${this.limitValues?.maxWeight}吨、${this.limitValues?.maxVolume}方、${this.limitValues?.maxTrainNumber}车】`
      );
      return;
    }

    if (this.sf4.value?.freightPrice > this.limitValues?.maxFreight) {
      this.service.msgSrv.error(`当前运费单价已超出限定值【${this.limitValues.maxFreight}元】`);
      return;
    }

    // //装卸货信息
    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 goodsInfoDTOList = [
      {
        ...this.sf4.value,
        ...this.sf3.value,
        carModel: this.sf4.value?.carModel.join(','),
        carLength: this.sf4.value?.carLength.join(',')
      }
    ];
    // 从“再下一单”过来，将所有的子参数内的id都删除
    if ((this.PageStatus = '大宗下一单')) {
      LoadingList.forEach((ele: any) => {
        delete ele.id;
      });
      goodsInfoDTOList.forEach((ele: any) => {
        delete ele.id;
      });
    }
    const params: any = {
      ...this.sf1.value,
      ...this.sf7.value,
      unLoadingPlaceDTOList: LoadingList,
      goodsInfoDTOList: goodsInfoDTOList,
      estimatedKilometers: this.totalDistance,
      estimatedTravelTime: this.totalTime
    };
    params.freightPrice = this.totalFees;
    const modalRef = this.modalService.create({
      nzTitle: '运输协议',
      nzContent: TranAgreementComponent,
      nzWidth: 900,
      nzFooter: null,
      nzComponentParams: { object: params, shipperName: this.shipperName, type: 'bulk' }
    });
    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;
      } else if (submitType === 'qrcode') {
        this.service.request(this.service.$api_saveAnotherBulkOrderQRCode, params).subscribe(res => {
          if (res) {
            this.assignedQrcode(res, params);
          }
        });
        return;
      }
    }
    if (this.PageStatus === '大宗修改') {
      this.requests(this.service.$api_set_bulkModify, params, 1);
    } else if (this.PageStatus === '大宗下一单') {
      this.requests(this.service.$api_set_saveAnotherBulkOrder, params, 2);
    }
  }
  // 生成二维码
  assignedQrcode(id: string, parms: any) {
    const item = {
      id,
      enterpriseInfoName: parms.enterpriseInfoName,
      loadingAddressArr: this.startInfo.map((ele: any) => ele.detailedAddress),
      unloadingAddressArr: this.endInfo.map((ele: any) => ele.detailedAddress),
      deadlineTime: parms.deadlineTime
    };
    const modalRef = this.modalService.create({
      nzTitle: '二维码',
      nzWidth: '468px',
      nzContent: SupplyManagementQrcodePageComponent,
      nzComponentParams: {
        i: item
      },
      nzFooter: null
    });
    modalRef.afterClose.subscribe(() => {
      this.router.navigate(['/supply-management/index'], { queryParams: { type: 'bulk' } });
    });
  }
  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 }
        });
      }
    });
  }
  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);
          }
        }
      });
  }
  backBillChange() {
    const modalRef = this.modalService.create({
      nzTitle: '选择收回单地址',
      nzContent: PublishAddressListComponent,
      nzWidth: 900,
      nzComponentParams: { spuStatus: '2' },
      nzOnOk: item => {
        const data = item.seleteData;
        if (JSON.stringify(data) === '{}') return;
        this.sf7.setValue('/receiptAddressId', data.id);
        this.sf7.setValue('/receiptUserName', data.contactName);
        this.sf7.setValue('/phon', data.contactTelephone);
        this.sf7.setValue('/area', `${data.province}-${data.city}-${data.area}`);
        this.sf7.setValue('/address', data.detailedAddress);
      }
    });
  }
  // 打开地图
  openMap(type: string, index: number) {
    const modalRef = this.modalService.create({
      nzTitle: '',
      nzContent: AmapPoiPickerComponent,
      nzWidth: 900,
      nzOnOk: item => {
        if (item?.poi) {
          const poi = item.poi;
          const locList = poi.location.toString().split(',');
          switch (type) {
            case 'start':
              this.startInfo[index].detailedAddress = poi.district + poi.name;
              this.startInfo[index].longitude = locList[0];
              this.startInfo[index].latitude = locList[1];
              this.startInfo[index].province = poi.cityInfo.province;
              this.startInfo[index].city = poi.cityInfo.city;
              this.startInfo[index].area = poi.cityInfo.district;
              this.startInfo[index].address = poi.name;
              break;
            case 'end':
              this.endInfo[index].detailedAddress = poi.district + poi.name;
              this.endInfo[index].longitude = locList[0];
              this.endInfo[index].latitude = locList[1];
              this.endInfo[index].province = poi.cityInfo.province;
              this.endInfo[index].city = poi.cityInfo.city;
              this.endInfo[index].area = poi.cityInfo.district;
              this.endInfo[index].address = poi.name;
              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;
            });
          }
          return true
        } else {
          this.service.msgSrv.warning('请重新手动选择地址！')
          return false
        }
      }
    });
  }
  goBack() {
    window.history.go(-1);
  }
  // 初始化信息
  initdata() {
    this.service.request(`${this.service.$api_get_getBulkDetail}`, { id: this.id }).subscribe(res => {
      this.dataR(res);
    });
  }

  // 初始化信息
  dataR(res: any) {
    // 注：区分编辑和下一单 区别是初始化的时候加不加ID
    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 = {
      dispatchPhone: res?.dispatchPhone,
      dispatchName: res?.dispatchName,
      // shipperAppUserName: res?.shipperAppUserName || '',
      enterpriseProjectId: res?.enterpriseProjectId || '',
      enterpriseInfoName: res?.enterpriseInfoName || '',
      externalResourceCode: res?.externalResourceCode || '',
      deadlineTime: res?.deadlineTime || ''
    };
    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
          });
        }
        if (element.createTime) {
          this.creatTime = element?.createTime;
          this.modifyTime = element?.modifyTime;
        }
        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));
      }
    });
    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 });

    this.sf4data = {
      freightPrice: res?.goodsInfoVOList[0]?.freightPrice || '',
      freightType: res?.goodsInfoVOList[0]?.freightType || '',
      rule: res?.goodsInfoVOList[0]?.rule || '',
      settlementBasis: res?.goodsInfoVOList[0]?.settlementBasis || '',
      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(',') || ''
    };
    if (this.PageStatus === '大宗修改') {
      this.sf4data.id = res?.goodsInfoVOList[0]?.id;
    }
    // 计算里程，时间
    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.totalFees = res?.freightPrice || '0';
    this.sf7data = {
      stateReceipt: res?.stateReceipt,
      receiptType: res?.receiptType || '',
      receiptUserName: res?.supplementaryInformationVO?.receiptUserName || '',
      receiptAddressArea: res?.supplementaryInformationVO?.area || '',
      receiptUserPhone: res?.supplementaryInformationVO?.phon || '',
      receiptAddress: res?.receiptAddress || '',
      paymentDays: res?.paymentDays || '',
      remarks: res?.remarks || ''
    };
  }
  // 回退
  choose() {
    window.history.go(-1);
  }
  // 选择地址
  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;
        }
      }
    });
  }
  // 装卸货地址互换
  swapAddress() {
    let item = this.startInfo;
    this.startInfo = this.endInfo;
    this.endInfo = item;

    this.startInfo.forEach((element: any) => {
      element.type = '1';
    });
    this.endInfo.forEach((element: any) => {
      element.type = '2';
    });

    // 计算里程，时间
    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;
      });
    }
  }
  getLimitvalue() {
    const getlimitvaluesParms = [
      this.service.limitKeys2.month,
      this.service.limitKeys2.weight,
      this.service.limitKeys2.volume,
      this.service.limitKeys2.trainNumber,
      this.service.limitKeys2.freight
    ];
    this.service.request(this.service.$api_findItemValueByItemKeys, getlimitvaluesParms).subscribe(res => {
      const maxMonth = res.filter((item: any) => item.itemKey === this.service.limitKeys2.month)[0].itemValue;
      const maxWeight = res.filter((item: any) => item.itemKey === this.service.limitKeys2.weight)[0].itemValue;
      const maxVolume = res.filter((item: any) => item.itemKey === this.service.limitKeys2.volume)[0].itemValue;
      const maxTrainNumber = res.filter((item: any) => item.itemKey === this.service.limitKeys2.trainNumber)[0].itemValue;
      const maxFreight = res.filter((item: any) => item.itemKey === this.service.limitKeys2.freight)[0].itemValue;
      this.limitValues = {
        maxMonth: Number(maxMonth),
        maxWeight: Number(maxWeight),
        maxVolume: Number(maxVolume),
        maxTrainNumber: Number(maxTrainNumber),
        maxFreight: Number(maxFreight)
      };
    });
  }
  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);
        });
      }
    });
  }
}
