import { Component, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { STComponent, STColumn, STRequestOptions, STChange } from '@delon/abc/st';
import { SFComponent, SFSchema, SFDateWidgetSchema, SFAutoCompleteWidgetSchema, SFSelectWidgetSchema } from '@delon/form';
import { NzModalService } from 'ng-zorro-antd/modal';
import { of } from 'rxjs';
import { AddCollectionInvoiceModalComponent } from 'src/app/routes/ticket-management/components/input-invoice/add-collection-invoice-modal/add-collection-invoice-modal.component';

import { PartnerListService } from '../../services/partner-list.service';
import { PartnerAuditModalComponent } from '../partner-audit-modal/partner-audit-modal.component';

@Component({
  selector: 'app-partner-list',
  templateUrl: './partner-list.component.html',
  styleUrls: ['../../../../commom/less/box.less']
})
export class PartnerListComponent {
  @ViewChild('st', { static: true })
  st!: STComponent;
  @ViewChild('sf', { static: false })
  sf!: SFComponent;
  columns: STColumn[] = this.initST();
  searchSchema: SFSchema = this.initSF();
  _$expand = false;

  @ViewChild('editTemplate', { static: true })
  editTemplate: any;
  templateId: any;
  templates: any[] = [];

  @ViewChild('editCannel', { static: true })
  editCannel: any;
  customers: any[] = [];
  cannels: any[] = [];
  selectedRows: any[] = [];
  cannelItem: any = { channelId: null, effectiveNode: 1, enterpriseIdList: [], remark: '' };

  selectItem: any = {};

  constructor(public service: PartnerListService, private nzModalService: NzModalService, private router: Router) {
    this.loadSelectOptions();
  }

  beforeReq = (requestOptions: STRequestOptions) => {
    if (this.sf) {
      let params = { ...this.sf.value };
      if (params.createTime) {
        params.createTime = { start: this.sf?.value?.createTime?.[0], end: this.sf?.value?.createTime?.[1] };
      }
      Object.assign(requestOptions.body, params);
    }
    return requestOptions;
  };

  loadSelectOptions() {
    this.service.getRebateConfig().subscribe(res => {
      if (res) {
        this.customers = res;
      }
    });
    this.service.getChannel().subscribe(res => {
      if (res) {
        this.cannels = res;
      }
    });
  }

  auditPartner(item: any) {
    const modal = this.nzModalService.create({
      nzTitle: '审核',
      nzContent: PartnerAuditModalComponent,
      nzComponentParams: { info: { ...item, enterpriseName: item.enterpriseName || item.contactName }, sourcePage: '合伙人审核列表' },
      nzFooter: null
    });
    modal.afterClose.subscribe(res => {
      if (res) {
        this.st.load(1);
      }
    });
  }

  editTemplateAction(item: any) {
    this.selectItem = item;
    this.templateId = item.templateId || null;
    const modal = this.nzModalService.create({
      nzTitle: '修改返佣模板',
      nzContent: this.editTemplate,
      nzOnOk: () => {
        if (!this.templateId) {
          this.service.msgSrv.warning('请选择返佣模板');
          return false;
        }
        this.confirmEditTemplate();
        return false;
      }
    });
  }

  private confirmEditTemplate() {
    const modal = this.nzModalService.confirm({
      nzTitle: '确定要修改返佣模板吗？',
      nzOnOk: () => {
        this.service
          .request(this.service.$api_update_partner_template, {
            id: this.selectItem.id,
            templateId: this.templateId
          })
          .subscribe(res => {
            if (res) {
              this.service.msgSrv.success('修改成功');
              this.st.load(1);
              this.nzModalService.closeAll();
            }
          });
        return false;
      }
    });
  }

  stChange(e: STChange): void {
    switch (e.type) {
      case 'checkbox':
        this.selectedRows = e.checkbox!;
        break;
    }
  }

  editCannelAction(item: any) {
    this.selectItem = item;
    this.cannelItem = { channelId: null, effectiveNode: 1, enterpriseIdList: [], remark: '' };
    this.selectedRows = [];
    // 校验合伙人是否可修改渠道销售 true:可以修改 false：不可以修改
    this.service.request(this.service.$api_check_partenr_change_channel, { id: item.id }).subscribe(res => {
      if (res) {
        this.selectItem = item;
        const modal = this.nzModalService.create({
          nzTitle: '修改渠道销售',
          nzWidth: 650,
          nzContent: this.editCannel,
          nzOnOk: () => {
            if (!this.cannelItem.channelId) {
              this.service.msgSrv.warning('请选择渠道销售');
              return false;
            }
            if (!this.cannelItem.remark) {
              this.service.msgSrv.warning('请填写备注');
              return false;
            }
            this.confirmEditCannel(item);
            return false;
          }
        });
      }
    });
  }

  confirmEditCannel(item: any) {
    const modal = this.nzModalService.confirm({
      nzTitle: '确定提交吗？',
      nzOnOk: () => {
        this.cannelItem.enterpriseIdList = this.selectedRows.map(row => row.id);
        this.service
          .request(this.service.$api_update_partner_channel_by_id, {
            ...this.cannelItem,
            id: item.id
          })
          .subscribe(res => {
            if (res) {
              this.service.msgSrv.success('修改成功');
              this.nzModalService.closeAll();
              this.st.load(1);
            }
          });
      }
    });
  }

  /**
   * 重新发起crm
   * @param item
   */
  reSendCRM(item: any) {
    const modal = this.nzModalService.confirm({
      nzTitle: '是否确定重新发起CRM？',
      nzOnOk: () => {
        this.service
          .request(this.service.$api_resend_crm, {
            id: item.id
          })
          .subscribe(res => {
            if (res) {
              this.service.msgSrv.success('发起成功');
            } else {
              this.service.msgSrv.warning('发起失败');
            }
            this.st.load(1);
          });
      }
    });
  }

  routeTo(route: string) {
    this.router.navigate([route]);
  }

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

  /**
   * 伸缩查询条件
   */
  expandToggle() {
    this._$expand = !this._$expand;
    this.sf?.setValue('/expand', this._$expand);
  }

  private initSF(): SFSchema {
    return {
      properties: {
        expand: {
          type: 'boolean',
          ui: {
            hidden: true
          }
        },
        enterpriseName: {
          type: 'string',
          title: '合伙人名称'
        },
        contactName: {
          type: 'string',
          title: '企业管理员'
        },
        contactMobile: {
          type: 'string',
          title: '手机号'
        },
        channelId: {
          type: 'string',
          title: '渠道销售',
          ui: {
            widget: 'select',
            searchDebounceTime: 300,
            searchLoadingText: '搜索中...',
            allowClear: true,
            visibleIf: {
              expand: (value: boolean) => value
            },
            onSearch: (q: any) => {
              let str = q.replace(/^\s+|\s+$/g, '');
              if (str) {
                return this.service.getChannel({ name: str }).toPromise();
              } else {
                return of([]);
              }
            }
          } as SFSelectWidgetSchema
        },
        partnerType: {
          type: 'string',
          title: '类型',
          enum: [
            { value: '', label: '全部' },
            { value: 1, label: '企业' },
            { value: 2, label: '个人' }
          ],
          ui: {
            widget: 'select',
            placeholder: '请选择',
            visibleIf: {
              expand: (value: boolean) => value
            }
          },
          default: ''
        },
        approvalStatus: {
          type: 'string',
          title: '认证审核状态',
          ui: {
            widget: 'dict-select',
            containsAllLabel: true,
            params: { dictKey: 'pay:mode' },
            placeholder: '请选择',
            visibleIf: {
              expand: (value: boolean) => value
            }
          }
        },
        signStatus: {
          type: 'string',
          title: '签约状态',
          ui: {
            widget: 'dict-select',
            containsAllLabel: true,
            params: { dictKey: 'pay:mode' },
            placeholder: '请选择',
            visibleIf: {
              expand: (value: boolean) => value
            }
          }
        },
        crmStatus: {
          type: 'string',
          title: 'CRM状态',
          ui: {
            widget: 'dict-select',
            containsAllLabel: true,
            params: { dictKey: 'pay:mode' },
            placeholder: '请选择',
            visibleIf: {
              expand: (value: boolean) => value
            }
          }
        },
        paymo11de: {
          type: 'string',
          title: '注册渠道',
          enum: [
            { value: '', label: '全部' },
            { value: 1, label: '合伙人注册' },
            { value: 2, label: '平台添加' }
          ],
          ui: {
            widget: 'select',
            placeholder: '请选择',
            visibleIf: {
              expand: (value: boolean) => value
            }
          },
          default: ''
        },
        templateId: {
          type: 'string',
          title: '返佣模板',
          ui: {
            widget: 'select',
            placeholder: '请选择',
            visibleIf: {
              expand: (value: boolean) => value
            }
          }
        },
        lockedStatus: {
          type: 'string',
          title: '合伙人状态',
          enum: [
            { value: '', label: '全部' },
            { value: 0, label: '启用' },
            { value: 1, label: '冻结' }
          ],
          ui: {
            widget: 'select',
            placeholder: '请选择',
            visibleIf: {
              expand: (value: boolean) => value
            }
          },
          default: ''
        },
        createTime: {
          title: '注册时间',
          type: 'string',
          ui: {
            widget: 'sl-from-to-search',
            format: 'yyyy-MM-dd',
            visibleIf: {
              expand: (value: boolean) => value
            }
          } as SFDateWidgetSchema
        }
      }
    };
  }

  private initST(): STColumn[] {
    return [
      {
        title: '合伙人名称',
        index: 'enterpriseName',
        width: 180,
        format: item => (item.partnerType ? `${item.enterpriseName || item.contactName}` : '')
      },
      { title: '付款编码', index: 'payCode', width: 160 },
      { title: '邀请码', index: 'invitationCode', className: 'text-center', width: 130 },
      { title: '企业管理员', index: 'contactName', width: 150, format: item => (item.partnerType ? `${item.contactName}` : '') },
      { title: '手机号', index: 'contactMobile', className: 'text-center', width: 150 },
      { title: '类型', index: 'partnerType', className: 'text-center', width: 130, type: 'enum', enum: { 1: '企业', 2: '个人' } },
      { title: '注册渠道', index: 'source', type: 'enum', enum: { 1: '合伙人注册', 2: '平台添加' }, width: 130 },
      { title: '注册时间', index: 'createTime', className: 'text-center', width: 170 },
      { title: '渠道销售', index: 'channelIdLabel', width: 170 },
      { title: '返佣模板', index: 'templateName', width: 150 },
      {
        title: '认证审核状态',
        index: 'approvalStatus',
        width: 150,
        type: 'badge',
        badge: {
          '-1': { text: '未提交', color: 'default' },
          10: { text: '待审核', color: 'processing' },
          20: { text: '审核通过', color: 'success' },
          30: { text: '驳回', color: 'error' }
        }
      },
      {
        title: '签约状态',
        index: 'signStatus',
        width: 150,
        type: 'badge',
        badge: {
          0: { text: '未发起', color: 'default' },
          10: { text: '待合伙人签约', color: 'default' },
          15: { text: '签约中', color: 'processing' },
          20: { text: '平台签约完成', color: 'success' },
          30: { text: '驳回', color: 'error' }
        }
      },
      {
        title: 'CRM状态',
        index: 'crmStatus',
        width: 150,
        type: 'badge',
        badge: {
          0: { text: '未发起', color: 'default' },
          10: { text: '审核失败', color: 'error' },
          20: { text: '审核通过', color: 'success' }
        }
      },
      {
        title: '合伙人状态',
        index: 'lockedStatus',
        className: 'text-center',
        width: 140,
        type: 'badge',
        badge: {
          0: { text: '启用', color: 'success' },
          1: { text: '冻结', color: 'error' }
        }
      },
      {
        title: '操作',
        fixed: 'right',
        width: '150px',
        buttons: [
          { type: 'divider' },
          {
            text: '审核',
            iif: item => item.id && item.approvalStatus === 10,
            click: item => this.auditPartner(item)
          },
          {
            text: '详情<br>',
            iif: item => item.id,
            click: item => {
              if (item.partnerType === 1) {
                this.router.navigate([`/partner/partner-list/etp-detail/${item.id}`]);
              } else {
                this.router.navigate([`/partner/partner-list/personal-detail/${item.id}`]);
              }
            }
          },
          {
            text: '修改返佣模板',
            iif: item => item.id,
            click: item => this.editTemplateAction(item)
          },
          {
            text: '修改渠道销售',
            iif: item => item.id,
            click: item => this.editCannelAction(item)
          },
          {
            text: '重发CRM流程',
            click: item => item.id && this.reSendCRM(item),
            iif: item => item.crmStatus === 10
          }
        ]
      }
    ];
  }
}
