import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { STColumn, STColumnBadge, STComponent, STData } from '@delon/abc/st';
import { SFComponent, SFDateWidgetSchema, SFSchema, SFUISchema } from '@delon/form';
import { NzModalService } from 'ng-zorro-antd/modal';
import { UsermanageService } from '../../../services/usercenter.service';
@Component({
  selector: 'app-Freight-components-user',
  styleUrls: ['./user.component.less'],
  templateUrl: './user.component.html'
})
export class FreightComponentsUserComponent implements OnInit {
  _$expand = false;
  ui: SFUISchema = { '*': { spanLabelFixed: 120, grid: { lg: 8, md: 12, sm: 12, xs: 24 }, enter: () => this.st.load() } };
  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) {}

  /**
   * 查询参数
   */
  get reqParams() {
    const params: any = {
      ...(this.sf && this.sf.value)
    };
    if (this.sf?.value.effectiveDate) {
      Object.assign(params, {
        time: {
          start: this.sf?.value.effectiveDate[0],
          end: this.sf?.value.effectiveDate[1]
        }
      });
      // 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);
    });
  }

  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)) {
          return false;
        }
        this.service.request(this.service.$api_add_salesman, { ids: [item.id], salesmanMobile: this.promotersTelephone }).subscribe(res => {
          if (res) {
            this.service.msgSrv.success(item?.promotersTelephone ? '添加推广员成功' : '修改推广员成功');
          }
          this.st.load();
        });
        return;
      }
    });
  }

  userAction(status: number, appUserId: Array<number>) {
    this.modal.warning({
      nzTitle: status === 1 ? '确定启用该用户吗？' : '确定冻结该用户吗？',
      nzContent:
        status === 1
          ? '停用后，该用户将被限制使用，不限于访问受限、无法发布货源等，请谨慎操作'
          : '启用后，该用户将恢复正常使用功能，请再次确认',
      nzOnOk: () => {
        this.service
          .request(this.service.$api_lock_app_user, {
            appUserId,
            freezeOrResume: !!!status
          })
          .subscribe(res => {
            if (res) {
              this.service.msgSrv.success(status === 1 ? '启用成功' : '冻结成功');
              this.st.reload();
            }
          });
      }
    });
  }

  expandToggle() {
    this._$expand = !this._$expand;
    this.sf?.setValue('/expand', this._$expand);
  }
  creat() {
    this.router.navigate(['./new'], { relativeTo: this.ar });
  }

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

  private initSF(): SFSchema {
    return {
      properties: {
        expand: {
          type: 'boolean',
          ui: {
            hidden: true
          }
        },
        name: {
          title: '用户姓名',
          type: 'string',
          ui: {
            placeholder: '请输入',
            showRequired: false
          }
        },
        contactsName: {
          title: '企业名称',
          type: 'string',
          ui: {
            placeholder: '请输入',
            showRequired: false
          }
        },
        telephone: {
          title: '手机号',
          type: 'string',
          format: 'mobile',
          maxLength: 11,
          ui: {
            placeholder: '请输入'
          }
        },
        stateLocked: {
          type: 'string',
          title: '状态',
          enum: [
            { label: '全部', value: '' },
            { label: '正常', value: 0 },
            { label: '冻结', value: 1 }
          ],
          default: '',
          ui: {
            widget: 'select',
            visibleIf: {
              expand: (value: boolean) => value
            }
          }
        },
        promotersTelephone: {
          title: '推广业务员',
          type: 'string',
          format: 'mobile',
          maxLength: 11,
          ui: {
            placeholder: '请输入手机号',
            visibleIf: {
              expand: (value: boolean) => value
            }
          }
        },
        effectiveDate: {
          title: '申请时间',
          type: 'string',
          ui: {
            widget: 'date',
            mode: 'range',
            format: 'yyyy-MM-dd',
            visibleIf: {
              expand: (value: boolean) => value
            }
          } as SFDateWidgetSchema
        }
      }
    };
  }

  private initST(): STColumn[] {
    return [
      { title: '用户姓名', className: 'text-center', index: 'name' },
      { title: '手机号', className: 'text-center', index: 'telephone' },
      { title: '身份证件号', className: 'text-center', index: 'certificateNumber' },
      { title: '常用服务', className: 'text-center', index: 'unifiedSocialCreditCode' },
      { title: '推广业务员', className: 'text-center', index: 'promotersTelephone', render: 'promotersTelephone' },
      { title: '申请时间', className: 'text-center', index: 'createTime', type: 'date' },
      {
        title: '状态',
        className: 'text-center',
        index: 'certificationStatus',
        type: 'badge',
        badge: {
          0: { text: '待审核', color: 'processing' },
          1: { text: '已成功', color: 'success' },
          2: { text: '已驳回', color: 'warning' }
        }
      },
      {
        title: '操作',
        width: '170px',
        className: 'text-center',
        buttons: [
          {
            text: '查看',
            click: (item: any) => {
              this.router.navigate(['./view', item.appUserId], { relativeTo: this.ar });
            }
          },
          {
            text: '冻结',
            iif: item => item.stateLocked === 0,
            click: (item: any) => this.userAction(0, [Number(item.appUserId)])
          },
          {
            text: '启用',
            iif: item => item.stateLocked === 1,
            click: (item: any) => this.userAction(1, [Number(item.appUserId)])
          }
        ]
      }
    ];
  }
}
