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 { 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 } from '@angular/router';
import { OneCarOrderAppealComponent } from '../../modal/audit/appeal/appeal.component';

@Component({
  selector: 'app-order-management-compliance-audit',
  templateUrl: './compliance-audit.component.html',
  styleUrls: ['./compliance-audit.component.less']
})
export class OrderManagementComplianceAuditComponent implements OnInit {
  ui: SFUISchema = {};
  uiView: SFUISchema = {};
  schema: SFSchema = {};
  schemaView: SFSchema = {};
  changeId: any;       // 主页面查看运费变更记录id - 用于运费变更记录
  changeViewId: any;  // 查看运费变更记录id - 用于查看
  auditId: any;
  auditIdR: any;
  auditMany = false;
  isVisibleView = false;
  isVisibleEvaluate = false;
  isVisible = false;
  isVisibleRE = false;
  _$expand = false;
  @ViewChild('st') private readonly st!: STComponent;
  @ViewChild('sf', { static: false }) sf!: SFComponent;
  @ViewChild('sfView', { static: false }) sfView!: SFComponent;
  @ViewChild('stFloat') private readonly stFloat!: STComponent;
  @ViewChild('stFloatView') private readonly stFloatView!: STComponent;
  columns: STColumn[] = [];
  columnsFloat: STColumn[] = [];
  columnsFloatView: STColumn[] = [];
  ViewCause: any;  // 变更运费查看数据
  resourceStatus: any;
  tabs = {
    totalCount: 0,
    qualifiedtity: 0,
    spotQuantity: 0,
    unstayQuantity: 0
  };
  constructor(
    public service: OrderManagementService,
    private modal: NzModalService,
    public shipperservice: ShipperBaseService,
    private router: Router
  ) { }

