import { Component, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { STColumn, STComponent, STRequestOptions } from '@delon/abc/st';
import { SFComponent, SFDateWidgetSchema, SFSchema, SFSchemaEnum, SFSelectWidgetSchema, SFUISchema } from '@delon/form';
import { ShipperBaseService } from '@shared';
import { NzModalService } from 'ng-zorro-antd/modal';
import { fromEvent, of, Subscription } from 'rxjs';
import { debounceTime, map } from 'rxjs/operators';
import { BasicTableComponent } from 'src/app/routes/commom/components/basic-table/basic-table.component';
import { SearchDrawerService } from 'src/app/shared/components/search-drawer/search-drawer.service';
import { OneCarOrderCancelConfirmComponent } from '../../modal/vehicle/cancel-confirm/cancel-confirm.component';
import { VehicleConfirReceiptComponent } from '../../modal/vehicle/confir-receipt/confir-receipt.component';
import { VehicleFreightPeopleComponent } from '../../modal/vehicle/freight-people/freight-people.component';
import { VehicleModifyCaptainComponent } from '../../modal/vehicle/modify-captain/modify-captain.component';
import { VehicleModifyRateComponent } from '../../modal/vehicle/modify-rate/modify-rate.component';
import { VehicleUpdateFreightComponent } from '../../modal/vehicle/update-freight/update-freight.component';
import { OneCarOrderViewtrackComponent } from '../../modal/vehicle/view-track/view-track.component';
import { OrderManagementService } from '../../services/order-management.service';
@Component({
  selector: 'app-supply-management-vehicle',
  templateUrl: './vehicle.component.html',
  styleUrls: ['../../../commom/less/commom-table.less', './vehicle.component.less']
})
export class OrderManagementVehicleComponent extends BasicTableComponent implements OnInit {
  auditMany = false;
  isVisibleView = false;
  isVisibleEvaluate = false;
  isVisible = false;
  loading: boolean = true;
  paramsList: any;
  changeId: any; // 主页面查看运费变更记录id - 用于运费变更记录
  changeViewId: any; // 查看运费变更记录id - 用于查看
  ViewCause: any; // 变更运费查看数据
  shipList: any; // 货主评价 数据
  diverList: any; // 司机评价 数据
  _$expand = false;
  @ViewChild('st') private readonly st!: STComponent;
  @ViewChild('stFloat') private readonly stFloat!: STComponent;
  @ViewChild('stFloatView') private readonly stFloatView!: STComponent;
  @ViewChild('sfFre', { static: false }) sfFre!: SFComponent;
  columns: STColumn[] = [];
  columnsFloat: STColumn[] = [];
  columnsFloatView: STColumn[] = [];
  datass: any = [
    {
      one: '1',
      two: '1',
      three: '1',
      id: 1
    },
    {
      one: '2',
      two: '2',
      three: '2',
      id: 2
    }
  ];
  tabs = {
    cancelQuantity: 0,
    receivedQuantity: 0,
    stayQuantity: 0,
    signQuantity: 0,
    compolatelQuantity: 0,
    GoingQuantity: 0,
    totalCount: 0
  };
  resourceStatus: any;
  constructor(
    public service: OrderManagementService,
    private modal: NzModalService,
    public shipperservice: ShipperBaseService,
    public router: Router,
    public ar: ActivatedRoute,
    public searchDrawerService: SearchDrawerService
  ) {
    super(searchDrawerService);
  }
  /**
   * 查询参数
   */
  get changeParams() {
    return {
      id: this.changeId
    };
  }
  get changeViewParams() {
    return {
      id: this.changeViewId
    };
  }
  get reqParams() {
    const a: any = {};
    if (this.resourceStatus) {
      a.billStatus = this.resourceStatus;
    }
    const params: any = Object.assign({}, this.sfValue || this.paramsList);
    delete params._$expand;
    return {
      ...a,
      ...params
    };
  }
  beforeReq = (requestOptions: STRequestOptions) => {
    const a: any = {};
    if (this.resourceStatus) {
      a.billStatus = this.resourceStatus;
    }
    const params: any = Object.assign({}, this.sfValue || this.paramsList);
    delete params._$expand;
    this.paramsList = params;
    Object.assign(requestOptions.body, {
      ...a,
      ...this.paramsList
    });
    this.loading = true;
    return requestOptions;
  };
  afterRes = (data: any[], rawData?: any) => {
    console.log(data);
    this.loading = false;
    return data.map(item => ({
      ...item,
      disabled: item.billStatus == '6'
    }));
  };
  get selectedRows() {
    return this.st?.list.filter(item => item.checked) || [];
  }
  ngOnInit(): void {
    this.getGoodsSourceStatistical();
    this.initSF();
    this.initST();
    this.initSTFloat();
    this.initSTFloatView();
  }
  search() {
    this.st?.load(1);
    this.getGoodsSourceStatistical();
  }
  getGoodsSourceStatistical() {
    this.tabs = {
      cancelQuantity: 0,
      receivedQuantity: 0,
      stayQuantity: 0,
      signQuantity: 0,
      compolatelQuantity: 0,
      GoingQuantity: 0,
      totalCount: 0
    };
    const params: any = Object.assign({}, this.reqParams || {});
    delete params.billStatus;
    this.service.request(this.service.$api_statisticalStatus, params).subscribe(res => {
      if (res) {
        let totalCount = 0;
        res.forEach((element: any) => {
          if (element.billStatusLabel === '待发车') {
            this.tabs.stayQuantity = element.quantity;
          } else if (element.billStatusLabel === '待接单') {
            this.tabs.receivedQuantity = element.quantity;
          } else if (element.billStatusLabel === '运输中') {
            this.tabs.GoingQuantity = element.quantity;
          } else if (element.billStatusLabel === '待签收') {
            this.tabs.signQuantity = element.quantity;
          } else if (element.billStatusLabel === '已完成') {
            this.tabs.compolatelQuantity = element.quantity;
          } else if (element.billStatusLabel === '已取消') {
            this.tabs.cancelQuantity = element.quantity;
          }
          totalCount += element.quantity;
        });
        this.tabs.totalCount = totalCount;
      }
    });
  }
  /**
   * 初始化查询表单
   */
  initSF() {
    this.schema = {
      properties: {
        _$expand: { type: 'boolean', ui: { hidden: true } },
        billCode: {
          type: 'string',
          title: '订单号',
          ui: {
            placeholder: '最多100个单号,空号隔开'
          }
        },
        wayBillCode: {
          type: 'string',
          title: '运单号',
          ui: {
            placeholder: '最多100个单号,空号隔开'
          }
        },
        resourceCode: {
          type: 'string',
          title: '货源编号'
        },
        shipperAppUserId: {
          type: 'string',
          title: '货主',
          ui: {
            widget: 'select',
            serverSearch: true,
            searchDebounceTime: 300,
            searchLoadingText: '搜索中...',
            allowClear: true,
            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: any) => (res as any[]).map(i => ({ label: i.enterpriseName, value: i.id } as SFSchemaEnum))))
                  .toPromise();
              } else {
                return of([]);
              }
            },
            change: (q: any) => {
              this.getRegionCode(q);
            }
          } as SFSelectWidgetSchema
        },
        enterpriseProjectId: {
          type: 'string',
          title: '所属项目',
          ui: {
            widget: 'select',
            placeholder: '请先选择货主'
          } as SFSelectWidgetSchema
        },
        loadingPlace: {
          type: 'string',
          title: '装货地',
          ui: {}
        },
        dischargePlace: {
          type: 'string',
          title: '卸货地',
          ui: {}
        },
        driverName: {
          title: '承运司机',
          type: 'string',
          ui: {}
        },
        carNo: {
          title: '车牌号',
          type: 'string',
          ui: {}
        },
        carCaptainName: {
          title: '车队长',
          type: 'string',
          ui: {}
        },
        paymentStatus: {
          title: '支付状态',
          type: 'string',
          ui: {
            widget: 'dict-select',
            params: { dictKey: 'overall:payment:status' },
            containsAllLable: true
          } as SFSelectWidgetSchema
        },
        // createTime: {
        //   title: '创建时间',
        //   type: 'string',
        //   ui: {
        //     widget: 'date',
        //     mode: 'range',
        //     format: 'yyyy-MM-dd'
        //   } as SFDateWidgetSchema
        // },
        createTime: {
          type: 'string',
          title: '创建时间',
          ui: { widget: 'sl-from-to', type: 'date', format: 'yyyy-MM-dd' } as SFDateWidgetSchema
        },
        riskStatus: {
          type: 'string',
          title: '是否风险单',
          enum: [
            { label: '全部', value: '' },
            { label: '是', value: '3' },
            { label: '否', value: '1' }
          ],
          ui: {
            widget: 'select',
            placeholder: '请选择'
          }
        },
        enterpriseInfoName: {
          type: 'string',
          title: '网络货运人',
          ui: {
            widget: 'select',
            placeholder: '请选择',
            allowClear: true,
            asyncData: () => this.shipperservice.getNetworkEnterpriseName()
          }
        },
        // goodsNameId: {
        //   type: 'string',
        //   title: '货物名称',
        //   ui: {
        //     widget: 'select',
        //     placeholder: '请选择',
        //     errors: { required: '请选择货物类型' },
        //     visibleIf: {
        //       _$expand: (value: boolean) => value,
        //     },
        //     asyncData: () =>
        //       this.shipperservice.loadConfigByKey('goods.name.config.type').pipe(
        //         map((data: any) => {
        //           return data[0].children?.map((m: any) => {
        //             return { label: m.name, value: m.id };
        //           });
        //         })
        //       ),
        //   } as SFSelectWidgetSchema
        // },
        serviceType: {
          title: '服务类型',
          type: 'string',
          default: '',
          ui: {
            widget: 'dict-select',
            params: { dictKey: 'service:type' },
            containsAllLable: true
          } as SFSelectWidgetSchema
        }
      },
      type: 'object'
    };
  }
  /**
   * 初始化数据列表
   */
  initST() {
    this.columns = [
      { title: '', type: 'checkbox', fixed: 'left', width: '50px', className: 'text-center' },
      {
        title: '订单号',
        width: '200px',
        fixed: 'left',
        className: 'text-left',
        render: 'billCode'
      },
      { title: '货主', index: 'shipperAppUserName', width: '250px', className: 'text-left' },
      { title: '录单员', render: 'createUserName', width: '200px', className: 'text-left' },
      { title: '装货地', index: 'loadingAddressArr', width: '180px', className: 'text-left' },
      {
        title: '卸货地',
        className: 'text-left',
        width: '180px',
        index: 'unloadingAddressArr'
      },
      {
        title: '运费明细',
        width: '250px',
        className: 'text-right',
        render: 'mybidDetailInfo'
      },
      {
        title: '货物信息',
        className: 'text-left',
        width: '170px',
        render: 'goodsName'
      },
      {
        title: '承运司机',
        className: 'text-left',
        width: '250px',
        render: 'driverName'
      },
      { title: '网络货运人', index: 'enterpriseInfoName', width: '250px', className: 'text-left' },
      { title: '关联运单号', index: 'wayBillCode', width: '170px', className: 'text-left' },
      { title: '关联货源编号', index: 'resourceCode', width: '170px', className: 'text-left' },
      {
        title: '装卸货时间',
        width: '200px',
        className: 'text-left',
        render: 'loadingTime'
      },
      {
        title: '录单时间',
        className: 'text-left',
        index: 'recordTime',
        width: '170px'
      },
      {
        title: '创建时间',
        className: 'text-left',
        index: 'createTime',
        width: '170px'
      },
      {
        title: '操作',
        fixed: 'right',
        width: '130px',
        className: 'text-center block-td',
        buttons: [
          {
            text: '运费变更记录',
            click: _record => this.OpenPrice(_record),
            iif: item =>
              item.billType !== '3' &&
              (item.billStatus == '4' ||
                item.billStatus == '5' ||
                item.billStatus == '2' ||
                item.billStatus == '3' ||
                item.billStatus == '6'),
            acl: { ability: ['ORDER-VEHICLE-ChangeApplyList'] }
          },
          // {
          //   text: '查看详情',
          //   click: (item: any) => {
          //     this.router.navigate(['./vehicle-detail', item.id], { relativeTo: this.ar });
          //   },
          //   acl: { ability: ['USERCENTER-FREIGHT-USER-view'] }
          // },
          {
            text: '查看评价',
            click: _record => this.viewEvaluate(_record),
            iif: item => item.billStatus == '5',
            acl: { ability: ['ORDER-VEHICLE-evaluation'] }
          },
          {
            text: '变更运费',
            click: _record => this.updateFreight(_record),
            iif: item => item.billType !== '3' && item.billStatus !== '1' && item.billStatus !== '6' && item.overallPaymentStatus != '2',
            acl: { ability: ['ORDER-VEHICLE-FreightChangeWholeDetail'] }
          },
          {
            text: '确认签收',
            click: _record => this.confirmReceipt(_record),
            iif: item => item.billStatus == '4',
            acl: { ability: ['ORDER-VEHICLE-signWholeOrder'] }
          },
          {
            text: '取消订单',
            click: _record => this.cancellation(_record),
            iif: item => item.billStatus !== '6' && item.overallPaymentStatus !== '2',
            acl: { ability: ['ORDER-VEHICLE-cancelAnOrder'] }
          },
          {
            text: '修改订单',
            click: _record => this.changeOrder(_record),
            iif: item => item.billStatus == '4' || item.billStatus == '5' || item.billStatus == '2' || item.billStatus == '3',
            acl: { ability: ['ORDER-VEHICLE-modificationOrder'] }
          },
          {
            text: '申请退款',
            click: _record => this.applyRefund(_record),
            iif: item => item.isApplyForRefund,
            acl: { ability: ['ORDER-VEHICLE-modificationOrder'] }
          },
          {
            text: '查看轨迹',
            click: _record => this.viewTrack(_record),
            iif: item => item.billStatus !== '1' && item.billStatus !== '6'
            // acl: { ability: ['VEHICLE-LIST-view'] },
          },
          {
            text: '订单上报推送',
            click: _record => this.orderReportPush(_record),
            iif: item => item.overallPaymentStatus === '2' && (item.billStatus === '4' || item.billStatus === '5'),
            acl: { ability: ['ORDER-VEHICLE-push'] },
          }
        ]
      }
    ];
  }
  initSTFloat() {
    this.columnsFloat = [
      {
        title: '序号',
        className: 'text-center',
        render: 'order'
      },
      {
        title: '操作时间',
        className: 'text-center',
        index: 'applyTime'
      },
      {
        title: '操作人',
        className: 'text-center',
        index: 'applyUserName'
      },
      { title: '状态', index: 'handleStatusLabel', className: 'text-center' },
      {
        title: '操作',
        fixed: 'right',
        className: 'text-center',
        buttons: [
          {
            text: '查看',
            click: _record => this.FloatView(_record)
          },
          {
            text: '撤销',
            click: _record => this.revoke(_record),
            iif: item => item.handleStatus === '1' || item.handleStatus === 1
          }
        ]
      }
    ];
  }
  initSTFloatView() {
    this.columnsFloatView = [
      {
        title: '费用名称',
        width: '100px',
        className: 'text-center',
        index: 'costName'
      },
      {
        title: '变更前',
        width: '100px',
        className: 'text-center',
        index: 'amountBeforeChange',
        render: 'amountBeforeChange'
      },
      { title: '变更值', index: 'amountchangeValue', render: 'amountchangeValue', width: '120px', className: 'text-center' },
      { title: '变更后', index: 'amountAfterChange', render: 'amountAfterChange', width: '120px', className: 'text-center' }
    ];
  }
  // 获取城市列表
  getRegionCode(regionCode: any) {
    console.log(regionCode);
    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.sf.getProperty('/enterpriseProjectId')!.schema.enum = res;
        this.sf.getProperty('/enterpriseProjectId')!.widget.reset(res);
        // if (this.enterpriseProjectIds) {
        //   this.sf1.setValue('/enterpriseProjectId', this.enterpriseProjectIds);
        // }
      });
  }
  /**
   * 查询字段个数
   */
  get queryFieldCount(): number {
    return Object.keys(this.schema?.properties || {}).length;
  }
  tabChange(item: any) {
    console.log(item);
  }
  selectChange(e: number) {
    this.resourceStatus = e;
    this.initST();
    setTimeout(() => {
      this.st.load();
    }, 500);
  }
  /**
   * 导入货源
   */
  importGoodsSource() {}
  audit(item: any) {}
  /*
  * 审核关闭弹窗
  view: 1
  浮动费用: 0
  查看评价: 3
  */
  handleCancel(type: string) {
    console.log(type);
    if (type === '0') {
      this.isVisible = false;
    } else if (type === '1') {
      this.isVisibleView = false;
    } else if (type === '2') {
      this.isVisibleEvaluate = false;
    }
  }
  OpenPrice(value: any) {
    this.changeId = value.id;
    this.isVisible = true;
  }
  /**
   * 浮动费用查看
   */
  FloatView(item: any) {
    console.log(item);
    this.changeViewId = item.id;
    this.service.request(this.service.$api_getChangeRecordWholeDetail, { id: this.changeViewId }).subscribe(res => {
      this.ViewCause = res;
    });
    this.isVisibleView = true;
  }
  /**
   *查看评价
   */
  viewEvaluate(item: any) {
    console.log(item);
    this.isVisibleEvaluate = true;
    const params = {
      businessCode: item.billCode,
      evaluateUserId: item.shipperAppUserId
    };
    const params2 = {
      businessCode: item.billCode,
      evaluateUserId: item.shipperAppUserId
    };
    this.service.request(this.service.$api_getBillEvaluateByShipper, params).subscribe(res => {
      console.log(res);
      this.shipList = res.evaluateInfos;
    });
    this.service.request(this.service.$api_getBillEvaluateDriverByShipper, params2).subscribe(res => {
      console.log(res);
      this.diverList = res.evaluateInfos;
    });
  }
  /**
   *变更运费
   */
  updateFreight(item: any) {
    console.log(item?.isFreightChangeApplication);
    this.service.request(this.service.$api_get_getFreightChangeWholeDetail, { id: item.id }).subscribe(data => {
      if (data) {
        const modal = this.modal.create({
          nzTitle: '变更运费',
          nzWidth: 580,
          nzContent: VehicleUpdateFreightComponent,
          nzComponentParams: { data: { ...data, id: item.id, isFreightChangeApplication: item?.isFreightChangeApplication } },
          nzFooter: null
        });
        modal.afterClose.subscribe((res: Boolean) => {
          if (res) {
            this.st.load();
            this.getGoodsSourceStatistical();
          }
        });
      }
    });
  }
  /**
   *修改附加费率
   */
  modifyRate() {
    let params: any[] = [];
    this.selectedRows.forEach(item => {
      params.push(item.id);
    });
    if (params.length === 0) {
      this.service.msgSrv.error('请先选择订单!');
      return;
    }
    const modal = this.modal.create({
      nzTitle: '修改附加费率',
      nzWidth: 600,
      nzContent: VehicleModifyRateComponent,
      nzComponentParams: { data: { ids: params } },
      nzFooter: null
    });
    modal.afterClose.subscribe(result => {
      if (result) {
        this.st.load(1);
        this.getGoodsSourceStatistical();
      }
    });
  }
  /**
   *修改网络货运人
   */
  modifyFreightPeople() {
    let params: any[] = [];
    this.selectedRows.forEach(item => {
      params.push(item.id);
    });
    let params2: any[] = [];
    this.selectedRows.forEach(item => {
      params2.push(item.enterpriseInfoId);
    });
    if (params.length === 0) {
      this.service.msgSrv.error('请先选择订单!');
      return;
    }
    const modal = this.modal.create({
      nzTitle: '修改网络货运人',
      nzWidth: 600,
      nzContent: VehicleFreightPeopleComponent,
      nzComponentParams: { data: { ids: params, enterpriseInfoIds: params2 } },
      nzFooter: null
    });
    modal.afterClose.subscribe(result => {
      if (result) {
        this.st.load(1);
        this.getGoodsSourceStatistical();
      }
    });
  }
  /**
   *修改网络货运人
   */
  modifycaptain() {
    let params: any[] = [];
    this.selectedRows.forEach(item => {
      params.push(item.id);
    });
    if (params.length === 0) {
      this.service.msgSrv.error('请先选择订单!');
      return;
    }
    const modal = this.modal.create({
      nzTitle: '修改车队长',
      nzWidth: 900,
      nzContent: VehicleModifyCaptainComponent,
      nzComponentParams: { data: { ids: params } },
      nzFooter: null
      // nzOnOk: sin => {
      //       this.st.reload();
      //     }
      //   });
      //   return false;
      // }
    });
    modal.afterClose.subscribe(result => {
      if (result) {
        this.st.load(1);
        this.getGoodsSourceStatistical();
      }
    });
  }
  // 订单上报推送
  orderReportPush(item: any) {
    this.service.request(this.service.$api_manualOrderSubmission,{id: item.id}).subscribe( res=> {
      if(res) {
        this.st.reload(this.st.pi)
        this.service.msgSrv.success('推送成功');
      }
    })
  }
  //  *确认签收
  confirmReceipt(item: any) {
    const modalRef = this.modal.create({
      nzTitle: '确认签收',
      nzWidth: '50%',
      nzContent: VehicleConfirReceiptComponent,
      nzComponentParams: {
        i: item,
        Status: 2
      },
      nzFooter: null
    });
    modalRef.afterClose.subscribe((res: boolean) => {
      if (res) {
        this.st.load();
        this.getGoodsSourceStatistical();
      }
    });
  }
  revoke(item: any) {
    this.modal.confirm({
      nzTitle: '是否确定立即撤销费用变更!',
      nzOnOk: () =>
        this.service.request(this.service.$api_get_revokeChangeRecord, { id: item.id }).subscribe(res => {
          console.log(res);
          if (res) {
            this.service.msgSrv.success('撤销成功!');
            this.stFloat.reload();
          }
        })
    });
  }
  // 取消订单
  cancellation(item: any) {
    // api_get_cancelAnOrder
    this.modal.confirm({
      nzTitle: '确定取消该订单吗?',
      nzContent: `取消后无法恢复,请确认`,
      nzOnOk: () =>
        this.service.request(this.service.$api_get_cancelAnOrder, { id: item.id }).subscribe(res => {
          if (res === true) {
            this.service.msgSrv.success('操作成功!');
            this.st.load(1);
            this.getGoodsSourceStatistical();
            this.initST();
          }
        })
    });
  }
  userAction() {
    let params: any[] = [];
    if (this.selectedRows.length <= 0) {
      this.service.msgSrv.warning('请选择需要签收的订单!');
      return;
    }
    let flag = true;
    this.selectedRows.forEach(item => {
      if (item.billStatus !== '4') {
        this.service.msgSrv.warning('存在非待签收状态订单,无法签收!');
        flag = false;
      }
      params.push(item.id);
    });
    if (!flag) return;
    this.service.request(this.service.$api_get_batchSignWholeOrder, params).subscribe(res => {
      if (res) {
        console.log(res);
        this.st.load(1);
        this.getGoodsSourceStatistical();
      }
    });
  }
  // 修改订单
  changeOrder(value: any) {
    this.router.navigate(['order-management/vehicle-detailChange', value.id]);
  }
  /**
   *申请退款
   */
  applyRefund(item: any) {
    const modalRef = this.modal.create({
      nzTitle: '申请退款',
      nzContent: OneCarOrderCancelConfirmComponent,
      nzComponentParams: {
        i: item,
        sts: 2
      },
      nzFooter: null
    });
    modalRef.afterClose.subscribe((res: boolean) => {
      if (res) {
        this.st.load();
      }
    });
  }
  /**
   *查看轨迹
   */
  viewTrack(item: any) {
    const modalRef = this.modal.create({
      nzTitle: '查看轨迹',
      nzContent: OneCarOrderViewtrackComponent,
      nzWidth: '900px',
      nzComponentParams: {
        i: item
      },
      nzFooter: null
    });
    modalRef.afterClose.subscribe((res: boolean) => {
      if (res) {
      }
    });
  }
  // 导出
  exprot() {
    this.service.exportStart({ ...this.reqParams, pageSize: -1 }, this.service.$api_get_asyncExportWholeList);
  }
}