import { Component, OnInit, ViewChild } from '@angular/core';
import { STChange, STColumn, STColumnBadge, STComponent, STData } from '@delon/abc/st';
import { SFComponent, SFSchema, SFUISchema } from '@delon/form';
import { ModalHelper, _HttpClient } from '@delon/theme';
import { EAEnvironmentService } from '@shared';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalRef, NzModalService } from 'ng-zorro-antd/modal';
import { SupplyManagementService } from '../../services/supply-management.service';
import { SupplyManagementAddDriversComponent } from '../add-drivers/add-drivers.component';
import { CarAddmodalComponent } from '../addmodal/addmodal.component';


const BADGE: STColumnBadge = {
  1: { text: '空闲', color: 'success' },
  2: { text: '未实名', color: 'error' },
  3: { text: '在途', color: 'warning' },
};

@Component({
  selector: 'app-supply-management-assigned-car',
  templateUrl: './assigned-car.component.html',
})
export class SupplyManagementVehicleAssignedCarComponent implements OnInit {
  record: any = {};
  i: any;
  schema: SFSchema = {};
  ui: SFUISchema = {};
  columns: STColumn[] = [];

  @ViewChild('st') st!: STComponent;
  @ViewChild('sf', { static: false }) sf!: SFComponent;
  status: string = 'anew';
  url = ''; // 请求的api地址
  params: any = {}; // 传进来的参数
  cardBADGE: STColumnBadge | any = {
    0: { text: '空闲', color: 'success' },
    1: { text: '在途', color: 'warning' },
    2: { text: '未认证', color: 'error' },
  };
  selectedRows: any = null; // 已选行
  constructor(
    private modal: NzModalRef,
    private msgSrv: NzMessageService,
    public service: SupplyManagementService,
    private modalHelper: ModalHelper,
    private envSrv: EAEnvironmentService,
    private modalSrv: NzModalService
  ) {
    this.initSF();
    this.initSt();
  }

  /**
* 查询参数
*/
  get reqParams() {
    return {
      ...this.sf?.value,
      loadingTime: this.params?.loadingTime,
      enterpriseId: this.params?.shipperAppUserId,
      enterpriseProjectId: this.params?.enterpriseProjectId,
      unloadingTime: this.params?.unloadingTime,
    };
  }




  /**
* 初始化查询表单
*/
  initSF() {
    this.schema = {
      properties: {
        _$expand: { type: 'boolean', ui: { hidden: true } },
        nameOrPhone: {
          type: 'string',
          title: '承运司机',
          ui: {
            placeholder: '请输入司机姓名/手机号'
          }
        },
        carNo: {
          type: 'string',
          title: '车牌号',
          maxLength: 9,
          ui: {
            placeholder: '请输入车牌号'
          }
        },
      },
      type: 'object',
    };
    this.ui = { '*': { spanLabelFixed: 10, grid: { span: 8, gutter: 1 } } };
  }

  /**
   * 初始化数据列表
   */
  initSt() {
    this.columns = [
      { width: 50, type: 'radio', className: 'text-center' },
      { title: '司机姓名', width: 120, index: 'name', className: 'text-center' },
      { title: '手机号', index: 'telephone', width: 200, className: 'text-center' },
      { title: '车队长', render: 'carCaptain', className: 'text-center' },
      { title: '指定车辆', width: 300, render: 'carId', className: 'text-center' },
      { title: '状态', render: 'driverStatus', className: 'text-center', type: 'badge', badge: BADGE },
    ];
  }

  ngOnInit(): void {
    console.log(this.params)
  }

  dataProcess = (data: STData[], rawData: any): STData[] => {
    if (rawData.status === 505016) {
      this.modalSrv.confirm({
        nzTitle: '系统提示',
        nzContent: '<b>该司机还未注册，是否邀请他注册？点击"是"系统将发送邀请短信给司机</b>',
        nzOkText: '确定',
        nzCancelText: '取消',
        nzOnOk: () => {
          this.sendMsg(this.sf?.value?.nameOrPhone).subscribe((res => {
            if (res.code === '1') {
              this.service.msgSrv.success('发送成功');
            } else {
              this.service.msgSrv.success('发送失败');
            }
          }));
        }
      });
      return [];
    }
    return data.map((i, index) => {
      i.carId = '';
      i.disabled = (i?.certificationStatus === 1 && i.driverStatus === 1);
      const defaultCar = i?.userCarLicenseDesensitizationVOList?.find((item: any) => item.isDefault);
      if (defaultCar) {
        i.carId = defaultCar?.carId;
      }
      return i;
    });
  }