  /**
   * 查询参数
   */
  get reqParams() {
    const a: any = {};
    if (this.resourceStatus >= 0) {
      a.complianceStatus = 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] || ''
      }
    };
  }
  get changeParams() {
    return {
      id: this.changeId
    };
  }
  get selectedRows() {
    return this.st?.list.filter(item => item.checked) || [];
  }
  get changeViewParams() {
    return {
      id: this.changeViewId
    };
  }
  search() {
    this.st?.load(1);
    this.getGoodsSourceStatistical();
  }
  getGoodsSourceStatistical() {
    this.tabs = {
      totalCount: 0,
      qualifiedtity: 0,
      spotQuantity: 0,
      unstayQuantity: 0
    };
    const params: any = Object.assign({}, this.reqParams || {});
    delete params.complianceStatus
    this.service.request(this.service.$api_get_getComplianceStatisticalStatus, params).subscribe(res => {
      if (res) {
        let totalCount = 0;
        res.forEach((element: any) => {
          if (element.complianceStatusLabel === '待抽查') {
            this.tabs.spotQuantity = element.quantity;
          } else if (element.complianceStatusLabel === '合格') {
            this.tabs.qualifiedtity = element.quantity;
          } else if (element.complianceStatusLabel === '不合格') {
            this.tabs.qualifiedtity = element.quantity;
          }
          totalCount += element.quantity;
        });
        this.tabs.totalCount = totalCount;
      }
    });
  }
  selectChange(e: number) {
    this.resourceStatus = e - 1;
    this.initST();
    setTimeout(() => {
      this.st.load();
    }, 500);
  }
  ngOnInit(): void {
    this.getGoodsSourceStatistical();
    this.initSF();
    this.initST();
    this.initSTFloat();
    this.initSTFloatView();
  }

  /**
   * 初始化查询表单
   */
  initSF() {
    this.schema = {
      properties: {
        _$expand: { type: 'boolean', ui: { hidden: true } },
        billCode: {
          type: 'string',
          title: '订单号',
          ui: {
          }
        },
        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: '请先选择货主',
            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
        },
        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
        },
        createTime: {
          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: 'billCode'
      },
      {
        title: '费用明细',
        width: '250px',
        className: 'text-right',
        render: 'mybidDetailInfo'
      },
      { title: '网络货运人', index: 'enterpriseInfoName', width: '220px', className: 'text-left' },
      { title: '货主', index: 'shipperAppUserName', width: '220px', className: 'text-left' },
      { title: '所属项目', index: 'enterpriseProjectName', width: '220px', className: 'text-left' },
      { title: '关联运单号', index: 'wayBillCode', width: '220px', className: 'text-left' },
      { title: '货源编号', index: 'resourceCode', width: '180px', className: 'text-left' },
      { title: '服务类型', index: 'serviceTypeLabel', 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: '承运司机',
        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: '审核人',
        width: '180px',
        className: 'text-left',
        index: 'complianceName'
      },
      {
        title: '审核时间',
        width: '180px',
        className: 'text-left',
        index: 'complianceTime'
      },
      {
        title: '状态',
        width: '180px',
        className: 'text-left',
        index: 'complianceStatusLabel'
      },
      {
        title: '操作',
        fixed: 'right',
        width: '140px',
        className: 'text-center block-td',
        buttons: [
          {
            text: '查看申诉记录',
            click: _record => this.appeal(_record),
            // iif: item => item.billStatus == '5'
          },
          {
            text: '运费变更记录',
            click: _record => this.OpenPrice(_record),
            // iif: item => item.billStatus == '4',
            acl: { ability: ['ORDER-COMPLIANCE-AUDIT-listChangeApply'] },
          },
          {
            text: '合规抽查',
            click: _record => this.audit(_record),
            iif: item => item.complianceStatus == '0',
            acl: { ability: ['ORDER-COMPLIANCE-AUDIT-updateBillByCompliance'] },
          },
        ]
      }
    ];
  }
  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: 'amountAfterChange',
        render: 'amountAfterChange'
      },
      {
        title: '变更值',
        index: 'amountchangeValue',
        render: 'amountchangeValue',
        width: '120px',
        className: 'text-center'
      },
      {
        title: '变更后',
        index: 'amountBeforeChange',
        render: 'amountBeforeChange',
        width: '120px',
        className: 'text-center'
      }
    ];
  }
  /**
   * 查询字段个数
   */
  get queryFieldCount(): number {
    return Object.keys(this.schema?.properties || {}).length;
  }
  // 申诉记录
  appeal(item: any) {
    // const modalRef = this.modal.create({
    //   nzTitle: '申诉',
    //   nzContent: OneCarOrderAppealComponent,
    //   nzComponentParams: {
    //     i: item
    //   },
    //   nzFooter: null
    // });
    // modalRef.afterClose.subscribe((res) => {
    //   if(res){
    //     this.resetSF;
    //     this.st.load();
    //   }
    // });
    this.router.navigate(['/order-management/risk-detail', item.id]);
  }
  /**
* 浮动费用查看
*/
  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
  }
  revoke(item: any) {
    this.modal.confirm({
      nzTitle: '是否确定立即撤销费用变更！</i>',
      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()
          }
        })
    });
  }
  /**
   * 伸缩查询条件
   */
  expandToggle(): void {
    this._$expand = !this._$expand;
    this.sf?.setValue('/_$expand', this._$expand);
  }
  tabChange(item: any) { }
  /**
   * 重置表单
   */
  resetSF(): void {
    this.sf.reset();
    this._$expand = false;
  }

  /**
   * 导入货源
   */
  importGoodsSource() { }
  OpenPrice(item: any) {
    this.changeId = item.id;
    this.isVisible = true;
  }

  initSTAudit(value: number) {
    if (value == 1) {
      this.schemaView = {
        properties: {
          billCode: {
            title: '订单号',
            type: 'string',
            default: this.auditId,
            ui: {
              widget: 'text'
            }
          },
          complianceRemark: {
            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'
            }
          },
          complianceRemark: {
            title: '备注',
            type: 'string',
            maxLength: 50,
            ui: {
              placeholder: '合格可以不用填写原因 ，不合格必须说明原因',
              widget: 'textarea',
              autosize: { minRows: 3, maxRows: 6 }
            }
          }
        }
      };
    }

    this.uiView = { '*': { spanLabelFixed: 110, grid: { span: 24 } } };
  }
  /*
 * 审核关闭弹窗
 */
  handleCancel(value?: string) {
    if (value === '0') {
      this.isVisible = false;
    } else if (value === '1') {
      this.isVisibleRE = false;
    } else if (value === '2') {
      this.isVisibleView = false;
    }
  }
  /**
* 审核通过按钮
*/
  handleOK() {
    let idList: any[] = [];
    if (this.selectedRows.length > 0) {
      this.selectedRows.forEach(item => {
        idList.push(item.id);
      });
    } else {
      idList.push(this?.auditIdR)
    }
    const parms = {
      ids: idList,
      complianceRemark: this.sfView.value.complianceRemark,
      complianceStatus: 1,
    };
    this.service.request(this.service.$api_get_updateBillByCompliance, parms).subscribe(res => {
      if (res) {
        this.service.msgSrv.success('提交成功！');
        this.isVisibleRE = false;
        this.st?.load(1);
        this.getGoodsSourceStatistical()
      }
    });
  }
  /**
 * 审核拒绝按钮
 */
  reject() {
    if (!this.sfView.value.complianceRemark) {
      this.service.msgSrv.error('备注不能为空！');
      return;
    }
    let idList: any[] = [];
    if (this.selectedRows.length > 0) {
      this.selectedRows.forEach(item => {
        idList.push(item.id);
      });
    } else {
      idList.push(this.sfView.value.billCode)
    }
    const parms = {
      ids: idList,
      complianceRemark: this.sfView.value.complianceRemark,
      complianceStatus: 2,
    };
    this.service.request(this.service.$api_get_updateBillByCompliance, parms).subscribe(res => {
      if (res) {
        this.service.msgSrv.success('提交成功！');
        this.isVisibleRE = false;
        this.st?.load(1);
        this.getGoodsSourceStatistical()
      }
    });
  }
  /**
*合规抽查
*/
  audit(item?: any) {
    if (item) {
      this.isVisibleRE = true;
      this.auditId = item.billCode;
      this.auditIdR = item.id;
      this.initSTAudit(1);
    } else {
      if (this.selectedRows.length <= 0) {
        this.service.msgSrv.error('请选择订单！')
        return;
      } else {
        this.isVisibleRE = true;
        this.initSTAudit(2);
      }
    }
  }
    // 导出
    exprot() {
      this.service.exportStart({ ...this.reqParams, pageSize: -1 }, this.service.$api_get_asyncExportSpotCheckList);
    }
}
