import { ActivatedRoute, Router } from '@angular/router';
import { Component, OnInit, ViewChild, OnChanges } from '@angular/core';
import { STColumn, STComponent, STRequestOptions } from '@delon/abc/st';
import { SFComponent, 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 { SupplyManagementService } from '../../services/supply-management.service';
import { SupplyManagementVehicleAssignedCarComponent } from '../assigned-car/assigned-car.component';
import { SupplyManagementUpdateExternalSnComponent } from '../update-external-sn/update-external-sn.component';
import { of } from 'rxjs';
import { ShipperBaseService } from '@shared';
import { SupplyManagementImportSupplyComponent } from '../../model/import-supply/import-supply.component';

@Component({
  selector: 'app-supply-management-vehicle',
  templateUrl: './vehicle.component.html',
  styleUrls: ['./vehicle.component.less']
})
export class SupplyManagementVehicleComponent implements OnInit {
  @ViewChild('st') private readonly st!: STComponent;
  @ViewChild('sf', { static: false }) sf!: SFComponent;
  @ViewChild('sfFre', { static: false }) sfFre!: SFComponent;
  loading: boolean = true;
  schema: SFSchema = this.initSF();
  columns: STColumn[] = this.initST();
  _$expand = false;
  tabs = {
    totalQuantity: 0,
    cancelQuantity: 0,
    receivedQuantity: 0,
    stayQuantity: 0
  };

  isVisible = false;
  freightSchema: SFSchema = {};
  auditMany = false;

  resourceStatus: any;
  auditID: any;
  constructor(
    public service: SupplyManagementService,
    private modal: NzModalService,
    private router: Router,
    private ar: ActivatedRoute,
    public shipperSrv: ShipperBaseService
  ) { }

  /**
   * 查询参数
   */
  get reqParams() {
    const params = Object.assign({}, this.sf?.value || {});
    delete params._$expand;
    const a: any = {
      ...params
    };
    if (this.resourceStatus) {
      a.resourceStatus = this.resourceStatus;
    }
    this.loading = true;
    return {
      ...a
    };
  }
  beforeReq = (requestOptions: STRequestOptions) => {
    const params = Object.assign({}, this.sf?.value || {});
    delete params._$expand;
    const a: any = {
      ...params
    };
    if (this.resourceStatus) {
      a.resourceStatus = this.resourceStatus;
    }
    if (this.sf) {
      Object.assign(requestOptions.body, {
        ...a
      });
    }
    this.loading = true;
    return requestOptions;
  };
  afterRes = (data: any[], rawData?: any) => {
    this.loading = false;
    return data.map(item => ({
      ...item,
      disabled: item.auditStatus !== '1'
    }));
  };

  get selectedRows() {
    return this.st?.list.filter(item => item.checked) || [];
  }
  ngOnInit(): void {
    this.initSFFre();
    this.getGoodsSourceStatistical();
  }
  /**
   * 初始化查询表单
   */

  initSFFre() {
    this.freightSchema = {
      properties: {
        remarks: {
          title: '备注',
          type: 'string',
          maxLength: 50,
          ui: {
            placeholder: '请输入备注',
            widget: 'textarea'
          }
        }
      },
      require: ['remarks']
    };
  }

  add(): void {
    // this.modal
    //   .createStatic(FormEditComponent, { i: { id: 0 } })
    //   .subscribe(() => this.st.reload());
  }

  search() {
    this.st?.load(1);
    this.getGoodsSourceStatistical();
  }
  /**
   * 伸缩查询条件
   */
  expandToggle(): void {
    this._$expand = !this._$expand;
    this.sf?.setValue('/_$expand', this._$expand);
  }
  /**
   * 重置表单
   */
  resetSF(): void {
    this.sf.reset();
    this._$expand = false;
  }

  selectChange(e: number) {
    this.resourceStatus = e;
    setTimeout(() => {
      this.st.load(1);
    }, 500);
  }
  /**
   * 导入货源
   */
   importGoodsSource() {
    const modalRef = this.modal.create({
      nzTitle: '货源导入',
      nzWidth: 600,
      nzContent: SupplyManagementImportSupplyComponent,
      nzComponentParams: {
        // i: item
      },
      nzFooter: null
    });
    modalRef.afterClose.subscribe(result => {
      if (result) {
        const tipsModal = this.modal.create({
          nzTitle: '上传提示',
          nzWidth: 600,
          nzContent: `<div>文件上传完成！成功<span class="text-blue-dark">${result?.successNumber}</span>条，失败<span class="text-red-dark">${result?.failNumber}</span>条！</div>`,
          nzFooter: [
            {
              label: '取 消',
              type: 'default',
              onClick: () => {
                tipsModal.destroy();
                this.st?.reload();
                this.getGoodsSourceStatistical();
              }
            },
            {
              label: '下载失败数据',
              type: 'primary',
              loading: this.service.http.loading,
              onClick: () => {
                if(!result?.failNumber) {
                  this.service.msgSrv.error('没有失败数据！');
                  tipsModal.destroy();
                  this.st?.reload();
                  this.getGoodsSourceStatistical();
                  return;
                }
                this.service.downloadFile(this.service.$api_getFailUploadGoodsOperateResource, result.ids)
                tipsModal.destroy();
                this.st?.reload();
                this.getGoodsSourceStatistical();
              }
            },
          ]
        })
        tipsModal.afterClose.subscribe(result => { 
          this.st?.reload();
         this.getGoodsSourceStatistical();
        })
      } else {
        this.st?.reload();
        this.getGoodsSourceStatistical();
      }
    });
  }


  /**
   * 重新指派
   */
  /**
   * 重新指派
   */
  assignedCar(item: any) {
    const { id } = item;
    const modalRef = this.modal.create({
      nzTitle: '指派熟车',
      nzWidth: '1200px',
      nzContent: SupplyManagementVehicleAssignedCarComponent,
      nzComponentParams: {
        i: item,
        status: 'anew',
        params: { id },
        url: this.service.$api_save_assign_vehicle
      },
      nzFooter: null
    });
    modalRef.afterClose.subscribe(result => {
      if (result) {
        this.st.reload();
      }
    });
  }
  /**
   * 审核
   */
  audit(value: any, status?: any) {
    console.log(value);
    console.log(status);
    if (status === 2) {
      if (this.selectedRows.length <= 0) {
        this.service.msgSrv.error('未选择货源单！');
        return;
      }
      let list: any[] = [];
      this.selectedRows.forEach(item => {
        list.push(item.id);
      });
      this.auditID = list;
      this.auditMany = true;
    } else {
      this.auditID = value.id;
      this.auditMany = false;
    }
    this.isVisible = true;
  }
  /**
   * 审核关闭弹窗
   */
  handleCancel(type: any) {
    this.isVisible = false;
  }
  /**
   * 审核通过按钮
   */
  handleOK(value: any) {
    if (this.auditMany === false) {
      const params: any = {
        id: this.auditID,
        remarks: this.sfFre.value.remarks
      };
      if (value == 1) {
        params.auditStatus = 2;
      } else {
        params.auditStatus = 3;
      }
      console.log('999');
      console.log(params);
      this.service.request(this.service.$api_goodsResourceAudit, params).subscribe(res => {
        if (res === true) {
          this.service.msgSrv.success('审核成功！');
          this.isVisible = false;
          this.st?.reload();
          this.getGoodsSourceStatistical();
        }
      });
    } else {
      const params: any = {
        ids: this.auditID,
        remarks: this.sfFre.value.remarks
      };
      if (value == 1) {
        params.auditStatus = 2;
      } else {
        params.auditStatus = 3;
      }
      console.log(params);
      this.service.request(this.service.$api_batchGoodsResourceAudit, params).subscribe(res => {
        if (res === true) {
          this.service.msgSrv.success('审核成功！');
          this.isVisible = false;
          this.st?.reload();
          this.getGoodsSourceStatistical();
        }
      });
    }
  }
  /**
   * 跳转修改货源
   */
  amend(item: any) {
    console.log(item);
    this.router.navigate(['/supply-management/vehicle-amend', item.id], {
      queryParams: {
        sta: 1
      }
    });
  }
  nextOrder(item: any) {
    this.router.navigate(['/supply-management/vehicle-amend', item.id], {
      queryParams: {
        sta: 2
      }
    });
  }
  /**
   * 代发货源
   */
  releaseGoods() {
    this.router.navigate(['/supply-management/vehicle-release']);
  }
  /**
   * 取消货源
   */
  cancleGoodsSource(record: any) {
    this.modal.confirm({
      nzTitle: '<b>确定取消货源吗?</b>',
      nzContent: `<b>取消后不可恢复，谨慎操作</b>`,
      nzOnOk: () =>
        this.service.request(this.service.$api_cancle_goods_source, { id: record.id }).subscribe(res => {
          if (res === true) {
            this.service.msgSrv.success('操作成功！');
            this.st?.reload();
            this.getGoodsSourceStatistical();
          }
        })
    });
  }
  // 获取货源状态统计
  getGoodsSourceStatistical() {
    this.tabs = {
      totalQuantity: 0,
      cancelQuantity: 0,
      receivedQuantity: 0,
      stayQuantity: 0
    };
    const params: any = Object.assign({}, this.reqParams || {});
    delete params.resourceStatus;
    this.service.request(this.service.$api_get_goods_resource_statistical, { resourceType: 1, ...params }).subscribe(res => {
      if (res) {
        console.log(res);
        this.tabs = res;
      }
    });
  }

  private initSF(): SFSchema {
    return {
      properties: {
        _$expand: { type: 'boolean', ui: { hidden: true } },
        resourceCode: {
          type: 'string',
          title: '货源编号',
          ui: { placeholder: '请输入' }
        },
        loadingPlace: {
          type: 'string',
          title: '装货地',
          ui: {
            placeholder: '请输入'
          }
        },
        dischargePlace: {
          type: 'string',
          title: '卸货地',
          ui: { placeholder: '请输入' }
        },
        shipperAppUserId: {
          type: 'string',
          title: '货主',
          ui: {
            widget: 'select',
            serverSearch: true,
            searchDebounceTime: 300,
            searchLoadingText: '搜索中...',
            visibleIf: {
              _$expand: (value: boolean) => value
            },
            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',
        //     visibleIf: {
        //       _$expand: (value: boolean) => value
        //     },
        //     allowClear: true,
        //     containsAllLabel: true,
        //     asyncData: () => this.shipperSrv.getEnterpriseProject(this.sf.value?.shipperAppUserId)
        //   } as SFSelectWidgetSchema
        // },
        enterpriseProjectId: {
          type: 'string',
          title: '所属项目',
          ui: {
            widget: 'select',
            placeholder: '请先选择货主',
            visibleIf: {
              _$expand: (value: boolean) => value
            }
          } as SFSelectWidgetSchema
        },
        serviceType: {
          title: '服务类型',
          type: 'string',
          ui: {
            widget: 'dict-select',
            containsAllLabel: true,
            params: { dictKey: 'service:type' },
            visibleIf: {
              _$expand: (value: boolean) => value
            },
            allowClear: true
          } as SFSelectWidgetSchema
        },
        auditStatus: {
          title: '审核状态',
          type: 'string',
          ui: {
            widget: 'dict-select',
            allowClear: true,
            containsAllLabel: true,
            params: { dictKey: 'goodresource:audit:status' },
            visibleIf: {
              _$expand: (value: boolean) => value
            }
          } as SFSelectWidgetSchema
        },
        enterpriseInfoId: {
          type: 'string',
          title: '网络货运人',
          ui: {
            widget: 'select',
            placeholder: '请选择',
            asyncData: () => this.shipperSrv.getNetworkFreightForwarder(),
            visibleIf: {
              _$expand: (value: boolean) => value
            },
            allowClear: true
          }
        }
      }
    };
  }
  // 获取城市列表
  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);
        // }
      });
  }
  /**
   * 初始化数据列表
   */
  private initST(): STColumn[] {
    return [
      { title: '', type: 'checkbox', fixed: 'left', width: '50px', className: 'text-center' },
      {
        title: '货源编号',
        width: '180px',
        fixed: 'left',
        className: 'text-left',
        render: 'resourceCode'
      },
      { title: '录单员', render: 'createUserName', width: '200px', className: 'text-left' },
      {
        title: '货主',
        index: 'shipperAppUserName',
        width: '180px',
        className: 'text-left'
      },

      {
        title: '项目名称',
        index: 'enterpriseProjectName',
        width: '180px',
        className: 'text-left'
      },
      {
        title: '装货地',
        index: 'loadingAddressArr',
        width: '200px',
        className: 'text-left'
      },
      {
        title: '卸货地',
        index: 'unloadingAddressArr',
        width: '200px',
        className: 'text-left'
      },
      {
        title: '货物名称',
        index: 'goodsName',
        width: '150px',
        className: 'text-left'
      },
      {
        title: '货物数量',
        width: '200px',
        index: 'goodsNumber',
        className: 'text-left',
        format: item => item.goodsNumber.join('/')
      },
      {
        title: '用车需求',
        className: 'text-left',
        width: '180px',
        render: 'useCarDemand'
      },
      {
        title: '总费用',
        className: 'text-right',
        width: '120px',
        render: 'total'
      },
      {
        title: '总运费',
        width: '150px',
        className: 'text-right',
        index: 'totalAmount',
        render: 'totalAmount'
      },
      {
        title: '附加费',
        className: 'text-right',
        width: '120px',
        index: 'surcharge',
        render: 'surcharge'
      },
      {
        title: '货源状态',
        className: 'text-left',
        index: 'resourceStatusLabel',
        width: '120px'
      },
      {
        title: '创建时间',
        width: '200px',
        index: 'createTime',
        className: 'text-left'
      },
      {
        title: '审核状态',
        className: 'text-left',
        index: 'auditStatus',
        type: 'badge',
        width: '170px',
        badge: {
          '1': { text: '待审核', color: 'warning' },
          '2': { text: '审核通过', color: 'success' },
          '3': { text: '不通过', color: 'error' },
          '4': { text: '已取消', color: 'default' }
        }
      },
      {
        title: '操作',
        fixed: 'right',
        width: '110px',
        className: 'text-center block-td',
        buttons: [
          {
            text: '货源审核',
            click: _record => this.audit(_record, 1),
            iif: item => item.auditStatus === '1',
            acl: { ability: ['SUPPLY-INDEX-vehicleBatchAudit'] }
          },
          {
            text: '修改货源',
            click: _record => this.amend(_record),
            iif: item => item.resourceStatus === '1' && item.insurancePayment !== 'Y',
            acl: { ability: ['SUPPLY-INDEX-vehicleModificationSupply'] }
          },
          // {
          //   text: '修改运费',
          //   click: _record => this.updateFreight(_record),
          //   iif: item => item.resourceStatus === '1' && item.serviceType === '2'
          // },
          {
            text: '取消货源',
            click: _record => this.cancleGoodsSource(_record),
            iif: item => item.resourceStatus === '1',
            acl: { ability: ['SUPPLY-INDEX-vehicleCancelSupply'] }
          },
          {
            text: '再下一单',
            click: _record => this.nextOrder(_record),
            acl: { ability: ['SUPPLY-INDEX-vehiclePlaceOrder'] }
          },
          {
            text: '重新指派',
            click: _record => this.assignedCar(_record),
            iif: item => item.resourceStatus === '1' && item.serviceType === '2',
            acl: { ability: ['SUPPLY-INDEX-vehicleReassign'] }
          },
          { type: 'divider' }
        ]
      }
    ];
  }
  // 导出
  exportFire() {
    this.service.exportStart(this.reqParams, this.service.$api_asyncExportWholeList);
  }
}
