import {Component, OnInit} from '@angular/core';
import {environment} from "../../../../environments/environment";
import {ReactiveFormsModule, UntypedFormBuilder, UntypedFormGroup, Validators} from "@angular/forms";
import {NzUploadComponent, NzUploadFile} from "ng-zorro-antd/upload";
import {NzModalComponent, NzModalModule, NzModalService} from "ng-zorro-antd/modal";
import {NzMessageService} from "ng-zorro-antd/message";
import {MerService} from "../../../services/mer.service";
import {MerPlatformService} from "../../../services/mer-platform.service";
import {SalesmanService} from "../../../services/salesman.service";
import {ADMIN_INFO_OBJECT} from "../../../services/local-storage.namespace";
import {NzOptionComponent, NzSelectComponent} from "ng-zorro-antd/select";
import {
  NzFormControlComponent,
  NzFormDirective,
  NzFormItemComponent,
  NzFormLabelComponent,
  NzFormModule
} from "ng-zorro-antd/form";
import {NzInputDirective} from "ng-zorro-antd/input";
import {NzColDirective, NzRowDirective} from "ng-zorro-antd/grid";
import {BreadcrumbComponent} from "../../common/breadcrumb/breadcrumb.component";
import {DatePipe, NgForOf, NgIf} from "@angular/common";
import {NzButtonComponent} from "ng-zorro-antd/button";
import {NzIconDirective} from "ng-zorro-antd/icon";
import {
  NzCellFixedDirective,
  NzTableComponent, NzTableModule,
  NzTdAddOnComponent,
  NzThMeasureDirective,
  NzThSelectionComponent
} from "ng-zorro-antd/table";
import {MerStatusPipe} from "../../../pipes/mer/mer-status.pipe";
import {CompleteStatusPipe} from "../../../pipes/mer/complete-status.pipe";
import {NzDropDownDirective, NzDropdownMenuComponent} from "ng-zorro-antd/dropdown";
import {NzMenuDirective, NzMenuItemComponent} from "ng-zorro-antd/menu";
import {RouterLink} from "@angular/router";
import {NzTabComponent, NzTabSetComponent} from "ng-zorro-antd/tabs";
import {MerTypePipe} from "../../../pipes/mer/mer-type.pipe";
import {NzTooltipDirective} from "ng-zorro-antd/tooltip";
import {BrowserStorageService} from "../../../utils/localStorage.service";
import {NzSpinModule} from "ng-zorro-antd/spin";
import {NzRadioComponent, NzRadioGroupComponent} from "ng-zorro-antd/radio";
import {NzDatePickerModule} from "ng-zorro-antd/date-picker";

@Component({
  selector: 'app-mer-list',
  standalone: true,
  imports: [
    NzOptionComponent,
    NzFormDirective,
    NzModalComponent,
    NzFormItemComponent,
    NzFormLabelComponent,
    NzFormControlComponent,
    NzSelectComponent,
    NzInputDirective,
    NzColDirective,
    BreadcrumbComponent,
    NzRowDirective,
    ReactiveFormsModule,
    NgForOf,
    NzButtonComponent,
    NzIconDirective,
    NzTableComponent,
    NzThMeasureDirective,
    NzThSelectionComponent,
    NzTdAddOnComponent,
    MerStatusPipe,
    CompleteStatusPipe,
    DatePipe,
    NzDropdownMenuComponent,
    NzMenuDirective,
    RouterLink,
    NgIf,
    NzMenuItemComponent,
    NzTabSetComponent,
    NzTabComponent,
    NzUploadComponent,
    MerTypePipe,
    NzCellFixedDirective,
    NzDropDownDirective,
    NzTooltipDirective,
    NzModalModule,
    NzTableModule,
    NzFormModule,
    NzSpinModule,
    NzRadioGroupComponent,
    NzRadioComponent,
    NzDatePickerModule
  ],
  templateUrl: './mer-list.component.html',
  styleUrl: './mer-list.component.less'
})
export class MerListComponent implements OnInit {
  BASE_URL = environment.baseUrl;
  roleType: number;

  platformConfigModal = false;

  dataObject: any = {};
  tableLoading = true;
  searchForm: UntypedFormGroup;
  pageNum: number;
  whereObject: any = {};

