import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
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 { VehicleService } from '../../../services/vehicle.service';
import { VehicleComponentsListEditComponent } from '../edit/edit.component';
import { VehicleImgViewComponent } from '../img-view/img-view.component';
import { apiConf } from '@conf/api.conf';
import { NzModalService } from 'ng-zorro-antd/modal';
import { ImageViewComponent } from 'src/app/shared/components/imagelist';
import { EADateUtil } from '@shared';
import { NzImageService } from 'ng-zorro-antd/image';

@Component({
  selector: 'app-supplier-components-list-view',
  templateUrl: './detail.component.html',
  styleUrls: ['./detail.component.less']
})
export class VehicleComponentsListDetailComponent implements OnInit {
  i: any;
  @ViewChild('st', { static: false }) st!: STComponent;
  isShow = false;
  isVisible = false;
  isEdit = false;
  modalTitle = '有效期';
  modalName = '';
  ui!: SFUISchema;
  columns!: STColumn[];
  uploadURl = apiConf.fileUpload;
  schema!: SFSchema;
  @ViewChild('sf', { static: false }) sf!: SFComponent;
  schema1!: SFSchema;
  @ViewChild('sf1', { static: false }) sf1!: SFComponent;
  validData: any = ['suppliersType'];
  suppliersData: any = {};
  disabledUpload = false;
  detailData: any = this.initData();
  tempalateData: any;
  contenCarNoColor: any;
  contencarModel: any;
  contenCarLength: any;

  constructor(
    private http: _HttpClient,
    private modal: ModalHelper,
    public service: VehicleService,
    private route: ActivatedRoute,
    private modalHelper: ModalHelper,
    private msgSrv: NzMessageService,
    private nzModalService: NzModalService,
    private nzImageService: NzImageService
  ) {}

  ngOnInit() {
    this.getSelectList();
    this.getDetailList();
    this.initSF();
    this.initSF1();
    this.initST();
  }
  /**
   * 查询参数
   */
  get reqParams() {
    return { id: this.route.snapshot?.params?.id };
  }
  /**
   * 初始化查询表单
   */
  initSF() {
    this.schema = {
      properties: {
        _$expand: { type: 'boolean', ui: { hidden: true } },
        effectiveDate: {
          title: '有效期',
          type: 'string',
          ui: {
            widget: 'date',
            format: 'yyyy-MM-dd 00:00:00'
            // hidden: this.modalName === 'effectiveDate' ? false : true,
          } as SFDateWidgetSchema
        }
      },
      required: ['effectiveDate']
    };
    this.ui = { '*': { spanLabelFixed: 120, grid: { span: 24 } } };
  }
  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: '录入人员', index: 'saveUser', 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),
            // iif: item => item.auditStatusEnum == -1
          }
        ]
      }
    ];
  }
  initSF1() {
    this.schema1 = {
      properties: {
        _$expand: { type: 'boolean', ui: { hidden: true } },
        suppliersType: {
          type: 'string',
          title: '类型',
          enum: [
            { label: '非外部供应商', value: 0 },
            { label: '外部供应商', value: 1 }
          ],
          default: '',
          ui: {
            widget: 'select',
            change: (args: any) => {
              console.log(args, 'args');
              this.suppliersData.suppliersType = args;
              if (args === 1) {
                this.validData = ['suppliersType', 'externalSuppliersId'];
              } else {
                this.validData = ['suppliersType'];
                this.suppliersData.externalSuppliersId = '';
              }
              this.initSF1();
            }
          }
        },
        externalSuppliersId: {
          title: '外部供应商id',
          type: 'string',
          default: '',
          ui: {
            visibleIf: { suppliersType: (value: any) => value === 1 }
          }
        }
      },
      required: this.validData
    };
  }
  // 获取录单员
  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;
  }
  //
  getDetailList() {
    console.log(this.route.snapshot?.params?.id);
    const params = {
      id: this.route.snapshot?.params?.id
    };
    this.service.request(`${this.service.$api_get_operate_get}`, params).subscribe(res => {
      this.detailData = res;
      this.tempalateData = res;
    });
  }

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

  handleCancel(name: any) {}

  /**
   *查看评价
   */
  viewEvaluate(item: any) {
    this.modal.createStatic(VehicleImgViewComponent, { i: item }).subscribe(() => {
      this.st.reload();
      this.getDetailList();
    });
  }
  /**
   *查看评价
   */
  updateEvaluate(item: any) {
    this.modal.createStatic(VehicleComponentsListEditComponent, { i: item }).subscribe(() => {
      this.st.reload();
      this.getDetailList();
    });
  }
  handleOK() {}
  ratify() {
    this.isEdit = true;
  }
  changeUpload({ file, fileList, type }: any, key: string) {
    console.log({ file, fileList, type });
    if (type === 'success') {
      this.detailData[key] = file.response.data.fullFilePath;
    }
  }
  deleteImg(key: string) {
    console.log(key);
    this.nzModalService.warning({
      nzTitle: '是否确认删除该图片',
      nzOnOk: () => {
        this.disabledUpload = true;
        this.detailData[key] = '';
        setTimeout(() => {
          this.disabledUpload = false;
        }, 100);
      }
    });
  }
  showImg(url: any) {
    const params = {
      imgList: [url],
      index: 0
    };
    this.nzImageService.preview([{ src: url }]);
    // this.nzModalService.create({ nzContent: ImageViewComponent, nzComponentParams: { params } });
  }

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

  save() {
    console.log(this.detailData);
    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);
    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, this.detailData).subscribe(res => {
      console.log(res);
      if (res) {
        this.getDetailList();
         this.isEdit = false;
        this.service.msgSrv.success('修改成功！');
      }
    });
  }

  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: ''
    };
  }
}
