import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { STChange, STColumn, STComponent, STData, STRequestOptions } 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';
import { AuditAdminComponent } from './audit-admin/audit-admin.component';

@Component({
  selector: 'app-Freight-components-enterprise-audit',
  templateUrl: './enterprise-audit.component.html',
  styleUrls: ['./enterprise-audit.component.less']
})
export class FreightComponentsEnterpriseAuditComponent implements OnInit {
  _$expand = false;
  ui: SFUISchema = { '*': { spanLabelFixed: 90, grid: { lg: 8, md: 12, sm: 12, xs: 24 } } };
  schema: SFSchema = this.initSF();
  enterColumns: STColumn[] = this.initEnterST();
  adminColumns: STColumn[] = this.initAdminST();
  @ViewChild('st', { static: false }) st!: STComponent;
  @ViewChild('sf', { static: false }) sf!: SFComponent;
  tabType = 1;
  tabs = [
    {
      name: '企业审核',
      type: 1,
      isActived: false
    },
    {
      name: '企业管理员审核',
      type: 2,
      isActived: false
    }
  ];

  @ViewChild('approvedModal', { static: false })
  approvedModal!: any;
  @ViewChild('redectModal', { static: false })
  redectModal!: any;
  ltdId: any = [];
  roles: any = [];
  customerServices: any = [];
  detailData: any = null;
  approvalOpinion = '';
  networkTransporter = null;
  roleId = null;
  customerServiceId = null;
  constructor(public service: UsermanageService, private router: Router, private modal: NzModalService) {}

