import { Component, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { apiConf } from '@conf/api.conf';
import { STColumn, STComponent } from '@delon/abc/st';
import { SFComponent, SFDateWidgetSchema, SFSchema, SFUISchema } from '@delon/form';
import { ModalHelper, _HttpClient } from '@delon/theme';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { NzUploadFile } from 'ng-zorro-antd/upload';
import { ImageViewComponent } from 'src/app/shared/components/imagelist';
import { VehicleService } from '../../../services/vehicle.service';
// import { VehicleComponentsListEditComponent } from '../edit/edit.component';
// import { VehicleImgViewComponent } from '../img-view/img-view.component';
import { EADateUtil } from '@shared';
import { VehicleImgViewComponent } from '../../list/img-view/img-view.component';
import { VehicleComponentsListEditComponent } from '../../list/edit/edit.component';
import { NzImageService } from 'ng-zorro-antd/image';
import { fromEvent, Subscription } from 'rxjs';

@Component({
  selector: 'app-Vehicle-components-Audit-detail',
  templateUrl: './detail.component.html',
  styleUrls: ['./detail.component.less']
})
export class VehicleComponentsAuditDetailComponent implements OnInit, OnDestroy  {
  @ViewChild('st', { static: false }) st!: STComponent;
  @ViewChild('redectModal', { static: false }) redectModal!: any;
  columns!: STColumn[];
  detailData: any = this.initData();
  tempalateData: any;
  contenCarNoColor: any;
  contencarModel: any;
  contenCarLength: any;
  isEdit = false;
  approvalOpinion = '';
  uploadURl = apiConf.waterFileUpload;
  disabledUpload = false;

  
  scrollTop = 0;
  subscribeScoll!: Subscription;
  constructor(
    public service: VehicleService,
    private route: ActivatedRoute,
    private nzModalService: NzModalService,
    private modal: ModalHelper,
    private nzImageService: NzImageService
  ) {}
  ngOnDestroy(): void {
    this.subscribeScoll.unsubscribe();
  }

  ngOnInit() {
    this.getSelectList();
    this.getDetailList();
    this.initST();
    this.subscribeScoll = fromEvent(window, 'scroll').subscribe(event => {
      this.scrollTop = document.documentElement.scrollTop;
    });
  }

  initST() {
    this.columns = [
      { title: '司机姓名', index: 'name', width: 150, className: 'text-center' },
      { title: '司机手机号', index: 'mobile',  width: 200,className: 'text-center' },
      { title: '身份证号', index: 'idCardNo', width: 200, className: 'text-center' },
      { title: '挂靠协议', render: 'auditStatusEnum', width: 100,className: 'text-center' },
      {
        title: '车主申明/挂靠协议',
        fixed: 'right',
        width: '200px',
        className: 'text-left',
        buttons: [
          {
            text: '查看协议',
            click: _record => this.viewEvaluate(_record),
            iif: item => item.auditStatusEnum == 10 || item.auditStatusEnum == 20
          },
          {
            text: '上传协议',
            click: _record => this.updateEvaluate(_record),
          }
        ]
      }
    ];
  }

  getDetailList() {
    const params = {
      id: this.route.snapshot?.params?.id
    };
    this.service.request(`${this.service.$api_get_operate_getaudit}`, params).subscribe(res => {
      this.detailData = res;
      this.tempalateData = res;
    });
  }

  approveDriver() {
    this.nzModalService.confirm({
      nzTitle: '审核通过',
      nzContent: `<p>车牌号：${this.detailData?.carNo}</p><p>是否确认通过审核`,
      nzOnOk: () => {
        this.adjuctUser(
          {
            approvalStatus: 20,
            id: this.route.snapshot?.params?.id
          },
          '审核成功'
        );
      }
    });
  }

  rejectedDriver() {
    this.approvalOpinion = '';
    this.nzModalService.create({
      nzTitle: '审核驳回',
      nzContent: this.redectModal,
      nzOnOk: () => {
        if (!this.approvalOpinion) {
          this.service.msgSrv.error('请填写备注！')
          return false;
        }
        this.adjuctUser(
          {
            id: this.route.snapshot?.params?.id,
            approvalStatus: 30,
            approvalOpinion: this.approvalOpinion
          },
          '审核驳回成功'
        );
        return;
      }
    });
  }

  reset() {
    this.detailData = { ...this.tempalateData };
    this.isEdit = false;
  }

  save() {
    this.detailData.driverLicenseRegisterTime = EADateUtil.yearToDate(this.detailData?.driverLicenseRegisterTime);

    this.detailData.driverLicenseEndTime = EADateUtil.yearToDate(this.detailData?.driverLicenseEndTime);

    this.detailData.driverLicenseGetTime = EADateUtil.yearToDate(this.detailData?.driverLicenseGetTime);

    this.detailData.roadTransportStartTime = EADateUtil.yearToDate(this.detailData?.roadTransportStartTime);

    this.detailData.roadTransportEndTime = EADateUtil.yearToDate(this.detailData?.roadTransportEndTime);
    console.log(this.detailData.roadTransportStartTime)
    if((this.detailData.roadTransportStartTime > this.detailData.roadTransportEndTime) || (this.detailData.driverLicenseRegisterTime > this.detailData.driverLicenseEndTime)) {
      this.service.msgSrv.error('发证日期起始不能大于结束日期！')
       return;
    }
    this.service.request(this.service.$api_get_update_audit, this.detailData).subscribe(res => {
      if (res) {
        this.getDetailList();
         this.isEdit = false;
        this.service.msgSrv.success('修改成功！');
      }
    });
  }

  ratify() {
    this.isEdit = true;
  }

  changeUpload({ file, fileList, type }: any, key: string) {
    if (type === 'success') {
      this.detailData[key] = file.response.data.fullFileWatermarkPath;
    }
  }

  goBack() {
    window.history.go(-1);
  }
  /**
   * 查询参数
   */
  get reqParams() {
    return { id: this.route.snapshot.queryParams.carId };
  }
  showImg(url: any) {
    const params = {
      imgList: [url],
      index: 0
    };
    this.nzImageService.preview([{ src: url }]);
    // this.nzModalService.create({ nzContent: ImageViewComponent, nzComponentParams: { params } });
  }

  deleteImg(key: string) {
    this.nzModalService.warning({
      nzTitle: '是否确认删除该图片',
      nzOnOk: () => {
        this.disabledUpload = true;
        this.detailData[key] = '';
        setTimeout(() => {
          this.disabledUpload = false;
        }, 100);
      }
    });
  }

  private adjuctUser(params: any, msg: string) {
    this.service.request(this.service.$api_get_operate_audit, { ...params }).subscribe(res => {
      if (res) {
        this.service.msgSrv.success(msg);
      }
      this.getDetailList();
    });
  }

  private initData() {
    return {
      carNo: '',
      carNoColor: '',
      carModel: '',
      carLength: '',
      archivesNo: '',
      driverLicenseSigningOrg: '',
      carDistinguishCode: '',
      carLoad: '',
      curbWeight: '',
      roadTransportNo: '',
      roadTransportLicenceNo: '',
      carOwner: '',
      isTrailer: null,
      useNature: null,
      driverLicenseRegisterTime: null,
      driverLicenseGetTime: null,
      driverLicenseEndTime: null,
      roadTransportStartTime: null,
      roadTransportEndTime: null,
      carFrontPhotoWatermark: ''
    };
  }
  // 获取录单员
  getSelectList() {
    this.Serveice('car:color');
    this.Serveice('car:model');
    this.Serveice('car:length');
  }
  Serveice(param: any) {
    let value: any;
    this.service
      .request(`${this.service.$api_get_getDictValue}`, {
        dictKey: param
      })
      .subscribe(res => {
        if (param === 'car:color') {
          this.contenCarNoColor = res;
        } else if (param === 'car:model') {
          this.contencarModel = res;
        } else if (param === 'car:length') {
          this.contenCarLength = res;
        }
      });
    return value;
  }
  viewEvaluate(item: any) {
    this.modal.createStatic(VehicleImgViewComponent, { i: item }).subscribe(i => {
      this.st.reload();
      this.getDetailList();
    });
  }
  updateEvaluate(item: any) {
    this.modal.createStatic(VehicleComponentsListEditComponent, { i: item }).subscribe(i => {
      this.st.reload();
      this.getDetailList();
    });
  }
}
