import { Component, OnInit, ViewChild } from '@angular/core';
import { STColumn, STComponent, STRequestOptions } from '@delon/abc/st';
import { SFComponent, SFDateWidgetSchema, SFSchema, SFSchemaEnum, SFSelectWidgetSchema, SFUISchema } from '@delon/form';
import { ModalHelper, _HttpClient } from '@delon/theme';
import { NzModalService } from 'ng-zorro-antd/modal';
import { map } from 'rxjs/operators';
import { OrderManagementService } from '../../services/order-management.service';
import { UpdateFreightComponent } from '../../modal/bulk/update-freight/update-freight.component';
import { ConfirReceiptComponent } from '../../modal/bulk/confir-receipt/confir-receipt.component';
import { of } from 'rxjs';
import { ShipperBaseService } from '@shared';
import { Router, ActivatedRoute } from '@angular/router';
import { OneCarOrderCancelConfirmComponent } from '../../modal/vehicle/cancel-confirm/cancel-confirm.component';
@Component({
  selector: 'app-supply-management-bulk',
  templateUrl: './bulk.component.html',
  styleUrls: ['./bulk.component.less']
})
export class OrderManagementBulkComponent implements OnInit {
  ui: SFUISchema = {};
  uiView: SFUISchema = {};
  schema: SFSchema = {};
  schemaView: SFSchema = {};
  auditMany = false;
  isVisibleView = false;
  isVisibleEvaluate = false;
  isVisible = false;
  _$expand = false;
  loading: boolean = true;
  changeId: any; // 主页面查看运费变更记录id - 用于运费变更记录
  changeViewId: any; // 查看运费变更记录id - 用于查看
  ViewCause: any; // 变更运费查看数据
  sfViewFormData: any; // 变更运费查看的sf 数据
  shipList: any; // 货主评价 数据
  diverList: any; // 司机评价 数据
  @ViewChild('st') private readonly st!: STComponent;
  @ViewChild('stFloat') private readonly stFloat!: STComponent;
  @ViewChild('stFloatView') private readonly stFloatView!: STComponent;
  @ViewChild('sf', { static: false }) sf!: SFComponent;
  @ViewChild('sfFre', { static: false }) sfFre!: SFComponent;
  @ViewChild('sfView', { static: false }) sfView!: SFComponent;
  columns: STColumn[] = [];
  columnsFloat: STColumn[] = [];
  columnsFloatView: STColumn[] = [];
  demoValue: any;
  resourceStatus: any;
  tabs = {
    cancelQuantity: 0,
    receivedQuantity: 0,
    stayQuantity: 0,
    signQuantity: 0,
    compolatelQuantity: 0,
    GoingQuantity: 0,
    totalCount: 0
  };
  constructor(
    public service: OrderManagementService,
    private modal: NzModalService,
    public shipperservice: ShipperBaseService,
    private router: Router,
    private ar: ActivatedRoute,
  ) {}
  /**
   * 查询参数
   */
  get reqParams() {
    const a: any = {};
    if (this.resourceStatus) {
      a.billStatus = this.resourceStatus;
    }
    const params: any = Object.assign({}, this.sf?.value || {});
    delete params._$expand;
    return {
      ...a,
      ...params,
      createTime: {
        start: this.sf?.value?.createTime?.[0] || '',
        end: this.sf?.value?.createTime?.[1] || ''
      }
    };
  }
  beforeReq = (requestOptions: STRequestOptions) => {
    const a: any = {};
    if (this.resourceStatus) {
      a.billStatus = this.resourceStatus;
    }
    const params: any = Object.assign({}, this.sf?.value || {});
    delete params._$expand;
    if (this.sf) {
      Object.assign(requestOptions.body, {
        ...a,
        ...params,
        createTime: {
          start: this.sf?.value?.createTime?.[0] || '',
          end: this.sf?.value?.createTime?.[1] || ''
        }
      });
    }
    this.loading = true;
    return requestOptions;
  };
  afterRes = (data: any[], rawData?: any) => {
    console.log(data)
    this.loading = false
    return data.map(item => ({
      ...item,
      disabled: item.billStatus !== '4' 
    }));
  };
  get selectedRows() {
    return this.st?.list.filter(item => item.checked) || [];
  }
  get changeParams() {
    return {
      id: this.changeId
    };
  }
  search() {
    this.st?.load();
    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_getBulkStatistical, 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.signQuantity = element.quantity;
          } else if (element.billStatusLabel === '已完成') {
            this.tabs.compolatelQuantity = element.quantity;
          } else if (element.billStatusLabel === '已取消') {
            this.tabs.cancelQuantity = element.quantity;
          } else if (element.billStatusLabel === '运输中') {
            this.tabs.GoingQuantity = element.quantity;
          }
          totalCount += element.quantity;
        });
        this.tabs.totalCount = totalCount;
      }
    });
  }
  selectChange(e: number) {
    this.resourceStatus = e;
    this.initST();
    setTimeout(() => {
      this.st.load();
    }, 500);
  }
  ngOnInit(): void {
    this.getGoodsSourceStatistical();
    this.initSF();
    this.initST();
    this.initSTFloat();
    this.initSTFloatView();
    this.initSFView();
  }
  /**
   * 初始化查询表单
   */
  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,
            visibleIf: {
              _$expand: (value: boolean) => value
            },
            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: '请先选择货主',
            visibleIf: {
              _$expand: (value: boolean) => value
            },
          } as SFSelectWidgetSchema
        },
        loadingPlace: {
          type: 'string',
          title: '装货地',
          ui: {
            visibleIf: {
              _$expand: (value: boolean) => value
            }
          }
        },
        dischargePlace: {
          type: 'string',
          title: '卸货地',
          ui: {
            visibleIf: {
              _$expand: (value: boolean) => value
            }
          }
        },
        driverName: {
          title: '承运司机',
          type: 'string',
          ui: {
            visibleIf: {
              _$expand: (value: boolean) => value
            }
          }
        },
        carNo: {
          title: '车牌号',
          type: 'string',
          ui: {
            visibleIf: {
              _$expand: (value: boolean) => value
            }
          }
        },
        carCaptainName: {
          title: '车队长',
          type: 'string',
          ui: {
            visibleIf: {
              _$expand: (value: boolean) => value
            }
          }
        },
        paymentStatus: {
          title: '支付状态',
          type: 'string',
          ui: {
            widget: 'dict-select',
            params: { dictKey: 'overall:payment:status' },
            containsAllLabel: true,
            visibleIf: {
              _$expand: (value: boolean) => value
            }
          } as SFSelectWidgetSchema
        },
        createTime: {
          title: '创建时间',
          type: 'string',
          ui: {
            widget: 'date',
            mode: 'range',
            format: 'yyyy-MM-dd',
            allowClear: true,
            visibleIf: {
              _$expand: (value: boolean) => value
            }
          } as SFDateWidgetSchema
        },
        riskStatus: {
          type: 'string',
          title: '是否风险单',
          enum: [
            { label: '全部', value: '' },
            { label: '是', value: '3' },
            { label: '否', value: '1' }
          ],
          ui: {
            widget: 'select',
            placeholder: '请选择',
            visibleIf: {
              _$expand: (value: boolean) => value
            }
          }
        },
        enterpriseInfoId: {
          type: 'string',
          title: '网络货运人',
          ui: {
            widget: 'select',
            placeholder: '请选择',
            allowClear: true,
            visibleIf: {
              _$expand: (value: boolean) => value
            },
            asyncData: () => this.shipperservice.getNetworkFreightForwarder()
          }
        },
        serviceType: {
          title: '服务类型',
          type: 'string',
          default: '',
          ui: {
            widget: 'dict-select',
            params: { dictKey: 'service:type' },
            containsAllLabel: true,
            visibleIf: {
              _$expand: (value: boolean) => value
            }
          } as SFSelectWidgetSchema
        },
        settlementBasis: {
          title: '结算依据',
          type: 'string',
          ui: {
            widget: 'dict-select',
            containsAllLabel: true,
            params: { dictKey: 'goodresource:settlement:type' },
            containAllLable: true,
            visibleIf: {
              _$expand: (value: boolean) => value
            }
          } as SFSelectWidgetSchema
        }
      },
      type: 'object'
    };
    this.ui = { '*': { spanLabelFixed: 110, grid: { span: 8, gutter: 4 } } };
  }
  /**
   * 初始化查询表单
   */
  initSFView() {
    this.schemaView = {
      properties: {
        freightPrice: {
          type: 'string',
          title: '运费单价'
        },
        rule: {
          title: '',
          type: 'string',
          ui: {
            widget: 'dict-select',
            params: { dictKey: 'goodresource:rounding:rules' },
            visibleIf: {
              _$expand: (value: boolean) => value
            }
          } as SFSelectWidgetSchema
        },
        settlementBasis: {
          type: 'string',
          title: '结算重量',
          ui: {
            widget: 'dict-select',
            params: { dictKey: 'goodresource:settlement:type' },
            visibleIf: {
              _$expand: (value: boolean) => value
            }
          } as SFSelectWidgetSchema
        }
      }
    };
    this.uiView = { '*': { spanLabelFixed: 80, grid: { span: 12, gutter: 4 } } };
  }
  // 获取所属项目
  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);
        // }
      });
  }
  /**
   * 初始化数据列表
   */
  initST() {
    this.columns = [
      { title: '', type: 'checkbox', fixed: 'left', width: '50px', className: 'text-center' },
      {
        title: '订单号',
        width: '180px',
        fixed: 'left',
        className: 'text-left',
        render: 'billCode'
      },
      {
        title: '运费明细',
        width: '250px',
        className: 'text-right',
        render: 'mybidDetailInfo'
      },
      { title: '录单员', render: 'createUserName', width: '200px', className: 'text-left' },
      { title: '网络货运人', index: 'enterpriseInfoName', width: '250px', className: 'text-left' },
      { title: '货主', index: 'shipperAppUserName', width: '250px', className: 'text-left' },
      { title: '所属项目', index: 'enterpriseProjectName', width: '250px', className: 'text-left' },
      { title: '关联运单号', index: 'wayBillCode', width: '180px', className: 'text-left' },
      { title: '货源编号', index: 'resourceCode', width: '180px', className: 'text-left' },
      { title: '装货地', index: 'loadingAddressArr', width: '180px', className: 'text-left' },
      {
        title: '卸货地',
        className: 'text-left',
        width: '180px',
        index: 'unloadingAddressArr'
      },
      // {
      //   title: '货物信息',
      //   className: 'text-left',
      //   width: '250px',
      //   render: 'goodsName'
      // },
      {
        title: '货物信息',
        index: 'goodsName',
        width: '180px',
        className: 'text-left',
        format: (item: any) =>
          `${item.goodsName}/
          ${item.goodsWeight || '0'}吨/
          ${item.goodsVolume || '0'}方/
          ${item.goodsNumber || '0'}件`
      },
      {
        title: '运费单价',
        className: 'text-right',
        width: '180px',
        render: 'freightPrice'
      },
      {
        title: '接单数量',
        render: 'receveOrderCountInfo',
        width: '170px',
        className: 'text-left',
        format: (item: any) =>
          `${item.loadWeight || '0'}吨/
           ${item.loadVolume || '0'}方`
      },
      {
        title: '结算数量',
        index: '结算数量',
        width: '170px',
        className: 'text-left',
        format: (item: any) =>
          `${item.settlementWeight || '0'}吨/
           ${item.settlementVolume || '0'}方`
      },
      {
        title: '承运司机',
        className: 'text-left',
        width: '250px',
        index: 'driverName',
        render: 'driverName'
      },
      {
        title: '收款人',
        className: 'text-left',
        width: '180px',
        index: 'payeeName',
        render: 'payeeName'
      },
      {
        title: '装卸货时间',
        width: '200px',
        className: 'text-left',
        render: 'loadingTime'
      },
      {
        title: '创建时间',
        width: '180px',
        className: 'text-left',
        index: 'createTime'
      },
      {
        title: '操作',
        fixed: 'right',
        width: '130px',
        className: 'text-left block-td',
        buttons: [
          {
            text: '运费变更记录',
            click: _record => this.OpenPrice(_record),
            iif: item =>
              item.billStatus == '4' || item.billStatus == '5' || item.billStatus == '2' || item.billStatus == '3' || item.billStatus == '6',
            acl: { ability: ['ORDER-BULK-listChangeApply'] },
          },
          {
            text: '查看评价',
            click: _record => this.viewEvaluate(_record),
            iif: item => item.billStatus == '5',
            acl: { ability: ['ORDER-BULK-evaluation'] },
          },
          {
            text: '查看详情',
            click: (item: any) => {
              this.router.navigate(['./bulk-detail', item.id], { relativeTo: this.ar });
            },
            acl: { ability: ['USERCENTER-FREIGHT-USER-view'] },
          },
          {
            text: '变更运费',
            click: _record => this.updateFreight(_record),
            iif: item => item.billStatus !== '1' && item.billStatus !== '6' && item.overallPaymentStatus != '2',
            acl: { ability: ['ORDER-BULK-FreightChangeBulkDetail'] },
          },
          {
            text: '确认签收',
            click: _record => this.confirmReceipt(_record),
            iif: item => item.billStatus == '4',
            acl: { ability: ['VEHICLE-LIST-view'] },
          },
          {
            text: '取消订单',
            click: _record => this.cancellation(_record),
            iif: item =>
              item.billStatus == '4' || item.billStatus == '5' || item.billStatus == '2' || item.billStatus == '3' || item.billStatus == '1',
            acl: { ability: ['ORDER-BULK-signBulkOrder'] },
          },
          {
            text: '申请退款',
            click: (_record) => this.applyRefund(_record),
            iif: item => item.isApplyForRefund,
            acl: { ability: ['ORDER-VEHICLE-modificationOrder'] },
          },
          {
            text: '修改订单',
            click: _record => this.changeOrder(_record),
            iif: item => item.billStatus == '4' || item.billStatus == '5' || item.billStatus == '2' || item.billStatus == '3',
            acl: { ability: ['ORDER-BULK-BulkBillDetail'] },
          }
        ]
      }
    ];
  }
  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, _modal, _instance) => this.view(_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: 'amountAfterChange',
        render: 'amountAfterChange'
      },
      { title: '变更值', index: 'amountchangeValue', width: '120px', className: 'text-center', render: 'amountchangeValue' },
      { title: '变更后', index: 'amountBeforeChange', render: 'amountBeforeChange', width: '120px', className: 'text-center' }
    ];
  }
  /**
   * 查询字段个数
   */
  get queryFieldCount(): number {
    return Object.keys(this.schema?.properties || {}).length;
  }
  get changeViewParams() {
    return {
      id: this.changeViewId
    };
  }
  /**
   * 伸缩查询条件
   */
  expandToggle(): void {
    this._$expand = !this._$expand;
    this.sf?.setValue('/_$expand', this._$expand);
  }
  tabChange(item: any) { }
  /**
   * 重置表单
   */
  resetSF(): void {
    this.sf.reset();
    this._$expand = false;
  }
  /**
   * 导入货源
   */
  importGoodsSource() { }
  audit(item: any) { }
  /*
  * 审核关闭弹窗
  view: 1
  浮动费用: 0
  查看评价: 3
  */
  handleCancel(type: string) {
    if (type === '0') {
      this.isVisible = false;
    } else if (type === '1') {
      console.log(type);
      this.isVisibleView = false;
    } else if (type === '2') {
      this.isVisibleEvaluate = false;
    }
  }
  /**
   * 审核通过按钮
   */
  handleOK() { }
  OpenPrice(item: any) {
    this.changeId = item.id;
    this.isVisible = true;
  }
  /**
   * 浮动费用查看
   */
  FloatView(item: any) {
    this.changeViewId = item.id;
    this.service.request(this.service.$api_getChangeRecordBulkDetail, { 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);
      console.log(res.evaluateInfos);
      this.shipList = res.evaluateInfos;
    });
    this.service.request(this.service.$api_getBillEvaluateDriverByShipper, params2).subscribe(res => {
      console.log(res);
      this.diverList = res.evaluateInfos;
    });
  }
  /**
   *变更运费
   */
  updateFreight(item: any) {
    this.service.request(this.service.$api_getFreightChangeBulkDetail, { id: item.id }).subscribe(data => {
      if (data) {
        const modal = this.modal.create({
          nzTitle: '变更运费',
          nzWidth: 580,
          nzContent: UpdateFreightComponent,
          nzComponentParams: { data: { ...data, billId: item.id } },
          nzFooter: null
        });
        modal.afterClose.subscribe((res: any) => {
          if (res) {
            this.st.reload(1);
            this.getGoodsSourceStatistical();
          }
        });
      }
    });
  }
  //  *确认签收
  confirmReceipt(item: any) {
    const modalRef = this.modal.create({
      nzTitle: '确认签收',
      nzWidth: '50%',
      nzContent: ConfirReceiptComponent,
      nzComponentParams: {
        i: item,
        Status: 1
      },
      nzFooter: null
    });
    modalRef.afterClose.subscribe((result: any) => {
      this.st.load(1);
      this.getGoodsSourceStatistical();
    });
  }
  userAction() {
    if (this.selectedRows.length <= 0) {
      this.service.msgSrv.error('请选择订单!');
      return;
    }
    let params: any[] = [];
    this.selectedRows.forEach(item => {
      params.push(item.id);
    });
    this.service.request(this.service.$api_get_batchSignBulkOrder, params).subscribe(res => {
      if (res) {
        this.st.load(1);
        this.getGoodsSourceStatistical();
      }
    });
  }
  // 取消订单
  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?.reload(1);
            this.getGoodsSourceStatistical();
            this.initST();
          }
          this.st?.reload(1);
          this.getGoodsSourceStatistical();
        })
    });
  }
  revoke(item: any) {
    this.modal.confirm({
      nzTitle: '是否确定立即撤销费用变更!',
      nzOnOk: () =>
        this.service.request(this.service.$api_get_revokeChangeRecord, { id: item.id }).subscribe(res => {
          if (res) {
            this.service.msgSrv.success('撤销成功!');
            this.stFloat.reload();
            this.st?.reload(1);
            this.getGoodsSourceStatistical();
          }
        })
    });
  }
  // 修改订单
  changeOrder(value: any) {
    this.router.navigate(['order-management/bulk-detailChange', value.id]);
  }
  /**
*申请退款
*/
  applyRefund(item: any) {
    const modalRef = this.modal.create({
      nzTitle: '申请退款',
      nzContent: OneCarOrderCancelConfirmComponent,
      nzComponentParams: {
        i: item,
        sts: 1
      },
      nzFooter: null
    });
    modalRef.afterClose.subscribe((res: boolean) => {
      if (res) {
        this.resetSF;
        this.st.load();
      }
    });
  }
}