  save(): void {
    const { carId, appUserId: driverId, captainAppUserId: carCaptainId } = this.selectedRows;
    const params: any = { carId, driverId, carCaptainId };
    this.service.request(this.url, { ...params, ...this.params }).subscribe((res: any) => {
      if (res) {
        this.service.msgSrv.success('指派成功！');
        this.modal.close(res);
      }
    })

  }

  changeSt(e: STChange): void {
    if (e?.type === 'loaded') this.selectedRows = null;
    if (e?.type === 'radio') this.selectedRows = e?.radio;

  }
  /**
   * 添加司机
   * @param item
   */
  addDriver() {
    this.modalHelper.create(CarAddmodalComponent, {}, { size: 900, modalOptions: { nzMaskClosable: false } }).subscribe((res) => {
      if (res) this.st.reload();
    });
  }

  /**
   * 校验司机是否能设置车队长
   * @param item 当前对象
   */
  verifyCanSetCarCaptain(item: any) {
    this.service.request(this.service.$api_get_sys_config, [{ itemKey: 'sys.config.shipper.setCarCaptain', businessId: this.envSrv.env.enterpriseId }]).subscribe(res => {
      if (res && res.length > 0) {
        const { itemValue } = res[0];
        if (itemValue !== '1') {
          this.service.msgSrv.error('不可设置车队长！');
          return;
        }
        this.setCarCaptain(item);
      }
    })
  }

  /**
   * 设置车队长
   */
  setCarCaptain(item: any) {

    this.modalHelper.create(SupplyManagementAddDriversComponent, { dirvierInfo: item }, {
      size: 900,
      modalOptions: { nzMaskClosable: false, nzTitle: '设置' }
    }
    ).subscribe((res) => {
      if (res) {
        item.captainName = res?.name;
        item.captainPhone = res?.mobile;
        item.captainAppUserId = res?.appUserId;
      }
    });
  }

  close(): void {
    this.modal.destroy();
  }

  reset() {
    this.sf.reset();
    this.st.load(1);
  }

  /**
   * 验证车辆的状态
   */
  verifyVechicleStatus(params: any) {
    if (this.selectedRows) {
      const obj = this.status === 'anew' ? { resourceId: params.id } : { ...params };
      const { carId, appUserId: driverId, captainAppUserId: carCaptainId } = this.selectedRows;
      const carInfo: any = { carId, driverId, carCaptainId };
      this.service.request(this.service.$api_verify_vehicle_status, { ...obj, ...carInfo }).subscribe(res => {
        if (res) {
          const { title, alert, subContent, content } = res;
          switch (alert) {
            case 'Error':
              // if (code === '3' || code === '4' || code === '8') {
              //   this.error(title, subContent, '#CF3834');
              // } else {
              this.error(title, content, subContent);
              break;
            case 'Warn':
              this.showConfirm(title, content, subContent);
              break;
            case 'Success':
              this.save();
              break;
          }
        }
      })
    }

  }

  error(title: string, content: string, subContent: string): void {
    this.modalSrv.error({
      nzTitle: title,
      nzContent: `<span class="text-error-dark">${content ? content : ''}</span><span class="text-grey-dark">${subContent ? subContent : ''}</span>`,
      nzOkText: '知道了'
    });
  }

  showConfirm(title: string, content: string, subContent: string): void {
    this.modalSrv.confirm({
      nzTitle: title,
      nzContent: `<span class="text-error-dark">${content ? content : ''}</span><span class="text-grey-dark">${subContent ? subContent : ''}</span>`,
      nzOkText: '继续',
      nzCancelText: '取消',
      nzOnOk: () => {
        this.save();
      }
    });
  }

  /**
* 发送邀请司机注册短信
*/
  sendMsg(phoneNumber: string) {
    return this.service.request(this.service.$api_send_msg_code, phoneNumber)
  }

}
