import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { STChange, STColumn, STColumnBadge, STComponent, STData, STRequestOptions } from '@delon/abc/st';
import { SFComponent, SFSchema, SFUISchema } from '@delon/form';
import { DynamicSettingModalComponent, ShipperBaseService } from '@shared';
import { NzModalService } from 'ng-zorro-antd/modal';
import { AccountDetailComponent } from 'src/app/shared/components/account-detail/account-detail.component';
import { UsermanageService } from '../../../services/usercenter.service';
@Component({
  selector: 'app-Freight-components-list',
  templateUrl: './list.component.html',
  styleUrls: ['./list.component.less']
})
export class FreightComponentsListComponent implements OnInit {
  _$expand = false;
  ui!: SFUISchema;
  schema!: SFSchema;
  columns!: STColumn[];
  @ViewChild('st', { static: false }) st!: STComponent;
  @ViewChild('sf', { static: false }) sf!: SFComponent;

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

  loadingList = true;
  constructor(
    public service: UsermanageService,
    private modal: NzModalService,
    private router: Router,
    private ar: ActivatedRoute,
    public shipperservice: ShipperBaseService
  ) {}

  ngOnInit() {
    this.initSF();
    this.initST();
    this.ar.url.subscribe(params => {
      this.st?.load(1);
    });
  }

  beforeReq = (requestOptions: STRequestOptions) => {
    Object.assign(requestOptions.body, { listSource: 1 });
    if (this.sf) {
      Object.assign(requestOptions.body, {
        ...this.sf.value
      });
    }
    this.loadingList = true;
    return requestOptions;
  };

  dataProcess = (data: STData[]): STData[] => {
    this.loadingList = false;
    return data;
  };

  settingAction(item?: any) {
    this.modal.create({
      nzTitle: '基础设置',
      nzContent: DynamicSettingModalComponent,
      nzWidth: 900,
      nzComponentParams: {
        extendType: '2',
        businessId: item.id
      },
      nzFooter: null
    });
  }

  showAccountDetail(item: any) {
    this.modal.create({
      nzTitle: '资金账户',
      nzContent: AccountDetailComponent,
      nzNoAnimation: true,
      nzWidth: 600,
      nzComponentParams: {
        isCanCreate: true,
        url: '/api/fcc/accountBalance/getShipperAccountBalanceDetailByOperator',
        params: { accountType: 1, roleId: item.id, ctfId: item.unifiedSocialCreditCode, clientName: item.enterpriseName }
      },
      nzFooter: null
    });
  }

  initSF() {
    this.schema = {
      properties: {
        expand: {
          type: 'boolean',
          ui: {
            hidden: true
          }
        },
        enterpriseName: {
          title: '企业名称',
          type: 'string',
          ui: {
            placeholder: '请输入',
            showRequired: false
          }
        },
        contactName: {
          title: '管理员',
          type: 'string',
          ui: {
            placeholder: '请输入',
            showRequired: false
          }
        },

        networkTransporter: {
          type: 'string',
          title: '网络货运人',
          ui: {
            widget: 'select',
            placeholder: '请选择',
            allowClear: true,
            asyncData: () => this.shipperservice.getNetworkFreightForwarder()
          }
        },
        promotersTelephone: {
          title: '业务员',
          type: 'string',
          ui: {
            placeholder: '请输入',
            showRequired: false,
            visibleIf: {
              expand: (value: boolean) => value
            }
          }
        },
        source: {
          type: 'string',
          title: '注册渠道',
          enum: [
            { label: '全部', value: '' },
            { label: '用户注册', value: 1 },
            { label: '货主添加', value: 2 },
            { label: '运营添加', value: 3},
          ],
          default: '',
          ui: {
            widget: 'select',
            visibleIf: {
              expand: (value: boolean) => value
            }
          }
        },
        lockedStatus: {
          type: 'string',
          title: '企业状态',
          enum: [
            { label: '全部', value: '' },
            { label: '正常', value: 0 },
            { label: '冻结', value: 1 }
          ],
          default: '',
          ui: {
            widget: 'select',
            visibleIf: {
              expand: (value: boolean) => value
            }
          }
        }
      }
    };
    this.ui = { '*': { spanLabelFixed: 110, grid: { lg: 8, md: 12, sm: 12, xs: 24 }, enter: () => this.st.load() } };
  }

  initST() {
    this.columns = [
      // { title: '', type: 'checkbox', className: 'text-center' },
      { title: '企业名称', className: 'text-center', index: 'enterpriseName' },
      { title: '管理员', className: 'text-center', render: 'contacter' },
      { title: '审核人', className: 'text-center', index: 'approvalUserName' },

      { title: '网络货运人', className: 'text-center', index: 'netTranName' },
      { title: '常用服务', className: 'text-center', index: 'oftenUsedServices', type: 'enum', enum: { 10: '整车发货', 20: '大宗发货' } },
      { title: '推广业务员', className: 'text-center', render: 'promotersTelephone' },
      { title: '注册渠道', className: 'text-center', index: 'source', type: 'enum', enum: { 1: '货主注册', 2: '平台添加', 3: '运营添加' } },
      {
        title: '企业状态',
        className: 'text-center',
        index: 'lockedStatus',
        type: 'badge',
        badge: {
          0: { text: '正常', color: 'success' },
          1: { text: '冻结', color: 'error' }
        }
      },
      {
        title: '操作',
        width: '110px',
        className: 'text-center',
        buttons: [
          {
            text: '查看<br/>',
            acl: { ability: ['USERCENTER-FREIGHT-LIST-view'] },
            click: item => {
              this.router.navigate(['./detail', item.id], { relativeTo: this.ar });
              // this.router.navigate(['./view', item.id], { relativeTo: this.ar, queryParams: { tenantId: item.tenantId } });
            }
          },
          {
            acl: { ability: ['USERCENTER-FREIGHT-LIST-basicSetting'] },
            text: '基础设置',
            click: item => this.settingAction(item)
          },
          {
            acl: { ability: ['USERCENTER-FREIGHT-LIST-balance'] },
            text: '资金账户',
            click: item => this.showAccountDetail(item)
          }
        ]
      }
    ];
  }
  daoyun(item: any) {
    this.router.navigate(['./view', item.tenantId], { relativeTo: this.ar });
  }

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

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

  exportList() {
    const params = { listSource: 1 };
    if (this.sf) {
      Object.assign(params, {
        ...this.sf.value
      });
    }
    this.service.downloadFile(this.service.$api_export_enterprise, params);
  }

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