  beforeReq = (requestOptions: STRequestOptions) => {
    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] || ''
          }
        });
      }
    }
    Object.assign(requestOptions.body, { flag: this.tabType, listSource: 2 });
    return requestOptions;
  };

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

  /**
   * 重置表单
   */
  resetSF() {
    this.sf.reset();
    this._$expand = false;
  }
  /**
   * 程序初始化入口
   */
  ngOnInit() {
    this.loadltdId();
    this.loadRoles();
    this.loadCustomerServices();
  }

  loadltdId() {
    this.service.getNetworkFreightForwarder().subscribe(res => {
      if (res) {
        this.ltdId = res;
      }
    });
  }
  loadRoles() {
    this.service.getRoles({ enterpriseId: 0, projectId: 0 }).subscribe(res => {
      if (res) {
        this.roles = res;
      }
    });
  }

  loadCustomerServices() {
    this.service.getStaffList({}, false).subscribe(res => {
      if (res) {
        this.customerServices = res;
      }
    });
  }

  /**
   * 查看详情
   */
  ViewAdimin(record: any, isReadOnly = false) {
    const modal = this.modal.create({
      nzTitle: isReadOnly ? '查看' : '审核',
      nzContent: AuditAdminComponent,
      nzWidth: 650,
      nzComponentParams: { i: { ...record }, isReadOnly },
      nzFooter: isReadOnly
        ? []
        : [
            {
              label: '驳回',
              type: 'primary',
              onClick: instance => {
                if (!instance?.sf.value.approvalOpinion) {
                  this.service.msgSrv.warning('请填写备注');
                  return false;
                }
                this.adminAuditUser(
                  {
                    id: record.id,
                    approvalStatus: '30',
                    approvalOpinion: instance?.sf.value.approvalOpinion
                  },
                  modal
                );
                return;
              }
            },
            {
              label: '通过',
              type: 'primary',
              onClick: () => {
                this.adminAuditUser(
                  {
                    id: record.id,
                    approvalStatus: '20'
                  },
                  modal
                );
              }
            }
          ]
    });
    modal.afterClose.subscribe(res => {
      // this.st.load(1);
    });
  }

  auditPass(item: any) {
    this.detailData = item;
    this.networkTransporter = null;
    this.roleId = null;
    this.modal.create({
      nzTitle: '审核通过',
      nzContent: this.approvedModal,
      nzOnOk: () => {
        if (!this.networkTransporter || !this.roleId || !this.customerServiceId) {
          return false;
        }
        this.auditEnterprise(20);
        return;
      }
    });
  }
  auditNo(item: any) {
    this.detailData = item;
    this.approvalOpinion = '';
    this.roleId = null;
    this.modal.create({
      nzTitle: '审核驳回',
      nzContent: this.redectModal,
      nzOnOk: () => {
        if (!this.approvalOpinion) {
          return false;
        }
        this.auditEnterprise(30);
        return;
      }
    });
  }

  private auditEnterprise(status: number) {
    this.service
      .request(this.service.$api_audit_freight, {
        approvalStatus: status,
        id: this.detailData.id,
        approvalOpinion: this.approvalOpinion,
        networkTransporter: this.networkTransporter,
        customerServiceId: this.customerServiceId,
        roleId: this.roleId || null
      })
      .subscribe(res => {
        if (res) {
          this.service.msgSrv.success(status === 20 ? '审核通过' : '驳回成功');
        }
        this.st.load(1);
      });
  }

  View(record: any) {
    this.router.navigate([`/usercenter/freight/enterprise/detail/${record.id}`]);
  }

  // 切换Tab
  changeTab(item: any) {
    this.tabType = item.type;
    this.expandToggle(false);
    this.sf?.reset();
    this.st.data = this.tabType === 1 ? this.service.$api_get_freight_list : this.service.$api_get_enterprise_admin_list;
    setTimeout(() => {
      this.st.load(1);
    }, 100);
  }

  private adminAuditUser(params: any, modal: any) {
    this.service.request(this.service.$api_audit_enterprise_admin, params).subscribe(res => {
      if (res) {
        this.service.msgSrv.success('审核成功');
        modal.destroy();
        this.st.load(1);
      }
    });
  }

  exportList() {
    const params = { ...this.sf.value, flag: this.tabType, listSource: 2,  pageSize: -1 };
    this.service.downloadFile(this.service.$api_export_enterprise, params);
  }

  /**
   * 初始化数据列表
   */
  initEnterST(): STColumn[] {
    return [
      { title: '企业名称', className: 'text-center', index: 'enterpriseName', width: 350 },
      { title: '统一社会信用代码', className: 'text-center', index: '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', index: 'contacter', width: 150, format: item => `${item.contacter}<br>/${item.mobile}` },
      {
        title: '常用服务',
        className: 'text-center',
        index: 'oftenUsedServices',
        type: 'enum',
        enum: { 10: '整车发货', 20: '大宗发货' },
        width: 140
      },
      { title: '业务员', className: 'text-center', index: 'promotersTelephone', width: 150 },
      {
        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',
        render: 'approvalStatus',
        width: 160
      },
      {
        title: '常用服务',
        className: 'text-center',
        index: 'oftenUsedServices',
        type: 'enum',
        enum: { 10: '整车发货', 20: '大宗发货' },
        width: 140
      },
      { title: '推广业务员', className: 'text-center', index: 'promotersTelephone', width: 150 },
      {
        title: '操作',
        fixed: 'right',
        width: '180px',
        className: 'text-center',
        buttons: [
          { text: '查看', click: _record => this.View(_record), acl: { ability: ['USERCENTER-FREIGHT-ENTERPRISE-view'] } },
          {
            text: '通过',
            click: _record => this.auditPass(_record),
            acl: { ability: ['USERCENTER-FREIGHT-ENTERPRISE-D-audit'] },
            iif: item => item.approvalStatus === 10
          },
          {
            text: '驳回',
            click: _record => this.auditNo(_record),
            acl: { ability: ['USERCENTER-FREIGHT-ENTERPRISE-D-audit'] },
            iif: item => item.approvalStatus === 10
          }
        ]
      }
    ];
  }

  initAdminST(): STColumn[] {
    return [
      { title: '企业名称', className: 'text-center', index: 'enterpriseName' },
      { title: '当前管理员', className: 'text-center', index: 'oldAdminName', width: 140 },
      { title: '当前管理员手机号', className: 'text-center', index: 'oldAdminMobile', width: 170 },
      { title: '转授对象', className: 'text-center', index: 'newAdminName', width: 140 },
      { title: '转授对象手机号', className: 'text-center', index: 'newAdminMobile', width: 150 },
      { title: '申请时间', className: 'text-center', index: 'createTime', width: 170 },
      {
        title: '状态',
        className: 'text-center',
        index: 'approvalStatus',
        type: 'badge',
        badge: {
          10: { text: '待审核', color: 'processing' },
          20: { text: '已成功', color: 'success' },
          30: { text: '已驳回', color: 'warning' }
        },
        width: 130
      },
      {
        title: '操作',
        fixed: 'right',
        width: '180px',
        className: 'text-center',
        buttons: [
          {
            text: '审核',
            click: _record => this.ViewAdimin(_record),
            acl: { ability: ['USERCENTER-FREIGHT-ENTERPRISE-adminAudit'] },
            iif: (item: any) => item.approvalStatus === 10
          },
          {
            text: '查看',
            click: _record => this.ViewAdimin(_record, true)
          }
        ]
      }
    ];
  }

  /**
   * 初始化查询表单
   */
  initSF(): SFSchema {
    return {
      properties: {
        expand: { type: 'boolean', ui: { hidden: true } },
        enterpriseName: {
          title: '企业名称',
          type: 'string',
          ui: {
            placeholder: '请输入'
          }
        },
        contactName: {
          title: '管理员',
          type: 'string',
          ui: {
            placeholder: '请输入'
          }
        },
        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',
            visibleIf: {
              expand: (value: boolean) => this.tabType === 1
            }
          }
        },
        enterpriseAddressCode: {
          type: 'string',
          title: '公司所在地',
          enum: [{ label: '全部', value: '' }],
          default: '',
          ui: {
            widget: 'select',
            visibleIf: {
              expand: (value: boolean) => this.tabType === 1 && value
            }
          }
        },
        oftenUsedServices: {
          type: 'string',
          title: '常用服务',
          enum: [
            { label: '全部', value: '' },
            { label: '整车发货', value: 10 },
            { label: '大宗发货', value: 20 }
          ],
          default: '',
          ui: {
            widget: 'select',
            visibleIf: {
              expand: (value: boolean) => this.tabType === 1 && value
            }
          }
        },
        // approval11St11atus: {
        //   type: 'string',
        //   title: '客户类型',
        //   enum: [{ label: '全部', value: '' }],
        //   default: '',
        //   ui: {
        //     widget: 'select',
        //     visibleIf: {
        //       expand: (value: boolean) => this.tabType === 1 && value
        //     }
        //   }
        // },
        promotersTelephone: {
          title: '业务员',
          type: 'string',
          ui: {
            placeholder: '请输入',
            showRequired: false,
            visibleIf: {
              expand: (value: boolean) => this.tabType === 1 && value
            }
          }
        },
        mobile: {
          title: '手机号',
          type: 'string',
          maxLength: 11,
          ui: {
            placeholder: '请输入',
            visibleIf: {
              expand: (value: boolean) => this.tabType === 2
            }
          }
        },
        approvalUserName: {
          title: '审核人',
          type: 'string',
          maxLength: 11,
          ui: {
            placeholder: '请输入',
            visibleIf: {
              expand: (value: boolean) => this.tabType === 1 && 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) => this.tabType === 1 && value
            }
          } as SFDateWidgetSchema
        },
        approvalStatus: {
          type: 'string',
          title: '审核状态',
          enum: [
            { label: '全部', value: '' },
            { label: '待审核', value: 10 },
            { label: '已撤销', value: 15 },
            { label: '已成功', value: 20 },
            { label: '审核失败', value: 30 }
          ],
          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) => this.tabType === 1 && value
            }
          }
        }
      }
    };
  }
}
