/*
 * @Description  :
 * @Version      : 1.0
 * @Author       : Shiming
 * @Date         : 2021-12-24 16:58:02
 * @LastEditors  : Shiming
 * @LastEditTime : 2022-04-20 14:46:48
 * @FilePath     : \\tms-obc-web\\src\\app\\routes\\order-management\\components\\bulk-detail-change\\bulk-detail-change.component.ts
 * Copyright (C) 2022 huzhenhong. All rights reserved.
 */
import { ViewChild } from '@angular/core';
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { STColumn, STComponent } from '@delon/abc/st';
import { SFComponent, SFNumberWidgetSchema, SFSchema, SFSelectWidgetSchema, SFUISchema, SFUploadWidgetSchema } from '@delon/form';
import { _HttpClient } from '@delon/theme';
import { AmapPoiPickerComponent, AmapService, EAEnvironmentService, ShipperBaseService } from '@shared';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { NzUploadChangeParam, NzUploadFile } from 'ng-zorro-antd/upload';
import { Observable, Observer } from 'rxjs';
import { apiConf } from '@conf/api.conf';
import { OrderManagementService } from '../../services/order-management.service';
import format from 'date-fns/format';
import { NzCardComponent } from 'ng-zorro-antd/card';
import { map } from 'rxjs/operators';
function getBase64(file: File): Promise<string | ArrayBuffer | null> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}
@Component({
  selector: 'app-supply-management-bulk-detail-change',
  templateUrl: './bulk-detail-change.component.html',
  styleUrls: ['./bulk-detail-change.component.less', '../../../commom/less/trajectory.less']
})
export class OrderManagementBulkDetailChangeComponent implements OnInit {
  validateForm1: FormGroup;
  id = this.route.snapshot.params.id;
  @ViewChild('distannce3', { static: false })
  i: any = { unLoadingPlaceList: [] };
  totalDistance = 0.0; //总里程
  totalTime = 0.0; //路程总时间
  startInfo: any = []; // 装货信息
  endInfo: any = []; // 卸货信息
  unloadTime: any; // 货源单设置回显
  loadTime: any; // 货源单设置回显
  sf3data: any; // 货源单设置回显
  sf4data: any; // 货源单设置回显
  dirverPhone: any; // 货源单设置回显
  dirverBankCard: any; // 货源单设置回显
  listImagUrls: any[] = []; // 货源单设置回显
  dirvingMessage = [];
  modalcontent: any;
  modalTitle: string = '';
  imges: any;
  totalObj: any;
  attObj: any;
  previewImage1 = '';
  previewVisible1 = false;
  @ViewChild('sf3', { static: false }) sf3!: SFComponent;
  schema3: SFSchema = {};
  ui3!: SFUISchema;
  @ViewChild('st') st!: STComponent;
  @ViewChild('sf4', { static: false }) sf4!: SFComponent;
  schema4: SFSchema = {};
  isVisible = false;
  billExpenses: any[] = []; //运费信息表格信息
  ui4!: SFUISchema;
  formData: any;
  @ViewChild('sf', { static: false }) sf!: SFComponent;
  schema: SFSchema = {};
  ui: SFUISchema = {};
  logColumns2: STColumn[] = [
    { title: '时间', index: 'parkBte' },
    { title: '地点', index: 'parkAdr' }
  ];
  logColumns: STColumn[] = [
    { title: '款项', index: 'expenseCodeLabel' },
    { title: '小计（元）', render: 'prices' },
    { title: '运输费（元）', render: 'price' },
    { title: '附加费（元）', render: 'surcharge' },
    { title: '支付时间', index: 'paymentTime' },
    {
      title: '支付状态',
      className: 'text-center',
      index: 'paymentStatus',
      type: 'badge',
      width: '120px',
      badge: {
        '1': { text: '待申请', color: 'warning' },
        '2': { text: '已支付', color: 'success' },
        '3': { text: '已拒绝', color: 'warning' },
        '4': { text: '申请中', color: 'warning' }
      }
    }
  ];
  trajectory = 'car';
  mapList: any[] = []; //地图点位数据组
  addressItems: any[] = []; //打点地址数据组
  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private msgSrv: NzMessageService,
    public service: OrderManagementService,
    private modalService: NzModalService,
    private amapService: AmapService,
    public shipperservice: ShipperBaseService,
    fb: FormBuilder,
    private envSrv: EAEnvironmentService,
    private ar: ActivatedRoute
  ) {
    this.validateForm1 = fb.group({
      loadTime: [null, []],
      unloadTime: [null, []]
    });
  }

  ngOnInit(): void {
    this.initData();
    this.initSF3();
    this.initSF4();
    this.getTrajectory();
  }
  initSF() {
    this.schema = {
      properties: {
        loadingLadingBillFilePath: {
          type: 'string',
          title: '装货凭证',
          // readOnly: this.i.billStatus !== '4' || this.i.billStatus !== '3',
          ui: {
            widget: 'upload',
            action: apiConf.waterFileUpload,
            fileType: 'image/png,image/jpeg,image/jpg,image/gif',
            limit: 1,
            limitFileCount: 1,
            resReName: 'data.fullFileWatermarkPath',
            urlReName: 'data.fullFileWatermarkPath',
            descriptionI18n: '提货单',
            data: {
              appId: this.envSrv.env.appId,
              content: [
                `上传用户:${this.i?.driverName}(${this.i?.driverTelephone})`,
                `上传位置:${this.i?.unLoadingPlaceList[0]?.province}`,
                `上传时间:${format(new Date(), 'yyyy-MM-dd HH:mm:ss')}`,
              ],
              position: '2',
              fontSize: '100'
            },
            name: 'multipartFile',
            beforeUpload: (file: any, fileList: any) => {
              return new Observable((observer: Observer<boolean>) => {
                const isLt1M = file.size / 1024 / 1024 < 5;
                const fileType = 'image/png,image/jpeg';
                if (fileType.indexOf(file.type) === -1) {
                  this.service.msgSrv.warning('图片格式不正确！');
                  observer.complete();
                  return;
                }
                if (!isLt1M) {
                  this.service.msgSrv.warning('图片大小超过5M!');
                  observer.complete();
                  return;
                }
                observer.next(isLt1M);
                observer.complete();
              });
            },
            multiple: false,
            listType: 'picture-card'
          } as SFUploadWidgetSchema
        },
        loadingPeopleVehiclesGoodsFilePath: {
          type: 'string',
          title: '',
          // readOnly: this.i.billStatus !== '4' || this.i.billStatus !== '3',
          ui: {
            widget: 'upload',
            action: apiConf.waterFileUpload,
            fileType: 'image/png,image/jpeg,image/jpg,image/gif',
            limit: 1,
            limitFileCount: 1,
            resReName: 'data.fullFileWatermarkPath',
            urlReName: 'data.fullFileWatermarkPath',
            descriptionI18n: '人车货照片',
            data: {
              appId: this.envSrv.env.appId,
              content: [
                `上传用户:${this.i?.driverName}(${this.i?.driverTelephone})`,
                `上传位置:${this.i?.unLoadingPlaceList[0]?.province}`,
                `上传时间:${format(new Date(), 'yyyy-MM-dd HH:mm:ss')}`,
              ],
              position: '2',
              fontSize: '100'
            },
            name: 'multipartFile',
            beforeUpload: (file: any, fileList: any) => {
              return new Observable((observer: Observer<boolean>) => {
                const isLt1M = file.size / 1024 / 1024 < 5;
                const fileType = 'image/png,image/jpeg';
                if (fileType.indexOf(file.type) === -1) {
                  this.service.msgSrv.warning('图片格式不正确！');
                  observer.complete();
                  return;
                }
                if (!isLt1M) {
                  this.service.msgSrv.warning('图片大小超过5M!');
                  observer.complete();
                  return;
                }
                observer.next(isLt1M);
                observer.complete();
              });
            },
            multiple: false,
            listType: 'picture-card'
          } as SFUploadWidgetSchema
        },
        no7: {
          type: 'string',
          title: '',
          ui: {
            widget: 'text'
          },
          default: ''
        },
        unloadingLadingBillFilePath: {
          type: 'string',
          title: '卸货凭证',
          // readOnly: this.i.billStatus !== '4' || this.i.billStatus !== '3',
          ui: {
            widget: 'upload',
            action: apiConf.waterFileUpload,
            fileType: 'image/png,image/jpeg,image/jpg,image/gif',
            limit: 1,
            limitFileCount: 1,
            resReName: 'data.fullFileWatermarkPath',
            urlReName: 'data.fullFileWatermarkPath',
            descriptionI18n: '提货单',
            data: {
              appId: this.envSrv.env.appId,
              content: [
                `上传用户:${this.i?.driverName}(${this.i?.driverTelephone})`,
                `上传位置:${this.i?.unLoadingPlaceList[1]?.province}`,
                `上传时间:${format(new Date(), 'yyyy-MM-dd HH:mm:ss')}`,
              ],
              position: '2',
              fontSize: '100'
            },
            name: 'multipartFile',
            beforeUpload: (file: any, fileList: any) => {
              return new Observable((observer: Observer<boolean>) => {
                const isLt1M = file.size / 1024 / 1024 < 5;
                const fileType = 'image/png,image/jpeg';
                if (fileType.indexOf(file.type) === -1) {
                  this.service.msgSrv.warning('图片格式不正确！');
                  observer.complete();
                  return;
                }
                if (!isLt1M) {
                  this.service.msgSrv.warning('图片大小超过5M!');
                  observer.complete();
                  return;
                }
                observer.next(isLt1M);
                observer.complete();
              });
            },
            multiple: false,
            listType: 'picture-card'
          } as SFUploadWidgetSchema
        },
        unloadingPeopleVehiclesGoodsFilePath: {
          type: 'string',
          title: '',
          // readOnly: this.i.billStatus !== '4' || this.i.billStatus !== '3',
          ui: {
            widget: 'upload',
            action: apiConf.waterFileUpload,
            fileType: 'image/png,image/jpeg,image/jpg,image/gif',
            limit: 1,
            limitFileCount: 1,
            resReName: 'data.fullFileWatermarkPath',
            urlReName: 'data.fullFileWatermarkPath',
            descriptionI18n: '人车货照片',
            data: {
              appId: this.envSrv.env.appId,
              content: [
                `上传用户:${this.i?.driverName}(${this.i?.driverTelephone})`,
                `上传位置:${this.i?.unLoadingPlaceList[1]?.province}`,
                `上传时间:${format(new Date(), 'yyyy-MM-dd HH:mm:ss')}`,
              ],
              position: '2',
              fontSize: '100'
            },
            name: 'multipartFile',
            beforeUpload: (file: any, fileList: any) => {
              return new Observable((observer: Observer<boolean>) => {
                const isLt1M = file.size / 1024 / 1024 < 5;
                const fileType = 'image/png,image/jpeg';
                if (fileType.indexOf(file.type) === -1) {
                  this.service.msgSrv.warning('图片格式不正确！');
                  observer.complete();
                  return;
                }
                if (!isLt1M) {
                  this.service.msgSrv.warning('图片大小超过5M!');
                  observer.complete();
                  return;
                }
                observer.next(isLt1M);
                observer.complete();
              });
            },
            multiple: false,
            listType: 'picture-card'
          } as SFUploadWidgetSchema
        },
        no5: {
          type: 'string',
          title: '',
          ui: {
            widget: 'text'
          },
          default: ''
        },
        no6: {
          type: 'string',
          title: '',
          ui: {
            widget: 'text'
          },
          default: ''
        }
      },
      required: ['loadingLadingBillFilePath', 'unloadingLadingBillFilePath']
    };
    this.ui = {
      '*': {
        spanLabelFixed: 100,
        grid: { span: 20 }
      },
      $unloadingLadingBillFilePath: { grid: { span: 12 } },
      $unloadingPeopleVehiclesGoodsFilePath: { grid: { span: 12 } },
      $loadingLadingBillFilePath: { grid: { span: 12 } },
      $loadingPeopleVehiclesGoodsFilePath: { grid: { span: 12 } },
      $no5: { grid: { span: 24 } }
    };
  }
  initData() {
    this.service.request(this.service.$api_getBulkBillDetail, { id: this.id }).subscribe(res => {
      if (res) {
        this.i = res;
        this.billExpenses = this.i?.billExpenseDetails?.filter((data: any) => data.expenseCode === 'TRA');
        this.initSF();
        // 对装货凭证进行初始化
        let arr: any = [];
        res?.receiptFilePath.forEach((element: any, index: any) => {
          arr.push({
            url: element,
            status: 'done',
            uid: index
          });
        });
        this.sf4data;
        this.listImagUrls = arr;
        // this.sf4data = res?.goodsInfoList?.[0]
        this.sf4data = {
          ...res,
          ...res?.goodsInfoList?.[0]
        };
        this.sf3data = {
          goodsTypeId: res?.goodsInfoList[0]?.goodsTypeId || '',
          goodsTypeName: res?.goodsInfoList[0]?.goodsTypeName || '',
          goodsNameId: res?.goodsInfoList[0]?.goodsNameId || '',
          goodsName: res?.goodsInfoList[0]?.goodsName || ''
        };
        if (this.sf3data.goodsTypeName === '其它') {
          this.sf3data.goodsName1 = res?.goodsInfoList[0]?.goodsName || '';
        }
        this.changeGoodsType(this.sf3data.goodsTypeId, { label: this.sf3data.goodsTypeName, value: this.sf3data.goodsTypeId });
        // 对装卸货信息进行初始化
        res?.unLoadingPlaceList.forEach((element: any) => {
          if (element.type === 1 || element.type === '1') {
            const controlId = this.startInfo.length;
            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
            });
            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;
            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
            });
            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.formData = {
          loadingLadingBillFilePath: [
            {
              uid: 'logo',
              name: 'LOGO',
              status: 'done',
              url: res?.loadingLadingBillFilePath,
              response: {
                url: res?.loadingLadingBillFilePath
              }
            }
          ],
          loadingPeopleVehiclesGoodsFilePath: [
            {
              uid: 'logo',
              name: 'LOGO',
              status: 'done',
              url: res?.loadingPeopleVehiclesGoodsFilePath,
              response: {
                url: res?.loadingPeopleVehiclesGoodsFilePath
              }
            }
          ],
          unloadingLadingBillFilePath: [
            {
              uid: 'logo',
              name: 'LOGO',
              status: 'done',
              url: res?.unloadingLadingBillFilePath,
              response: {
                url: res?.unloadingLadingBillFilePath
              }
            }
          ],
          unloadingPeopleVehiclesGoodsFilePath: [
            {
              uid: 'logo',
              name: 'LOGO',
              status: 'done',
              url: res?.unloadingPeopleVehiclesGoodsFilePath,
              response: {
                url: res?.unloadingPeopleVehiclesGoodsFilePath
              }
            }
          ]
        };
        // 发车时间到车时间初始化
        this.loadTime = res?.loadTime;
        this.unloadTime = res?.unloadTime;
        this.dirvingMessage = res?.billExpenseDetails;
        // 计算里程，时间
        if (this.startInfo[0]?.area && this.endInfo[0]?.area) {
          this.amapService.drivingCompute([...this.startInfo], [...this.endInfo]).subscribe(res => {
            this.totalDistance = res?.distance;
            this.totalTime = res?.time;
          });
        }
      }
    });
  }

  goBack() {
    window.history.go(-1);
  }
  // 取消修改
  cancelChange() {
    window.history.go(-1);
  }
  // 保存修改
  save() {
    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 });
    if (this.validateForm1.invalid || !this.sf3.valid || !this.sf4.valid) {
      this.service.msgSrv.warning('请完善必填项！');
      return;
    }
    if (
      this.sf4.value?.acceptWeight > this.i?.goodsInfoList?.[0]?.weight ||
      this.sf4.value?.settlementWeight.settlementWeight > this.i?.goodsInfoList?.[0]?.weight
    ) {
      this.service.msgSrv.warning('装货重量/卸货重量不能大于货物重量！');
      return;
    }
    let imgList: any = [];
    if (this.listImagUrls.length > 0) {
      this.listImagUrls?.forEach((res: any) => {
        if (res?.url) {
          imgList.push(res?.url);
        }
      });
    }
    if (typeof this.unloadTime !== 'string') {
      var c = new Date(this.unloadTime);
      this.unloadTime =
        c.getFullYear() +
        '-' +
        this.addPreZero(c.getMonth() + 1) +
        '-' +
        this.addPreZero(c.getDate()) +
        ' ' +
        this.addPreZero(c.getHours()) +
        ':' +
        this.addPreZero(c.getMinutes()) +
        ':' +
        this.addPreZero(c.getSeconds());
    }
    if (typeof this.loadTime !== 'string') {
      var c = new Date(this.loadTime);
      this.loadTime =
        c.getFullYear() +
        '-' +
        this.addPreZero(c.getMonth() + 1) +
        '-' +
        this.addPreZero(c.getDate()) +
        ' ' +
        this.addPreZero(c.getHours()) +
        ':' +
        this.addPreZero(c.getMinutes()) +
        ':' +
        this.addPreZero(c.getSeconds());
    }
    const params = {
      id: this.id,
      unLoadingPlaceDTOList: [...this.startInfo, ...this.endInfo],
      receiptFilePath: imgList,
      goodsInfoDTOList: [
        {
          id: this.i?.goodsInfoList?.[0].id,
          goodsName: this.sf3.value?.goodsName,
          ...this.sf4.value
        }
      ],
      // 运费信息
      // 车队长
      payeeId: this.dirverPhone,
      dirverBankCard: this.dirverBankCard, // 银行卡
      // 发车时间
      loadTime: this.loadTime,
      // 到车时间
      unloadTime: this.unloadTime,
      acceptWeight: this.sf4.value?.acceptWeight,
      acceptVolume: this.sf4.value?.acceptVolume,
      settlementWeight: this.sf4.value?.settlementWeight,
      settlementVolume: this.sf4.value?.settlementVolume,
      loadingLadingBillFilePath: this.sf?.value?.loadingLadingBillFilePath?.data
        ? this.sf?.value?.loadingLadingBillFilePath.data.fullFilePath
        : this.sf?.value?.loadingLadingBillFilePath?.url,

      loadingPeopleVehiclesGoodsFilePath: this.sf?.value?.loadingPeopleVehiclesGoodsFilePath?.data
        ? this.sf?.value?.loadingPeopleVehiclesGoodsFilePath.data.fullFilePath
        : this.sf?.value?.loadingPeopleVehiclesGoodsFilePath?.url,

      unloadingLadingBillFilePath: this.sf?.value?.unloadingLadingBillFilePath?.data
        ? this.sf?.value?.unloadingLadingBillFilePath.data.fullFilePath
        : this.sf?.value?.unloadingLadingBillFilePath?.url,

      unloadingPeopleVehiclesGoodsFilePath: this.sf?.value?.unloadingPeopleVehiclesGoodsFilePath?.data
        ? this.sf?.value?.unloadingPeopleVehiclesGoodsFilePath.data.fullFilePath
        : this.sf?.value?.unloadingPeopleVehiclesGoodsFilePath?.url
    };
    this.service.request(this.service.$api_set_modifyBulkOrder, params).subscribe((res: any) => {
      if (res) {
        this.service.msgSrv.success('修改成功！');
        this.router.navigate(['/order-management/bulk/bulk-detail/', this.id]);
      } else {
        this.service.msgSrv.error(res?.msg);
      }
    });
  }
  addPreZero(num: any) {
    if (num < 10) {
      return '0' + num;
    } else {
      return num;
    }
  }
  // -------------------装卸货信息处理
  // 打开地图
  // 打开地图
  // 打开地图
  openMap(type: string, index: number, address: string) {
    console.log(type);
    console.log(index);

    const modalRef = this.modalService.create({
      nzTitle: '',
      nzComponentParams: { selectedAddress: address },
      nzContent: AmapPoiPickerComponent,
      nzWidth: 900,
      nzOnOk: 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;
            });
          }
          return true
        } else {
          this.service.msgSrv.warning('请重新手动选择地址！')
          return false
        }
      }
    });
  }
  initSF3() {
    this.schema3 = {
      properties: {
        goodsTypeId: {
          type: 'string',
          title: '货物名称',
          ui: {
            widget: 'select',
            placeholder: '请选择',
            errors: { required: '请选择货物类型' },
            asyncData: () =>
              this.service.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: '',
          ui: {
            errors: { required: '请填写货物名称' },
            visibleIf: {
              goodsTypeName: (value: any) => value && value === '其它'
            }
          }
        }
      },
      required: ['goodsTypeId', 'goodsName', 'goodsNameId']
    };
    this.ui3 = {
      '*': {
        spanLabelFixed: 110,
        grid: { span: 12 }
      }
    };
  }
  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);
          }
        }
      });
  }
  initSF4() {
    this.schema4 = {
      properties: {
        weight: {
          type: 'string',
          title: '货物数量',
          ui: {
            widget: 'custom',
            placeholder: '请输入',
            errors: { required: '必填项' }
          }
        },
        carmand: {
          type: 'string',
          title: '用车需求',
          ui: {
            widget: 'custom',
            placeholder: '请输入'
          }
        },
        drivers: {
          type: 'string',
          title: '承运司机',
          ui: {
            widget: 'custom',
            placeholder: '请输入'
          }
        },
        weightModel: {
          type: 'string',
          title: '车型车长承重',
          ui: {
            widget: 'custom',
            placeholder: '请输入'
          }
        },
        loadTime: {
          type: 'string',
          title: '发车时间',
          ui: {
            widget: 'custom',
            placeholder: '请输入'
          }
        },
        unloadTime: {
          type: 'string',
          title: '到车时间',
          ui: {
            widget: 'custom',
            placeholder: '请输入'
          }
        },
        acceptWeight: {
          type: 'number',
          title: '装货重量',
          minimum: 0,
          maximum: 99999,
          ui: {
            unit: '吨',
            placeholder: '请输入',
            grid: {
              span: 12
            },
            hideStep: true
          } as SFNumberWidgetSchema
        },
        acceptVolume: {
          type: 'number',
          title: '装货体积',
          minimum: 0,
          maximum: 99999,
          ui: {
            unit: '吨',
            placeholder: '请输入',
            grid: {
              span: 12
            },
            hideStep: true
          } as SFNumberWidgetSchema
        },
        settlementWeight: {
          type: 'number',
          title: '卸货重量',
          minimum: 0,
          maximum: 99999,
          ui: {
            unit: '吨',
            placeholder: '请输入',
            grid: {
              span: 12
            },
            hideStep: true
          } as SFNumberWidgetSchema
        },
        settlementVolume: {
          type: 'number',
          title: '卸货体积',
          minimum: 0,
          maximum: 99999,
          ui: {
            unit: '吨',
            placeholder: '请输入',
            grid: {
              span: 12
            },
            hideStep: true
          } as SFNumberWidgetSchema
        }
      },
      required: ['loadTime', 'unloadTime']
    };
    this.ui4 = {
      '*': {
        spanLabelFixed: 110,
        grid: { span: 24 }
      },
      $weight: {
        grid: { span: 24 }
      },
      $carmand: {
        grid: { span: 24 }
      },
      $weightModel: {
        spanLabelFixed: 120,
        grid: { span: 12 }
      },
      $drivers: {
        grid: { span: 12 }
      },
      $loadTime: {
        grid: { span: 12 }
      },
      $unloadTime: {
        grid: { span: 12 }
      }
    };
  }
  // 处理上传图片
  handlePreview1 = async (file: NzUploadFile) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj!);
    }
    this.previewImage1 = file.url || file.preview;
    this.previewVisible1 = true;
  };

  handleChange1(info: NzUploadChangeParam): void {
    switch (info.file.status) {
      case 'uploading':
        break;
      case 'done':
        let fileList = [...info.fileList];
        // 2. Read from response and show file link
        fileList = fileList.map((file: any) => {
          if (file.response) {
            file.url = file.response.data.fullFilePath;
          }
          return file;
        });
        break;
      case 'error':
        this.service.msgSrv.error('网络错误');
        break;
    }
  }
  beforeUpload = (file: NzUploadFile, _fileList: NzUploadFile[]) => {
    return new Observable((observer: Observer<boolean>) => {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif' || file.type === 'image/bmp';
      if (!isJpgOrPng) {
        this.service.msgSrv.warning('只能上传图片!');
        observer.complete();
        return;
      }
      // tslint:disable-next-line: no-non-null-assertion
      const isLt2M = file.size! / 1024 / 1024 < 3;
      if (!isLt2M) {
        this.service.msgSrv.warning('图片大小超过3兆!');
        observer.complete();
        return;
      }
      observer.next(isJpgOrPng && isLt2M);
      observer.complete();
    });
  };
  agreement(value: any) {
    if (value === '1') {
      this.modalTitle = '附件信息';
      this.modalcontent = this.i?.contractContent?.contractContent;

    } else if (value === '2') {
      this.modalTitle = '补充协议';
      this.modalcontent = this.i?.supplementContent?.contractContent;
    }
    this.isVisible = true;
  }
  handleCancel() {
    this.isVisible = false;
  }
  handleOK() {
    this.isVisible = false;
  }
  goDistance(elf: any) {
    if (elf) {
      elf['elementRef'].nativeElement.scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'start' });
    }
  }
  // 装卸货地址互换
  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]?.area && this.endInfo[0]?.area) {
      this.amapService.drivingCompute([...this.startInfo], [...this.endInfo]).subscribe(res => {
        this.totalDistance = res?.distance;
        this.totalTime = res?.time;
      });
    }
  }

  // 获取车辆轨迹
  getTrajectory() {
    this.service.request(this.service.$api_get_getTrajectory, { id: this.id }).subscribe(res => {
      if (res) {
        const points = res?.trackArray;
        let list: any[] = [];
        points?.forEach((item: any) => {
          list.push({
            name: item.hgt,
            lnglat: [Number((Number(item.lon) / 600000).toFixed(6)), Number((Number(item.lat) / 600000).toFixed(6))],
            time: item.gtm
          });
        });
        this.mapList = list;
        this.addressItems = res?.parkArray;
        if (this.addressItems && this.addressItems.length > 0) {
          this.addressItems.forEach(item => {
            item.parkBte = this.getLocalTime(item.parkBte);
          });
        }
      }
    });
  }

  // 获取司机轨迹
  getDriverTrajectory() {
    this.service.request(this.service.$api_get_getAppDriverPosition, { id: this.id }).subscribe(res => {
      if (res) {
        const points = res?.tracks;
        let list: any[] = [];
        points?.forEach((item: any) => {
          list.push({
            name: item.hgt,
            lnglat: [Number((Number(item.lon) / 600000).toFixed(6)), Number((Number(item.lat) / 600000).toFixed(6))],
            time: item.gtm
          });
        });
        this.mapList = list;
        const addressItems = [...res.tracks];
        if (addressItems) {
          addressItems.forEach(item => {
            // item.parkBte = item.gtm;
            item.parkBte = this.getLocalTime(item.gtm);
            item.parkAdr = item.appAdress;
          });
          this.addressItems = [...addressItems];
        } else {
          this.addressItems = [];
        }
      }
    });
  }
  trajectoryChange(event: any) {
    if (event === 'car') {
      this.getTrajectory();
    } else if (event === 'driver') {
      this.getDriverTrajectory();
    }
  }
  getLocalTime(time: any) {
    return format(new Date(parseInt(time)), 'yyyy-MM-dd HH:mm:ss');
  }
}
