import { Router } from '@angular/router';
import { Component, OnInit, ViewChild } from '@angular/core';
import { STColumn, STComponent } from '@delon/abc/st';
import { SFComponent, SFDateWidgetSchema, SFSchema, SFSchemaEnum, SFSelectWidgetSchema, SFUISchema } from '@delon/form';
import { ModalHelper, _HttpClient } from '@delon/theme';
import { ShipperBaseService } from '@shared';
import { NzModalService } from 'ng-zorro-antd/modal';
import { of } from 'rxjs';
import { map } from 'rxjs/operators';
import { SupplyManagementService } from '../../services/order-management.service';

@Component({
  selector: 'app-supply-management-risk',
  templateUrl: './risk.component.html',
  styleUrls: ['./risk.component.less']
})
export class OrderManagementRiskComponent implements OnInit {
  url = `/user?_allow_anonymous=true`;
  ui: SFUISchema = {};
  uiView: SFUISchema = {};
  schema: SFSchema = {};
  schemaView: SFSchema = {};
  auditMany = false;
  auditId : any;
  isVisibleRE = false;
  _$expand = false;
  @ViewChild('st') private readonly st!: STComponent;
  @ViewChild('sf', { static: false }) sf!: SFComponent;
  @ViewChild('sfView', { static: false }) sfView!: SFComponent;
  columns: STColumn[] = [];
  datass: any = [
    {
    one: '1',
    two: '1',
    three: '1',
    id: 1
   },
    {
    one: '2',
    two: '2',
    three: '2',
    id: 2
   },
];
  tabs = [  {
    name: '全部',
    type: 5,
    count: 0,
  },
  {
    name: '待申诉',
    type: 5,
    count: 0,
  },
  {
    name: '申诉中',
    type: 5,
    count: 0,
  },
  {
    name: '申诉成功',
    type: 5,
    count: 0,
  },
  {
    name: '申诉失败',
    type: 5,
    count: 0,
  },
  ];
  constructor(public service: SupplyManagementService, public service2: ShipperBaseService, private modal: NzModalService, public router: Router) { }

  /**
 * 查询参数
 */
  get reqParams() {
    return {
      ...this.sf?.value,
    };
  }
  get selectedRows() {
    return this.st?.list.filter((item) => item.checked) || [];
  }
  ngOnInit(): void {
    this.initSF();
    this.initST();
  }



  /**
 * 初始化查询表单
 */
  initSF() {
    this.schema = {
      properties: {
        _$expand: { type: 'boolean', ui: { hidden: true } },
        billCode: {
          type: 'string',
          title: '订单号',
        },
        resourceCode: {
          type: 'string',
          title: '货源编号'
        },
        externalResourceCode: {
          type: 'string',
          title: '外部订单号'
        },
        loadingPlace: {
          type: 'string',
          title: '装货地',
          ui: {
            visibleIf: {
              _$expand: (value: boolean) => value,
            },
          }
        },
        dischargePlace: {
          type: 'string',
          title: '卸货地',
          ui: {
            visibleIf: {
              _$expand: (value: boolean) => value,
            },
          }
        },
        // driverName: {
        //   type: 'string',
        //   title: '承运司机',
        //   ui: {
        //     visibleIf: {
        //       _$expand: (value: boolean) => value,
        //     },
        //   }
        // },
        driverId: {
          title: '承运司机',
          type: 'string',
          ui: {
            widget: 'select',
            serverSearch: true,
            searchDebounceTime: 300,
            searchLoadingText: '搜索中...',
            onSearch: (q: any) => {
              if (!!q) {
                return this.service
                  .request(this.service.$api_get_getDriverInfo, { keyword: q,
                  model: 1, type: 1 })
                  .pipe(map((res) => (res as any[]).map((i) => ({ label: i.name, value: i.id } as SFSchemaEnum))))
                  .toPromise();
              } else {
                return of([]);
              }
            },
            visibleIf: {
              expand: (value: boolean) => value,
            },
          } as SFSelectWidgetSchema,
        },
        no9: {
          type: 'string',
          title: '车牌号',
          ui: {
            visibleIf: {
              _$expand: (value: boolean) => value,
            },
          }
        },
        no10: {
          type: 'string',
          title: '收款人',
          ui: {
            visibleIf: {
              _$expand: (value: boolean) => value,
            },
          }
        },
        wayBillType: {
          title: '运单类型',
          type: 'string',
          ui: {
            widget: 'dict-select',
            params: { dictKey: 'goodresourceType' },
            visibleIf: {
              _$expand: (value: boolean) => value,
            },
          } as SFSelectWidgetSchema,
        },
        shipperId: {
          title: '托运人',
          type: 'string',
          ui: {
            widget: 'dict-select',
            params: { dictKey: 'BulkFreightUnitPriceType' },
            visibleIf: {
              _$expand: (value: boolean) => value,
            },
          } as SFSelectWidgetSchema,
        },
        enterpriseInfoName: {
          type: 'string',
          title: '网络货运人',
          ui: {
            widget: 'select',
            placeholder: '请选择',
            visibleIf: {
              _$expand: (value: boolean) => value,
            },
            allowClear: true,
            asyncData: () => this.service2.getNetworkFreightForwarder(),
          },
        },
        createTime: {
          title: '创建时间',
          type: 'string',
          ui: {
            widget: 'date',
            mode: 'range',
            format: 'yyyy-MM-dd',
            visibleIf: {
              _$expand: (value: boolean) => value,
            },
          } as SFDateWidgetSchema,
        },
      },
      type: 'object',
    };
    this.ui = { '*': { spanLabelFixed: 110, grid: { span: 8, gutter: 4 } } };
  }

