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, SFDateWidgetSchema, 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';
import { EditPartnerComponentsAddComponent } from './editPartner/editPartner.component';
import { EditSaleComponentsAddComponent } from './editSale/editSale.component';
import { ShowServiceComponent } from './showService/showservice.component';
@Component({
  selector: 'app-Freight-components-list',
  templateUrl: './list.component.html',
  styleUrls: ['../../../../commom/less/expend-but.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
      });
      if (this.sf.value.createTime) {
        Object.assign(requestOptions.body, {
          createTime: {
            start: this.sf.value.createTime[0],
            end: this.sf.value.createTime[1]
          }
        });
      }
      if (this.sf.value.approvalTime) {
        Object.assign(requestOptions.body, {
          approvalTime: {
            start: this.sf.value.approvalTime[0],
            end: this.sf.value.approvalTime[1]
          }
        });
      }
    }
    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/getShipperAccountDetailByOperator',
        params: {
          accountType: 1,
          roleId: item.id,
          ctfId: item.unifiedSocialCreditCode,
          clientName: item.enterpriseName,
          projectId: item.mainProjectId,
          ltdId: item.networkTransporter
        }
      },
      nzFooter: null
    });
  }
  showService(record: any) {
    const modalRef = this.modal.create({
      nzTitle: '分配客服人员',
      nzContent: ShowServiceComponent,
      nzWidth: 600,
      nzComponentParams: {
        i: record
      },
      nzFooter: null
    });
    modalRef.afterClose.subscribe((res: any) => {
      if (res) {
        this.st.load(1);
      }
    });
  }
  editPartner(record: any) {
    const modalRef = this.modal.create({
      nzTitle: '修改合伙人',
      nzContent: EditPartnerComponentsAddComponent,
      nzWidth: 800,
      nzComponentParams: {
        i: record
      },
      nzFooter: null
    });
    modalRef.afterClose.subscribe((res: any) => {
      if (res) {
        this.st.load(1);
      }
    });
  }
  editSale(record: any) {
    const modalRef = this.modal.create({
      nzTitle: '修改渠道销售',
      nzContent: EditSaleComponentsAddComponent,
      nzWidth: 800,
      nzComponentParams: {
        i: record
      },
      nzFooter: null
    });
    modalRef.afterClose.subscribe((res: any) => {
      if (res) {
        this.st.load(1);
      }
    });
  }
  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
          }
        },
        enterpriseType: {
          type: 'string',
          title: '企业类型',
          enum: [
            { label: '全部', value: '' },
            { label: '物流企业', value: 1 },
            { label: '货运代理', value: 2 },
            { label: '生产型企业', value: 3 },
            { label: '贸易类企业', value: 4 },
            { label: '科技型企业', value: 5 },
            { label: '化学化工企业', value: 6 },
            { label: '其他', value: 7 }
          ],
          default: '',
          ui: {
            widget: 'select'
          }
        },
        enterpriseAddressCode: {
          type: 'string',
          title: '公司所在地',
          enum: [{ label: '全部', value: '' }],
          default: '',
          ui: {
            widget: 'select',
            visibleIf: {
              expand: (value: boolean) => value
            }
          }
        },
        oftenUsedServices: {
          type: 'string',
          title: '常用服务',
          enum: [
            { label: '全部', value: '' },
            { label: '整车发货', value: 10 },
            { label: '大宗发货', value: 20 }
          ],
          default: '',
          ui: {
            widget: 'select',
            visibleIf: {
              expand: (value: boolean) => value
            }
          }
        },
        customerType: {
          type: 'string',
          title: '客户类型',
          enum: [
            { label: '全部', value: '' },
            { label: '直客', value: 1 },
            { label: '渠道客户', value: 20 }
          ],
          default: '',
          ui: {
            widget: 'select',
            visibleIf: {
              expand: (value: boolean) => value
            }
          }
        },
        promotersTelephone: {
          title: '业务员',
          type: 'string',
          ui: {
            placeholder: '请输入',
            showRequired: false,
            visibleIf: {
              expand: (value: boolean) => value
            }
          }
        },
        partnerNamee: {
          title: '合伙人',
          type: 'string',
          ui: {
            placeholder: '请输入',
            showRequired: false,
            visibleIf: {
              expand: (value: boolean) => value
            }
          }
        },
        customerServiceId: {
          title: '客服人员',
          type: 'string',
          ui: {
            placeholder: '请输入',
            showRequired: false,
            visibleIf: {
              expand: (value: boolean) => value
            }
          }
        },
        approvalUserName: {
          title: '审核人',
          type: 'string',
          ui: {
            placeholder: '请输入',
            showRequired: false,
            visibleIf: {
              expand: (value: boolean) => value
            }
          }
        },
        createTime: {
          title: '申请时间',
          type: 'string',
          ui: {
            widget: 'sl-from-to-search',
            format: 'yyyy-MM-dd HH:mm:ss',
            nzShowTime: true,
            visibleIf: {
              expand: (value: boolean) => value
            }
          } as SFDateWidgetSchema
        },
        approvalTime: {
          title: '审核时间',
          type: 'string',
          ui: {
            widget: 'sl-from-to-search',
            format: 'yyyy-MM-dd HH:mm:ss',
            nzShowTime: true,
            visibleIf: {
              expand: (value: boolean) => value
            }
          } as SFDateWidgetSchema
        },
        lockedStatus: {
          type: 'string',
          title: '企业状态',
          enum: [
            { label: '全部', value: '' },
            { label: '正常', value: 0 },
            { label: '冻结', value: 1 }
          ],
          default: '',
          ui: {
            widget: 'select',
            visibleIf: {
              expand: (value: boolean) => value
            }
          }
        },
        source: {
          type: 'string',
          title: '注册渠道',
          enum: [
            { label: '全部', value: '' },
            { label: '货主注册', value: 1 },
            { label: '平台添加', value: 2 }
          ],
          default: '',
          ui: {
            widget: 'select',
            visibleIf: {
              expand: (value: boolean) => value
            }
          }
        },
        isExpired: {
          type: 'string',
          title: '证件是否过期',
          enum: [
            { label: '全部', value: '' },
            { label: '是', value: true },
            { label: '否', value: false }
          ],
          default: '',
          ui: {
            widget: 'select',
            visibleIf: {
              expand: (value: boolean) => value
            }
          }
        },
        networkTransporter: {
          type: 'string',
          title: '网络货运人',
          ui: {
            widget: 'select',
            placeholder: '请选择',
            allowClear: true,
            asyncData: () => this.shipperservice.getNetworkFreightForwarder(),
            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: '企业名称', render: 'enterpriseName', width: 350 },
      { title: '统一社会信用代码', className: 'text-center', render: 'unifiedSocialCreditCode', width: 200 },
      {
        title: '公司所在地',
        className: 'text-center',
        index: 'province',
        width: 200,
        format: item => `${item.provinceName}${item.cityName}${item.areaName}`
      },
      {
        title: '企业类型',
        className: 'text-center',
        index: 'enterpriseType',
        width: 200,
        type: 'enum',
        enum: { 1: '物流企业', 2: '货运代理', 3: '生产型企业', 4: '贸易类企业', 5: '科技型企业', 6: '化学化工企业', 7: '其他' }
      },
      { title: '管理员', className: 'text-center', render: 'contacter', width: 150 },
      {
        title: '常用服务',
        className: 'text-center',
        index: 'oftenUsedServices',
        type: 'enum',
        enum: { 10: '整车发货', 20: '大宗发货' },
        width: 140
      },
      { title: '业务员', className: 'text-center', render: 'promotersTelephone', width: 150 },
      { title: '合伙人', className: 'text-center', render: 'partnerName', width: 150 },
      { title: '客服人员', className: 'text-center', index: 'customerServiceIdLabel', width: 150 },
      { title: '网络货运人', className: 'text-center', index: 'netTranName', width: 180 },
      {
        title: '注册渠道',
        className: 'text-center',
        index: 'source',
        type: 'enum',
        enum: { 1: '货主注册', 2: '平台添加', 3: '运营添加' },
        width: 130
      },
      { title: '申请时间', className: 'text-center', index: 'createTime', width: 180, type: 'date' },
      { title: '审核时间', className: 'text-center', index: 'approvalTime', width: 180, type: 'date' },
      { title: '审核人', className: 'text-center', index: 'approvalUserName', width: 130 },
      {
        title: '保险认证状态',
        className: 'text-center',
        index: 'insuranceAuthState',
        type: 'badge',
        badge: {
          10: { text: '成功', color: 'success' },
          20: { text: '失败', color: 'error' }
        },
        width: 130
      },
      {
        title: '企业状态',
        className: 'text-center',
        index: 'lockedStatus',
        type: 'badge',
        badge: {
          0: { text: '正常', color: 'success' },
          1: { text: '冻结', color: 'error' }
        },
        width: 130
      },
      {
        title: '操作',
        width: '200px',
        className: 'text-center block-td',
        fixed: 'right',
        buttons: [
          {
            text: '查看',
            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)
          },
          {
            text: '分配客服人员',
            click: item => this.showService(item)
          },
          {
            text: '修改合伙人',
            click: item => this.editPartner(item)
          },
          {
            text: '修改渠道销售',
            click: item => this.editSale(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, pageSize: -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();
  }
}
