import { Component, Input, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { STColumn, STComponent, STData } from '@delon/abc/st';
import { SFComponent, SFSchema, SFUISchema } from '@delon/form';
import { ModalHelper } from '@delon/theme';
import { EAEnvironmentService } from '@shared';
import { NzDrawerService } from 'ng-zorro-antd/drawer';
import { NzModalRef, NzModalService } from 'ng-zorro-antd/modal';
import { SupplyManagementAddDriversComponent } from 'src/app/routes/supply-management/components/add-drivers/add-drivers.component';
import { SupplyManagementService } from '../../services/supply-management.service';
import { CarAddmodalComponent } from '../addmodal/addmodal.component';


@Component({
  selector: 'app-publish-goods-choose-famifiar',
  templateUrl: './choose-famifiar.component.html'
})
export class PublishGoodsChooseFamifiarComponent implements OnInit {
  schema: SFSchema = {};
  columns!: STColumn[];
  i: any;
  ui!: SFUISchema;
  sfExpand = false;
  @ViewChild('st', { static: false })
  st!: STComponent;
  @ViewChild('sf', { static: false })
  sf!: SFComponent;

  @ViewChild('st2', { static: false })
  st2!: STComponent;
  columns2!: STColumn[];
  st2Data: STData[] = [];

  @Input()
  submitUrl = '';

  @Input()
  submitParams: any;

  constructor(
    private modal: NzModalRef,
    public router: Router,
    public ar: ActivatedRoute,
    private drawerService: NzDrawerService,
    public service: SupplyManagementService,
    private modalService: NzModalService,
    private modalHelper: ModalHelper,
    private envSrv: EAEnvironmentService
  ) { }

  /**
   * 查询参数
   */
  get reqParams() {
    return {
      ...this.sf?.value,
      isManage: 0
    };
  }
  ngOnInit() {
    this.initSF();
    this.initST();
    this.initST2();
  }

  initSF() {
    this.schema = {
      properties: {
        nameOrPhone: {
          type: 'string',
          title: '承运司机',
          ui: {
            placeholder: '请输入司机姓名/手机号'
          }
        },
        carNo: {
          type: 'string',
          title: '车牌号',
          ui: {
            placeholder: '请输入车牌号'
          }
        }
      }
    };
    this.ui = {
      '*': {
        grid: { span: 12, gutter: 4 }
      }
    };
  }

  initST() {
    this.columns = [
      {
        title: '司机姓名',
        index: 'name'
      },
      {
        title: '手机号',
        index: 'telephone'
      },
      {
        title: '指定车辆',
        width: 130,
        render: 'userCarLicenseDesensitizationVOList'
      },
      {
        title: '状态',
        className: 'text-center',
        index: 'certificationStatus',
        type: 'badge',
        badge: {
          '-1': { text: '未提交', color: 'default' },
          0: { text: '待审核', color: 'processing' },
          1: { text: '已认证', color: 'success' },
          2: { text: '未认证', color: 'error' }
        }
      },
      {
        title: '操作',
        className: 'text-center',
        buttons: [
          {
            text: '选择',
            iif: item => item.showChoose != false,
            click: (_record, _modal, _instance) => this.verifyVechicleStatus(_record),
            iifBehavior: 'disabled'
          }
        ]
      }
    ];
  }

  initST2() {
    this.columns2 = [
      {
        title: '司机姓名',
        index: 'name',
        width: '90px'
      },
      {
        title: '手机号',
        index: 'telephone',
        width: '120px'
      },
      {
        title: '车队长',
        render: 'captain',
        width: '200px'
      },
      {
        title: '指定车辆',
        render: 'defaultCar',
        width: '130px'
      },
      {
        title: '操作',
        className: 'text-center',
        width: '90px',
        buttons: [
          {
            text: '移除',
            click: (_record, _modal, _instance) => this.remove(_record, _modal, _instance)
          }
        ]
      }
    ];
  }

  // 选择
  choose(record: STData) {
    this.st2Data = [...this.st2Data, ...[record]];
    this.st.setRow(record, { showChoose: false });
  }
  // 移除
  remove(record: STData, value1: any, comp: any) {
    const index = this.st?.list.findIndex((obj: any) => obj.appUserId === record.appUserId);
    if (index >= 0) {
      comp!.removeRow(record);
      this.st2Data = this.st2Data.filter(item => item.appUserId !== record.appUserId);
      this.st.setRow(index, { showChoose: true });
    }
  }

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

  /**
   * 校验司机是否能设置车队长
   * @param item 当前对象
   */
  verifyCanSetCarCaptain(item: any, index: 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.setCaptain(item, index);
      }
    })
  }

  //设置车队长
  setCaptain(record: STData, index: any) {
    this.modalHelper
      .create(
        SupplyManagementAddDriversComponent,
        { dirvierInfo: record },
        {
          size: 900,
          modalOptions: { nzMaskClosable: false, nzTitle: '设置' }
        }
      )
      .subscribe(res => {
        if (res) {
          this.st2.setRow(index, { captainName: res.name, captainPhone: res.mobile, captainAppUserId: res.appUserId });
        }
      });
  }

  /**
   * 重置表单
   */
  resetSF() {
    this.sf.reset();
    this.sfExpand = false;
    this.st.load(1);
  }

  expandToggle() {
    this.sfExpand = !this.sfExpand;
    this.sf?.setValue('/_expand', this.sfExpand);
  }

  // 熟车请求数据处理
  reqProcess = (data: STData[], rawData: any): STData[] => {
    if (rawData.status === 505016) {
      this.modalService.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) => {
      const defaultCart = i.userCarLicenseDesensitizationVOList.find((cart: any) => cart.isDefault);
      return { ...i, default: defaultCart || '' };
    });
  }

  cancel() {
    this.modal.destroy();
  }

  ok() {
    if (this.st2._data?.length <= 0) {
      this.service.msgSrv.warning('请选择熟车');
      return;
    }
    const data = this.st2._data.map(item => ({
      driverId: item.appUserId,
      carId: item.default?.carId || null,
      carCaptainId: item.captainAppUserId
    }));
    this.service.request(this.submitUrl, { ...this.submitParams, carDriverIds: data }).subscribe((rs: any) => {
      if (rs) {
        this.service.msgSrv.success('指派成功');
        this.modal.destroy(true);
      }
    });
  }

  carChange(event: any, item: STData) {

  }

  /**
* 验证车辆的状态
*/
  verifyVechicleStatus(_record: STData) {
    const { carId, appUserId: driverId, captainAppUserId: carCaptainId } = _record;
    const carInfo: any = { carId, driverId, carCaptainId };
    const goodsInfoList = this.submitParams?.goodsInfoList;
    this.service.request(this.service.$api_verify_vehicle_status, { ...carInfo, goodsInfoList }).subscribe((res: any) => {
      if (res) {
        const { title, alert, subContent, content } = res;
        switch (alert) {
          case 'Error':
            this.error(title, content, subContent);
            break;
          case 'Warn':
            this.showConfirm(_record, title, content, subContent);
            break;
          case 'Success':
            this.choose(_record);
            break;
        }
      }
    });

  }

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

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

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