  /**
   * 初始化数据列表
   */
  initST() {
    this.columns = [
      { title: '', type: 'checkbox', width: '50px', className: 'text-center' },
      {
        title: '申诉状态',
        width: '100px',
        className: 'text-center',
        index: 'representationsStatusLabel'
      },
      {
        title: '订单号',
        width: '100px',
        className: 'text-center',
        render: 'billCode'
      },
      {
        title: '异常信息',
        width: '100px',
        className: 'text-center',
        index: 'abnormalCause',
      },
      { title: '托运人', index: 'shipperName', width: '120px', className: 'text-center' },
      { title: '网络货运人', index: 'enterpriseInfoName', width: '120px', className: 'text-center' },
      {
        title: '运费明细',
        className: 'text-center',
        width: '120px',
        render: 'billExpenseDetailVOList',
      },
      {
        title: '服务类型',
        className: 'text-center',
        width: '120px',
        index: 'serviceTypeLabel',
      }, {
        title: '装货地',
        className: 'text-center',
        width: '180px',
        index: 'loadingPlace',

      },
      {
        title: '卸货地',
        className: 'text-center',
        width: '180px',
        index: 'dischargePlace',

      },
      {
        title: '货物信息',
        className: 'text-center',
        width: '180px',
        render: 'goodsInfoVOList',

      },
      {
        title: '承运司机',
        className: 'text-center',
        width: '120px',
        render: 'driverName'
      },
      {
        title: '收款人',
        className: 'text-center',
        width: '120px',
        render: 'payeeName'
      },
      {
        title: '运输信息',
        className: 'text-center',
        width: '120px',
        render: 'timeer'
      },
      {
        title: '操作',
        fixed: 'right',
        width: '200px',
        className: 'text-left',
        buttons: [
          {
            text: '审核',
            click: (_record) => this.audit(_record),
          },
          {
            text: '详情',
            click: (_record) => this.viewEvaluate(_record),
          },
        ],
      },
    ];
  }
  initSTAudit(value: number) {
    if(value == 1) {
      this.schemaView = {
        properties: {
          billCode: {
            title: '订单号',
            type: 'string',
            default: this.auditId,
            ui: {
              widget: 'text',
            },
          },
          representationsCause: {
            title: '备注',
            type: 'string',
            maxLength: 50,
            ui: {
              placeholder: '通过可以不用填写原因 ，拒绝必须说明原因',
              widget: 'textarea',
              autosize: { minRows: 3, maxRows: 6 }
            },
          },
        },
      };
    } else {
      this.schemaView = {
        properties: {
          billCode: {
            title: '',
            type: 'string',
            default: `已选${this.selectedRows?.length}条订单`,
            ui: {
              widget: 'text',
            },
          },
          representationsCause: {
            title: '备注',
            type: 'string',
            maxLength: 50,
            ui: {
              placeholder: '通过可以不用填写原因 ，拒绝必须说明原因',
              widget: 'textarea',
              autosize: { minRows: 3, maxRows: 6 }
            },
          },
        },
      };
    }
  
    this.uiView = { '*': { spanLabelFixed: 110, grid: { span: 24 } } };
  }
  /**
   * 查询字段个数
   */
  get queryFieldCount(): number {
    return Object.keys(this.schema?.properties || {}).length;
  }
  /**
  * 伸缩查询条件
  */
  expandToggle(): void {
    this._$expand = !this._$expand;
    this.sf?.setValue('/_$expand', this._$expand);
  }
  tabChange(item: any) {
    console.log(item)
  }
  /**
   * 重置表单
   */
  resetSF(): void {
    this.sf.reset();
    this._$expand = false;
  }



  // 获取录单员 
  getCatalogueMember() {
    const params = {
    };
    return this.service.request(this.service.$api_get_catalogue_member, params, 'GET').pipe(
      map((res) => {
        if (res) {
          console.log(res)
        }
      }),
    );
  }

  selectChange(e: number) {
    console.log(e);
  }
  /**
   * 导入货源
   */
  importGoodsSource() {

  }

 /*
  * 审核关闭弹窗
  */
  handleCancel() {
    this.isVisibleRE = false
  }
    /**
  * 审核通过按钮
  */
  handleOK() {
    console.log(this.sfView.value)
    const parms = {
      id: this.sfView.value.billCode,
      representationsCause: this.sfView.value.representationsCause,
    }
    this.service.request(this.service.$api_get_catalogue_member, parms).subscribe((res) => {
      console.log(res)
      if(res) {
        this.service.msgSrv.success('审核通过！')
       this.isVisibleRE = false
      } else{
        this.service.msgSrv.error(res.msg)

      }
    })
  }
    /**
  * 审核拒绝按钮
  */
  reject() {
    console.log(this.sfView.value)
    const parms = {
      id: this.sfView.value.billCode,
      representationsCause: this.sfView.value.representationsCause,
    }
    this.service.request(this.service.$api_get_catalogue_member, parms).subscribe((res) => {
      console.log(res)
      if(res) {
        this.service.msgSrv.success('审核通过！')
       this.isVisibleRE = false
      } else{
        this.service.msgSrv.error(res.msg)

      }
    })
  }
   /**
  *审核
  */
  audit(item?: any) {
    this.isVisibleRE = true
    if(item) {
    this.auditId = item.id;
    this.initSTAudit(1);
    } else {
    this.initSTAudit(2);
    }
    console.log(item)
  }
   /**
  *查看详情
  */
  viewEvaluate(item: any) {
    console.log(item)
    this.router.navigate(['/order-management/risk-detail', item.id])
  }
}
