import { DatePipe } from '@angular/common';
import { Component, 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, SFTagWidgetSchema, SFTextWidgetSchema, 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 { ImageViewComponent } from 'src/app/shared/components/imagelist';
import { UsermanageService } from '../../../services/usercenter.service';

@Component({
  selector: 'app-usercenter-components-driver-detail',
  templateUrl: './detail.component.html',
  styleUrls: ['./detail.component.less'],
  providers: [DatePipe]
})
export class UserCenterComponentsDriverDetailComponent implements OnInit {
  detailData: any;
  userDetail: any;
  userIdentityDetail: any = {};
  tempalateUserIdentityDetail = { ...this.userIdentityDetail };
  driverDetail: any = {};
  tempalateDriverData = { ...this.driverDetail };
  licenseDetail: any = {};
  tempalateLicenseDetail = { ...this.licenseDetail };
  carList: any = [];

  @ViewChild('redectModal', { static: false })
  redectModal!: any;
  @ViewChild('rejectedDriverModal', { static: false })
  rejectedDriverModal!: any;
  approvalOpinion = '';

  isEditUser = false;
  isEditDriver = false;

  uploadURl = apiConf.waterFileUpload;
  disabledUpload = false;
  constructor(
    private nzModalService: NzModalService,
    public service: UsermanageService,
    private route: ActivatedRoute,
    private datePipe: DatePipe
  ) {}

  ngOnInit() {
    this.initData();
  }
  initData() {
    // 获取司机头部信息
    this.service
      .request(this.service.$api_get_user_detail, {
        appUserId: this.route.snapshot.params.id
      })
      .subscribe(res => {
        if (res) {
          this.userDetail = res;
        }
      });
    // 获取用户个人信息
    this.service
      .request(this.service.$api_get_user_identity, {
        id: this.route.snapshot.params.id
      })
      .subscribe(res => {
        if (res) {
          this.userIdentityDetail = res;
          this.tempalateUserIdentityDetail = { ...this.userIdentityDetail };
        }
      });
    // 获取驾驶证信息
    this.service.request(this.service.$api_get_driver_license, { appUserId: this.route.snapshot.params.id }).subscribe(res => {
      if (res) {
        this.driverDetail = res;
        this.tempalateDriverData = { ...this.driverDetail };
      }
    });
    // 获取从业资格证信息
    this.service.request(this.service.$api_get_driver_practice_seniority, { appUserId: this.route.snapshot.params.id }).subscribe(res => {
      if (res) {
        this.licenseDetail = res;
        this.tempalateLicenseDetail = { ...this.licenseDetail };
      }
    });
    // 获取载具信息
    // this.service.request(this.service.$api_get_driver_car_license, { appUserId: this.route.snapshot.params.id }).subscribe(res => {
    //   if (res) {
    //     this.carList = res;
    //   }
    // });
  }

  /** 启用/冻结司机 */
  userAction(status: number) {
    console.log( this.userDetail );
    
    this.nzModalService.warning({
      nzTitle: status === 1 ? '确定启用该司机吗？' : '确定冻结该司机吗？',
      nzContent: status === 1 ? '停用后，司机将被限制使用，无法登陆，请谨慎操作！' : '启用后，该司机将恢复正常使用功能，请再次确认！',
      nzOnOk: () => {
        this.service
          .request(this.service.$api_lock_or_free_user, {
            appUserId: [this.userDetail.appUserId],
            freezeOrResume: !!!status,
            pageName: '司机详情',
            telephone: this.userDetail.phone
          })
          .subscribe(res => {
            if (res) {
              this.service.msgSrv.success('操作成功');
            }
            this.initData();
          });
      }
    });
  }

  /** 审核通过个人信息 */
  approveUser() {
    this.nzModalService.confirm({
      nzTitle: '审核通过',
      nzContent: `是否确认通过(姓名:${this.userIdentityDetail.name})审核`,
      nzOnOk: () => {
        this.adjuctUser({ auditStatus: 0, auditType: 0, identityId: this.userIdentityDetail?.id }, '审核通过');
      }
    });
  }

  /** 驳回个人信息 */
  rejectedUser() {
    this.approvalOpinion = '';
    this.nzModalService.create({
      nzTitle: '审核驳回',
      nzContent: this.redectModal,
      nzOnOk: () => {
        if (!this.approvalOpinion) {
          return false;
        }
        this.adjuctUser(
          {
            auditStatus: 1,
            auditType: 0,
            identityId: this.userIdentityDetail?.id,
            certificationOpinions: this.approvalOpinion
          },
          '审核驳回成功'
        );
        return;
      }
    });
  }

  /** 审核通过驾驶员信息 */
  approveDriver() {
    this.nzModalService.confirm({
      nzTitle: '审核通过',
      nzContent: `<p>驾驶证号：${this.driverDetail?.licenseNo}</p><p>从业资格证号：${this.licenseDetail?.licenseNo}</p><p>是否确认通过审核`,
      nzOnOk: () => {
        this.adjuctDriverLicense(
          {
            approvalStatus: 20,
            appUserId: this.userDetail?.appUserId
          },
          '审核成功'
        );
      }
    });
  }

  /** 驳回驾驶员信息 */
  rejectedDriver() {
    this.approvalOpinion = '';
    this.nzModalService.create({
      nzTitle: '审核驳回',
      nzContent: this.rejectedDriverModal,
      nzOnOk: () => {
        if (!this.approvalOpinion) {
          return false;
        }
        this.adjuctDriverLicense(
          {
            approvalStatus: 30,
            appUserId: this.userDetail?.appUserId,
            approvalOpinion: this.approvalOpinion
          },
          '审核驳回成功'
        );
        return;
      }
    });
  }

  /** 个人信息审核 */
  private adjuctUser(params: any, msg: string) {
    this.service.request(this.service.$api_approve_identity, { ...params }).subscribe(res => {
      if (res) {
        this.service.msgSrv.success(msg);
      }
      this.initData();
    });
  }

  /** 驾驶员审核 */
  private adjuctDriverLicense(params: any, msg: string) {
    this.service.request(this.service.$api_approve_driver_license, { ...params }).subscribe(res => {
      if (res) {
        this.service.msgSrv.success(msg);
      }
      this.initData();
    });
  }

  /**
   * 开启修改
   * @param type 修改类型
   */
  ratify(type: number) {
    if (type) {
      this.isEditDriver = true;
    } else {
      this.isEditUser = true;
    }
  }

  /**
   * 需求修改
   * @param type 修改类型
   */
  reset(type: number) {
    if (type) {
      this.driverDetail = { ...this.tempalateDriverData };
      this.licenseDetail = { ...this.tempalateLicenseDetail };
      this.isEditDriver = false;
    } else {
      this.userIdentityDetail = { ...this.tempalateUserIdentityDetail };
      this.isEditUser = false;
    }
  }

  /**
   * 修改驾驶证，从业资格证信息
   */
  saveDriver() {
    const driverDetail = this.driverDetail;
    const licenseDetail = this.licenseDetail;
    const params = {
      userId: this.route.snapshot.params.id,
      userDriverLicenseDTO: {
        appUserId: driverDetail.appUserId,
        certificatePhoto: driverDetail.certificatePhoto,
        certificatePhotoWatermark: driverDetail.certificatePhotoWatermark,
        driverModel: driverDetail.driverModel,
        id: driverDetail.id,
        licenseNo: driverDetail.licenseNo,
        signingOrganization: driverDetail.signingOrganization,
        validEndTime:
          driverDetail.validEndTime?.length === 10
            ? driverDetail.validEndTime
            : this.datePipe.transform(driverDetail.validEndTime, 'yyyy-MM-dd'),
        validStartTime:
          driverDetail.validStartTime?.length === 10
            ? driverDetail.validStartTime
            : this.datePipe.transform(driverDetail.validStartTime, 'yyyy-MM-dd')
      },
      userPracticeSeniorityDTO: {
        appUserId: licenseDetail.appUserId,
        approvalStatus: licenseDetail.approvalStatus,
        certificatePhoto: licenseDetail.certificatePhoto,
        certificatePhotoWatermark: licenseDetail.certificatePhotoWatermark,
        id: licenseDetail.id,
        licenseNo: licenseDetail.licenseNo,
        regionCode: licenseDetail.regionCode,
        validEndTime:
          licenseDetail.validEndTime?.length === 10
            ? licenseDetail.validEndTime
            : this.datePipe.transform(licenseDetail.validEndTime, 'yyyy-MM-dd'),
        validStartTime:
          licenseDetail.validStartTime?.length === 10
            ? licenseDetail.validStartTime
            : this.datePipe.transform(licenseDetail.validStartTime, 'yyyy-MM-dd')
      }
    };
    this.service.request(this.service.$api_update_driver_license, params).subscribe(res => {
      if (res) {
        this.service.msgSrv.success('修改成功');
        this.isEditDriver = false;
        this.initData();
      }
    });
  }

  saveUser() {
    const userIdentity = this.userIdentityDetail;
    const params = {
      certificateNumber: userIdentity.certificateNumber,
      certificatePhotoBack: userIdentity.certificatePhotoBack,
      certificatePhotoBackWatermark: userIdentity.certificatePhotoBackWatermark,
      certificatePhotoFront: userIdentity.certificatePhotoFront,
      certificatePhotoFrontWatermark: userIdentity.certificatePhotoFrontWatermark,
      certificateType: userIdentity.certificateType,
      handCertificate: userIdentity.handCertificate,
      id: userIdentity.id,
      name: userIdentity.name,
      souceType: userIdentity.souceType,
      sourceAppId: userIdentity.sourceAppId,
      tenantId: userIdentity.tenantId,
      userId: userIdentity.userId,
      validEndTime:
        userIdentity.validEndTime?.length === 10
          ? userIdentity.validEndTime
          : this.datePipe.transform(userIdentity.validEndTime, 'yyyy-MM-dd'),
      validStartTime:
        userIdentity.validStartTime?.length === 10
          ? userIdentity.validStartTime
          : this.datePipe.transform(userIdentity.validStartTime, 'yyyy-MM-dd')
    };
    this.service.request(this.service.$api_update_driver_identity, params).subscribe(res => {
      if (res) {
        this.service.msgSrv.success('修改成功');
        this.isEditUser = false;
        this.initData();
      }
    });
  }

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

  showImg(url: any) {
    const params = {
      imgList: [url],
      index: 0
    };
    this.nzModalService.create({ nzContent: ImageViewComponent, nzComponentParams: { params } });
  }

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

  goBack() {
    window.history.go(-1);
  }
}