  ccbConfigForm: UntypedFormGroup;
  ccbFileArray: NzUploadFile[] = [];

  salesmanArray = [];

  allChecked = false;
  checkedData = [];

  merMigrateSalesmanModal = false;
  merMigrateSalesmanForm: UntypedFormGroup;

  constructor(private modal: NzModalService,
              private message: NzMessageService,
              private merService: MerService,
              private merPlatformService: MerPlatformService,
              private salesmanService: SalesmanService,
              private store: BrowserStorageService,
              private form: UntypedFormBuilder) {
    this.roleType = this.store.get(ADMIN_INFO_OBJECT)['secRole'].roleType;
  }

  ngOnInit(): void {
    this.searchForm = this.form.group({
      merNo: [null],
      merName: [null],
      merType: [null],
      merStatus: [null],
      regPhone: [null],
      regName: [null],
      salesmanId: [null],
    });
    this.requestData(1);

    this.salesmanService.querySalesmanList({ pageNum: 1, pageSize: 999}, data => {
      this.salesmanArray = data['return_data']['list'];
    });

    this.ccbConfigForm = this.form.group({
      merId: [null],
      platformType: [null],
      platformNo: [null, [Validators.required]],
      posId: [null, [Validators.required]],
      branchId: [null, [Validators.required]],
      merPublicKey: [null, [Validators.required]],
      platformOperatorId: [null, [Validators.required]],
      platformOperatorPwd: [null, [Validators.required]],
      refundCertUrl: [null],
      refundCertPwd: [null, [Validators.required]],
    });

    this.merMigrateSalesmanForm = this.form.group({
      salesmanId: [null, [Validators.required]],
    });
  }

  /**
   * 请求数据
   */
  requestData(pageNum) {
    this.tableLoading = true;
    this.whereObject['pageNum'] = pageNum;
    this.whereObject['pageSize'] = 10;
    this.merService.getMerList(this.whereObject, data => {
      if (data['return_code'] === '000000') {
        this.dataObject = data['return_data'];
      } else {
        this.modal.error(data['return_msg']);
      }
      this.tableLoading = false;
    });
  }

  /**
   * 搜索
   * @param whereObject 条件
   */
  search(whereObject: object) {
    this.whereObject = whereObject;
    this.requestData(1);
  }

  /**
   * 重置
   */
  resetForm(): void {
    this.searchForm.reset();
  }

  /**
   * 审核失败原因
   * @param merId 商户id
   */
  auditFail(merId: number) {
    this.merService.getMerDetail(merId, data => {
      if (data['return_code'] === '000000') {
        this.modal.error({
          nzTitle: '审核失败',
          nzContent: '<p>失败原因：' + data['return_data']['merContractFailMsg']['response_msg'] + '</p>' +
            '<p>' + '审核时间：' + new Date(data['return_data']['merContractFailMsg']['create_time']).toLocaleString()  + '</p>'
        });
      } else {
        this.modal.error({
          nzTitle: '查询失败',
          nzContent: data['return_msg']
        });
      }
    });
  }

  /**
   * 展示平台配置模态框
   * @param merId 商户id
   */
  showPlatformConfig(merId: number) {
    this.merPlatformService.getMerPlatformNo(merId, 3, data => {
      if (data['return_code'] === '000000') {
        if (data['return_data'] != null) {
          this.ccbConfigForm.patchValue(data['return_data']);
          // 退款证书地址
          if (data['return_data']['refundCertUrl'] != null) {
            const array: NzUploadFile[] = [
              {
                uid: new Date().getTime() + '',
                name: data['return_data']['refundCertUrl'].substring(data['return_data']['refundCertUrl'].lastIndexOf('/') + 1),
                status: 'done',
                filename: data['return_data']['refundCertUrl']
              }
            ];
            this.ccbFileArray = array;
          }

        } else {
          this.ccbConfigForm.patchValue({ merId: merId});
        }
      }
    });
    this.platformConfigModal = true;
  }

  /**
   * 展示平台配置模态框
   * @param merId 商户id
   */
  closePlatformConfig() {
    this.ccbConfigForm.reset({});
    this.ccbFileArray = [];
    this.platformConfigModal = false;
  }

