import { Component, Input, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { STChange, STColumn, STColumnBadge, STComponent, STData } from '@delon/abc/st';
import { SFComponent, SFSchema, SFUISchema } from '@delon/form';
import { ModalHelper } from '@delon/theme';
import { isTemplateRef } from 'ng-zorro-antd/core/util';
import { NzModalRef, NzModalService } from 'ng-zorro-antd/modal';
import { SupplyManagementService } from '../../services/supply-management.service';
import { SupplyManagementAddDriversComponent } from '../add-drivers/add-drivers.component';
import { PublishchooseFamifiarAddComponent } from '../choose-famifiar/add/add.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-bulk.component.html',
})
export class SupplyManagementBulkAssignedCarComponent 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 = {};
  hasSelectedDrivers = [];

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

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

  ngOnInit() {
    this.initSF();
    this.initST();
    this.initST2();
    this.getHasAssignedCar(this.i?.id);
  }

  initSF() {
    this.schema = {
      properties: {
        nameOrPhone: {
          type: 'string',
          title: '',
          ui: {
            placeholder: '请输入司机姓名/手机号'
          }
        },
        carNo: {
          type: 'string',
          title: '',
          ui: {
            placeholder: '请输入车牌号'
          }
        }
      }
    };
    this.ui = {
      '*': {
        spanLabelFixed: 10,
        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.checked,
            click: (_record, _modal, _instance) => this.choose(_record),
            iifBehavior: 'disabled'
          }
        ]
      }
    ];
  }

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

  // 选择
  choose(record: STData) {
    this.st2Data = [...this.st2Data, ...[record]];
    this.st.setRow(record, { checked: true });
  }

  // 移除
  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, { checked: false });
    }
  }

  //添加司机
  add() {
    this.modalService.create({
      nzTitle: '添加司机',
      nzContent: PublishchooseFamifiarAddComponent
    });
  }

  //设置车队长
  setCaptain(record: STData) {

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

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

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

  // 熟车请求数据处理
  resProcess(data: STData[]): STData[] {
    return data.map((i, index) => {
      const defaultCart = i.userCarLicenseDesensitizationVOList.find((cart: any) => cart.isDefault);
      return { ...i, default: defaultCart || '' };
    });
  }

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

  submit() {
    if (this.st2Data?.length <= 0) {
      this.service.msgSrv.warning('请选择熟车');
      return;
    }
    const data = this.st2Data.map(item => ({ driverId: item.appUserId, carId: item.default?.carId || null, carCaptainId: item.captainAppUserId }));
    this.service.request(this.service.$api_save_assign_bulk, { id: this.i?.id, carDriverIds: data }).subscribe(res => {
      if (res) {
        this.service.msgSrv.success('指派成功');
        this.modal.destroy(true);
      }
    });
  }

  changeSt(e: STChange) {
    if (e?.type === 'loaded' && this.st2Data.length > 0) {
      // 页面加载完成时勾选
      (e?.loaded || []).forEach((r, index) => {
        this.st2Data.forEach((x) => {
          if (x.appUserId === r.appUserId) {
            this.st.setRow(index, { checked: true });
          }
        });
      });
    }
  }
  carChange(event: any, item: STData) {
    // this.st.setRow(item, { carName: event });
  }

  getHasAssignedCar(id: any) {
    this.service.request(this.service.$api_get_has_assigned_car_list, { id }).subscribe(res => {
      if (res) {
        this.hasSelectedDrivers = res;
        this.st2Data = [...res];
        this.st.reload();
      }
    })
  }

}
