import { ChangeDetectorRef, Component, Input, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { STChange, STColumn, STComponent, STData, STRequestOptions } from '@delon/abc/st';
import { SFComponent, SFSchema, SFSelectWidgetSchema, SFUISchema } from '@delon/form';
import { ModalHelper } from '@delon/theme';
import { processSingleSort } from '@shared';
import { NzDrawerRef, 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';
import { PublishchooseFamifiarAddComponent } from './add/add.component';
import { PublishchooseFamifiarSetCaptainComponent } from './set-captain/set-captain.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 = {};

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

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

    setTimeout(() => {
      this.initST();
      this.initST2();
    }, 200);
  }

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

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

  initST2() {
    this.columns2 = [
      {
        title: '司机姓名',
        index: 'name',
        width: 120
      },
      {
        title: '手机号',
        index: 'telephone',
        width: '120px'
      },
      {
        title: '车队长',
        render: 'captain',
        width: '100px'
      },
      {
        title: '指定车辆',
        index: 'carNo',
        width: '130px'
      },
      {
        title: '操作',
        className: 'text-center',
        width: 80,
        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();
    });
  }

  //设置车队长
  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[]): STData[] {
    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) {}
}
