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 { NzModalService } from 'ng-zorro-antd/modal';
import { map } from 'rxjs/operators';
import { of } from 'rxjs';
import { ShipperBaseService } from '@shared';
import { Router } from '@angular/router';
import { InsuranceManagementService } from '../../services/insurance-management.service';
import { VehicleImgViewComponent } from 'src/app/routes/vehicle/components/list/img-view/img-view.component';
import { ImageViewComponent } from 'src/app/shared/components/imagelist';

@Component({
  selector: 'app-insurance-management-list',
  templateUrl: './list.component.html',
  styleUrls: ['./list.component.less']
})
export class insuranceManagementListComponent implements OnInit {
  ui: SFUISchema = {};
  uiView: SFUISchema = {};
  schema: SFSchema = {};
  schemaView: SFSchema = {};
  auditMany = false;
  isVisibleView = false;
  isVisibleEvaluate = false;
  isVisible = false;
  _$expand = false;
  @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;
  datass: any = [
    {
      one: '1',
      two: '1',
      three: '1',
      id: 1
    },
    {
      one: '2',
      two: '2',
      three: '2',
      id: 2
    }
  ];
  tabs = {
    totalCount: 0,
    receivedQuantity: 0,
    stayQuantity: 0,
    GoingQuantity: 0,
    cancelQuantity: 0
  };
  constructor(
    public service: InsuranceManagementService,
    private modal: NzModalService,
    public shipperservice: ShipperBaseService,
    private router: Router,
    private modale: ModalHelper,
  ) { }