  /**
   * 保存建行支付配置
   */
  saveCCBConfig() {
    for (const i in this.ccbConfigForm.controls) {
      this.ccbConfigForm.controls[i].markAsDirty();
      this.ccbConfigForm.controls[i].updateValueAndValidity();
    }
    if (this.ccbConfigForm.status == null || this.ccbConfigForm.status !== 'VALID') {
      this.modal.warning({
        nzTitle: '提示',
        nzContent: '请规范填写所有的必填项信息',
      });
      return;
    }
    if (this.ccbFileArray.length === 0) {
      this.modal.warning({
        nzTitle: '提示',
        nzContent: '请规上传证书文件',
      });
      return;
    }
    this.ccbConfigForm.value.platformType = 3;
    this.ccbConfigForm.value.refundCertUrl = this.ccbFileArray[0].filename;

    this.merPlatformService.configMerPlatformNo(this.ccbConfigForm.value, data => {
      if (data['return_code'] === '000000') {
        this.modal.success({
          nzTitle: '提示',
          nzContent: '配置成功',
        });
      } else {
        this.modal.error({
          nzTitle: '提示',
          nzContent: data['return_msg'],
        });
      }
    });

  }


  ccbFileCandleChange(info: { file: NzUploadFile }): void {
    switch (info.file.status) {
      case 'uploading':
        break;
      case 'done':
        const array: NzUploadFile[] = [
          {
            uid: new Date().getTime() + '',
            name: info.file.response.return_data[0].substring(info.file.response.return_data[0].lastIndexOf('/') + 1),
            status: 'done',
            filename: info.file.response.return_data[0]
          }
        ];
        this.ccbFileArray = array;
        break;
      case 'error':
        this.modal.error({
          nzTitle: '提示',
          nzContent: '上传失败'
        });
        break;
    }
  }



  /**
   * 选中
   * @param data
   * @param checked
   */
  checkedChange(data: object, checked: boolean) {
    if (checked === true) {
      if (this.checkedData.find(o => Number(o['id']) === Number(data['id'])) == null) {
        data['checked'] = true;
        this.checkedData.push(data);
      }
    } else {
      data['checked'] = true;
      const findIndex = this.checkedData.findIndex(o => Number(o['id']) === Number(data['id']));
      this.checkedData.splice(findIndex, 1);
    }
  }

  /**
   * 全选
   * @param data
   */
  onAllChecked(checked: boolean) {
    if (checked === true) {
      const filterArray = this.dataObject['list'].filter(({ disabled }) => !disabled);
      for (const data of filterArray) {
        if (this.checkedData.find(o => Number(o['id']) === Number(data['id'])) == null) {
          data['checked'] = true;
          this.checkedData.push(data);
        }
      }
    } else {
      const filterArray = this.dataObject['list'].filter(({ disabled }) => !disabled);
      for (const data of filterArray) {
        data['checked'] = false;
        const findIndex = this.checkedData.findIndex(o => Number(o['id']) === Number(data['id']));
        this.checkedData.splice(findIndex, 1);
      }
    }
  }

  submitMigrateSalesman() {
    for (const i in this.merMigrateSalesmanForm.controls) {
      this.merMigrateSalesmanForm.controls[i].markAsDirty();
      this.merMigrateSalesmanForm.controls[i].updateValueAndValidity();
    }
    if (this.merMigrateSalesmanForm.status == null || this.merMigrateSalesmanForm.status !== 'VALID') {
      this.modal.warning({
        nzTitle: '提示',
        nzContent: '请选择业务员',
      });
      return;
    }
    if (this.checkedData.length === 0) {
      this.modal.warning({
        nzTitle: '提示',
        nzContent: '请选择需要转移的商户',
      });
      return;
    }
    const merList = [];
    for (const mer of this.checkedData) {
      merList.push(mer['id']);
    }
    this.merMigrateSalesmanForm.value['merList'] = merList;
    this.merService.merMigrateSalesman(this.merMigrateSalesmanForm.value, data => {
      if (data['return_code'] === '000000') {
        this.modal.success({
          nzTitle: '提示',
          nzContent: '操作成功',
        });
        this.checkedData = [];
        this.requestData(this.whereObject['pageNum']);
        this.merMigrateSalesmanModal = false;
      } else {
        this.modal.error({
          nzTitle: '提示',
          nzContent: data['return_msg'],
        });
      }
    });
  }
}
