import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { STColumn, STColumnBadge, STComponent, STData } from '@delon/abc/st';
import { SFComponent, SFSchema, SFUISchema } from '@delon/form';
import { ModalHelper } from '@delon/theme';
import { DynamicSettingModalComponent } from '@shared';
import { NzModalService } from 'ng-zorro-antd/modal';
import { UsermanageService } from '../../../services/usercenter.service';
@Component({
  selector: 'app-usercenter-components-driver-config',
  templateUrl: './driver-config.component.html',
  styleUrls: ['./driver-config.component.less']
})
export class UserCenterComponentsDriverConfigComponent implements OnInit {
  _$expand = false;

  ui: SFUISchema = { '*': { spanLabelFixed: 120, grid: { lg: 8, md: 12, sm: 12, xs: 24 } } };
  schema: SFSchema = this.initSF();
  columns: STColumn[] = this.initST();
  @ViewChild('st', { static: false }) st!: STComponent;
  @ViewChild('sf', { static: false }) sf!: SFComponent;

  @ViewChild('promoterModal', { static: false })
  promoterModal!: any;
  promotersTelephone = '';

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

  /**
   * 查询参数
   */
  get reqParams() {
    const params: any = {
      ...(this.sf && this.sf.value)
    };
    if (this.sf?.value.effectiveDate) {
      params.effectiveDateStart = this.sf?.value.effectiveDate[0];
      params.effectiveDateEnd = this.sf?.value.effectiveDate[1];
    }
    delete params.effectiveDate;
    delete params.expand;
    return params;
  }

  get selectedRows() {
    return this.st?.list.filter(item => item.checked) || [];
  }

  ngOnInit() {
    this.ar.url.subscribe(params => {
      this.st?.load(1);
    });
  }
  dataProcess(data: STData[]): STData[] {
    return data.map((i, index) => {
      i.showSortFlag = false;
      return i;
    });
  }

  addPromoter(item?: any) {
    this.promotersTelephone = item?.promotersTelephone;
    const modal = this.modal.create({
      nzTitle: '推广业务员',
      nzContent: this.promoterModal,
      nzOnOk: () => {
        if (!!!this.promotersTelephone) {
          return false;
        }
        if (typeof this.promotersTelephone === 'string' && !/(^1\d{10}$)/.test(this.promotersTelephone)) {
          this.service.msgSrv.error('手机格式错误');
          return false;
        }
        this.service
          .request(this.service.$api_add_user_salesman, { userId: item.userId, mobile: this.promotersTelephone })
          .subscribe(res => {
            if (res) {
              this.service.msgSrv.success(item?.promotersTelephone ? '添加推广员成功' : '修改推广员成功');
            }
            this.st.load();
          });
        return;
      }
    });
  }

  settingAction(item?: any) {
    this.modal.create({
      nzTitle: '配置',
      nzContent: DynamicSettingModalComponent,
      nzWidth: 900,
      nzComponentParams: {
        extendType: '3',
        businessId: item.id,
        configvalue: 'sys.config'
      },
      nzFooter: null
    });
  }

  expandToggle() {
    this._$expand = !this._$expand;
    this.sf?.setValue('/expand', this._$expand);
  }

  /**
   * 重置表单
   */
  resetSF() {
    this.sf.reset();
    this._$expand = false;
  }

  exportList() {
    const params = this.reqParams;
    this.service.downloadFile(this.service.$api_export_driver_cap, params);
  }

  private initSF(): SFSchema {
    return {
      properties: {
        expand: {
          type: 'boolean',
          ui: {
            hidden: true
          }
        },
        name: { title: '司机姓名', type: 'string', ui: { placeholder: '请输入', showRequired: false } },
        mobile: {
          title: '手机号',
          type: 'string',
          maxLength: 11,
          ui: {
            placeholder: '请输入'
          }
        },
        isCaptain: {
          type: 'string',
          title: '类型',
          enum: [
            { label: '全部', value: '' },
            { label: '车队长', value: 1 },
            { label: '司机', value: 0 },
          ],
          default: '',
          ui: {
            widget: 'select',
          }
        }
      }
    };
  }

  private initST(): STColumn[] {
    return [
      // { title: '', type: 'checkbox', className: 'text-center' },
      { title: '司机姓名', className: 'text-center', index: 'name' },
      { title: '手机号', className: 'text-center', index: 'mobile' },
      { title: '类型', className: 'text-center', render: 'isCaptain' },
      { title: '月承运金额上限（元）', className: 'text-center', render: 'monthFreightAmount' },
      { title: '日提现金额上限（元）', className: 'text-center', render: 'dayWithdrawalAmount', },
      { title: '月提现金额上限（元）', className: 'text-center', render: 'monthWithdrawalAmount' },
      { title: '月收款金额上限（元）', className: 'text-center', render: 'monthReceivableAmount' },
      {
        title: '操作',
        width: '170px',
        className: 'text-center',
        buttons: [
          {
            text: '配置',
            click: item => this.settingAction(item),
            acl: { ability: ['USERCENTER-DRIVER-CONFIG-config'] }
          }
        ]
      }
    ];
  }
}