  /**
   * 查询参数
   */
  get reqParams() {
    const a: any = {};
    if (this.resourceStatus) {
      a.insureStatus = 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] || ''
      },
      recordTime: {
        start: this.sf?.value?.recordTime?.[0] || '',
        end: this.sf?.value?.recordTime?.[1] || ''
      },
      insureTime: {
        start: this.sf?.value?.insureTime?.[0] || '',
        end: this.sf?.value?.insureTime?.[1] || ''
      },
    };
  }
  get selectedRows() {
    return this.st?.list.filter(item => item.checked) || [];
  }
  search() {
    this.st?.load(1);
    this.getGoodsSourceStatistical();
  }
  getGoodsSourceStatistical() {
    this.tabs = {
      totalCount: 0,
      receivedQuantity: 0,
      stayQuantity: 0,
      GoingQuantity: 0,
      cancelQuantity: 0
    };
    const params: any = Object.assign({}, this.reqParams || {});
    delete params.insureStatus;
    this.service.request(this.service.$api_listStatisticalStatus, params).subscribe((res: any) => {
      if (res) {
        let totalCount = 0;
        res.forEach((element: any) => {
          if (element.insureStatusLabel === '待投保') {
            this.tabs.receivedQuantity = element.quantity;
          } else if (element.insureStatusLabel === '已投保') {
            this.tabs.stayQuantity = element.quantity;
          } else if (element.insureStatusLabel === '投保失败') {
            this.tabs.GoingQuantity = element.quantity;
          } else if (element.insureStatusLabel === '已取消') {
            this.tabs.cancelQuantity = 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();
  }

  /**
   * 初始化查询表单
   */
  initSF() {
    this.schema = {
      properties: {
        _$expand: { type: 'boolean', ui: { hidden: true } },
        insureCode: {
          type: 'string',
          title: '投保编号'
        },
        billCode: {
          type: 'string',
          title: '订单号'
        },
        resourceCode: {
          type: 'string',
          title: '货源编号'
        },
        policyNo: {
          type: 'string',
          title: '保单号',
          ui: {
            visibleIf: {
              _$expand: (value: boolean) => value
            },
          }
        },
        insureType: {
          title: '类型',
          type: 'string',
          ui: {
            widget: 'dict-select',
            params: { dictKey: 'insure:type' },
            containsAllLabel: true,
            visibleIf: {
              _$expand: (value: boolean) => value
            }
          } as SFSelectWidgetSchema
        },
        startAddress: {
          type: 'string',
          title: '始发地',
          ui: {
            visibleIf: {
              _$expand: (value: boolean) => value
            }
          }
        },
        endAddress: {
          type: 'string',
          title: '目的地',
          ui: {
            visibleIf: {
              _$expand: (value: boolean) => value
            }
          }
        },
        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
        },

        driverName: {
          title: '承运司机',
          type: 'string',
          ui: {
            visibleIf: {
              _$expand: (value: boolean) => value
            }
          }
        },
        carNo: {
          title: '车牌号',
          type: 'string',
          ui: {
            visibleIf: {
              _$expand: (value: boolean) => value
            }
          }
        },
        insureStatus: {
          title: '投保状态',
          type: 'string',
          ui: {
            widget: 'dict-select',
            params: { dictKey: 'insure:status' },
            containsAllLabel: true,
            visibleIf: {
              _$expand: (value: boolean) => value
            }
          } as SFSelectWidgetSchema
        },
        insureRefundStatus: {
          title: '退款状态',
          type: 'string',
          ui: {
            widget: 'dict-select',
            params: { dictKey: 'insure:refund:status' },
            containsAllLable: true,
            visibleIf: {
              _$expand: (value: boolean) => value
            }
          } as SFSelectWidgetSchema
        },
        enterpriseInfoId: {
          type: 'string',
          title: '网络货运人',
          ui: {
            widget: 'select',
            placeholder: '请选择',
            allowClear: true,
            visibleIf: {
              _$expand: (value: boolean) => value
            },
            asyncData: () => this.shipperservice.getNetworkFreightForwarder()
          }
        },
        insureTime: {
          title: '投保时间',
          type: 'string',
          ui: {
            widget: 'date',
            mode: 'range',
            format: 'yyyy-MM-dd',
            allowClear: true,
            visibleIf: {
              _$expand: (value: boolean) => value
            }
          } as SFDateWidgetSchema
        },
        createTime: {
          title: '创建时间',
          type: 'string',
          ui: {
            widget: 'date',
            mode: 'range',
            format: 'yyyy-MM-dd',
            allowClear: true,
            visibleIf: {
              _$expand: (value: boolean) => value
            }
          } as SFDateWidgetSchema
        },
        recordTime: {
          title: '录单时间',
          type: 'string',
          ui: {
            widget: 'date',
            mode: 'range',
            format: 'yyyy-MM-dd',
            allowClear: true,
            visibleIf: {
              _$expand: (value: boolean) => value
            }
          } as SFDateWidgetSchema
        },

      },
      type: 'object'
    };
    this.ui = { '*': { spanLabelFixed: 110, grid: { span: 8, 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: 'insureCode'
      },
      {
        title: '保单号',
        width: '250px',
        className: 'text-right',
        index: 'policyNo'
      },
      { title: '类型', index: 'insureTypeLabel', width: '220px', className: 'text-left' },
      { title: '始发地', index: 'startAddress', width: '220px', className: 'text-left' },
      { title: '目的地', index: 'endAddress', width: '220px', className: 'text-left' },
      { title: '距离', render: 'distance', width: '180px', className: 'text-left' },
      { title: '保额（元）', render: 'insureAmount', width: '180px', className: 'text-right' },
      { title: '保费（元）', render: 'premium', width: '180px', className: 'text-right' },
      // {
      //   title: '实际保费（元）',
      //   className: 'text-right',
      //   width: '180px',
      //   render: 'practicalPremium'
      // },
      {
        title: '货物信息',
        className: 'text-left',
        width: '250px',
        render: 'goodsName'
      },
      {
        title: '承运司机',
        className: 'text-right',
        width: '250px',
        render: 'driverName'
      },
      {
        title: '关联订单号',
        className: 'text-right',
        render: 'goodsNumber',
        width: '180px'
      },
      {
        title: '货源编号',
        className: 'text-right',
        render: 'resourceCode',
        width: '150px'
      },
      {
        title: '网络货运人',
        className: 'text-left',
        width: '250px',
        index: 'enterpriseInfoName'
      },
      {
        title: '货主',
        className: 'text-left',
        width: '250px',
        index: 'shipperAppUserName'
      },
      {
        title: '所属项目',
        width: '250px',
        className: 'text-left',
        index: 'enterpriseProjectName'
      },
      {
        title: '投保时间',
        width: '180px',
        className: 'text-left',
        index: 'insureTime'
      },
      {
        title: '生效时间',
        width: '180px',
        className: 'text-left',
        index: 'effectTime'
      },
      {
        title: '录单时间',
        width: '180px',
        className: 'text-left',
        index: 'recordTime'
      },
      {
        title: '创建时间',
        width: '180px',
        className: 'text-left',
        index: 'createTime'
      },
      {
        title: '失败原因',
        width: '180px',
        className: 'text-left',
        render: 'processMessage',
        // processResult=2
      },
      {
        title: '退款状态',
        width: '180px',
        className: 'text-left',
        index: 'insureRefundStatusLabel',
        // processResult=2
      },
      {
        title: '操作',
        fixed: 'right',
        width: '110px',
        className: 'text-center',
        buttons: [
          {
            text: '查看保单',
            click: _record => this.showImg(_record),
            iif: item => item.insureStatus == '2' 
            // acl: { ability: ['VEHICLE-LIST-view'] },
            // iif: item =>
            //   item.billStatus == '4' || item.billStatus == '5' || item.billStatus == '2' || item.billStatus == '3' || item.billStatus == '1'
          },
          {
            text: '退保费',
            click: _record => this.retreatPrice(_record),
            iif: item => item.insureStatus == '2' 
            // acl: { ability: ['VEHICLE-LIST-view'] },
          }
        ]
      }
    ];
  }
  showImg(_record: any) {
    // var newUrl=_record.policyUrl.replace('http','https')
    // console.log(newUrl);
    
    // window.open(newUrl,'_self');
    window.open(`${_record.newPolicyUrl}`);
    // this.service.downloadFile(`${_record.newPolicyUrl}`)

    
    // const params = {
    //   imgList: [_record.policyUrl],
    //   index: 0
    // };
    // this.modal.create({ nzContent: ImageViewComponent, nzComponentParams: { params } });
  }
  /**
   * 查询字段个数
   */
  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) { }
  /**
   * 重置表单
   */
  resetSF(): void {
    this.sf.reset();
    this._$expand = false;
  }

  // 退保费
  retreatPrice(value: any) {
    this.modal.warning({
      nzTitle: '确认退还保费吗？',
      nzClosable: true,
      nzContent: '退还后不可撤销，请谨慎操作！',
      nzCancelText: '取消',
      nzOnOk: () => {
        this.service.request(this.service.$api_get_addINPBillRefundApplication, {id: value.id}).subscribe(res => {
          if (res) {
            this.service.msgSrv.success('删除菜单成功');
          }
        });
      }
    });
  }
  // 再次投保
  retreatNext(value: any) {
    this.modal.warning({
      nzTitle: '确认再次投保吗？',
      nzClosable: true,
      nzCancelText: '取消',
      nzOnOk: () => {
        this.service.request(this.service.$api_del_many, [value.id]).subscribe(res => {
          if (res) {
            this.service.msgSrv.success('删除菜单成功');
          }
        });
      }
    });
  }
  // 保险配置
  changeOrder() {
    this.router.navigate(['/insurance-management/list-set']);
  }
  exprot() {
    this.service.downloadFile(this.service.$api_get_asyncExport, { ...this.reqParams, pageSize: -1 });
  }
}
