import {Component, OnInit} from '@angular/core';
import {ReactiveFormsModule, UntypedFormBuilder, UntypedFormGroup, Validators} from "@angular/forms";
import {NzModalComponent, NzModalModule, NzModalService} from "ng-zorro-antd/modal";
import {NzMessageService} from "ng-zorro-antd/message";
import {AgentService} from "../../../services/agent.service";
import {CompanyService} from "../../../services/company.service";
import {CommonsService} from "../../../services/commons.service";
import {TradeTakeConfigService} from "../../../services/trade-take-config.service";
import {ADMIN_INFO_OBJECT} from "../../../services/local-storage.namespace";
import {NzColDirective, NzRowDirective} from "ng-zorro-antd/grid";
import {NzFormDirective, NzFormItemComponent, NzFormLabelComponent} from "ng-zorro-antd/form";
import {NzInputNumberComponent} from "ng-zorro-antd/input-number";
import {NzInputDirective} from "ng-zorro-antd/input";
import {NzButtonComponent} from "ng-zorro-antd/button";
import {BreadcrumbComponent} from "../../common/breadcrumb/breadcrumb.component";
import {NzOptionComponent, NzSelectComponent} from "ng-zorro-antd/select";
import {NzCellFixedDirective, NzTableComponent, NzThMeasureDirective} from "ng-zorro-antd/table";
import {AgentStatusPipe} from "../../../pipes/agent-status.pipe";
import {DatePipe, NgForOf, NgIf} from "@angular/common";
import {NzDropDownDirective, NzDropdownMenuComponent} from "ng-zorro-antd/dropdown";
import {NzMenuDirective, NzMenuItemComponent} from "ng-zorro-antd/menu";
import {NzIconDirective} from "ng-zorro-antd/icon";
import {RouterLink} from "@angular/router";
import {BrowserStorageService} from "../../../utils/localStorage.service";

@Component({
  selector: 'app-agent-list',
  standalone: true,
  imports: [
    NzColDirective,
    NzFormItemComponent,
    NzInputNumberComponent,
    NzInputDirective,
    NzButtonComponent,
    BreadcrumbComponent,
    NzFormDirective,
    NzRowDirective,
    ReactiveFormsModule,
    NzOptionComponent,
    NzSelectComponent,
    NzTableComponent,
    NzThMeasureDirective,
    AgentStatusPipe,
    DatePipe,
    NzDropdownMenuComponent,
    NzMenuDirective,
    NzMenuItemComponent,
    NzCellFixedDirective,
    NzIconDirective,
    RouterLink,
    NzDropDownDirective,
    NzModalComponent,
    NzFormLabelComponent,
    NgIf,
    NgForOf,
    NzModalModule
  ],
  templateUrl: './agent-list.component.html',
  styleUrl: './agent-list.component.less'
})
export class AgentListComponent implements OnInit {

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

  userObjectType: number;
  companyArray = [];

  tradeTakeConfigMadel = false;
  platformTypeArray = [];

  agentId: number;
  constructor(private modal: NzModalService,
              private message: NzMessageService,
              private agentService: AgentService,
              private companyService: CompanyService,
              private commonsService: CommonsService,
              private localStorageService: BrowserStorageService,
              private tradeTakeConfigService: TradeTakeConfigService,
              private form: UntypedFormBuilder) {
    this.userObjectType = Number(this.localStorageService.get(ADMIN_INFO_OBJECT)['secUser']['objectType']);
  }

  ngOnInit(): void {
    if (this.userObjectType != null && this.userObjectType === 0) {
      this.getCompanyList();
    }
    this.commonsService.getDictionary('PLATFORM_TYPE', data => {
      this.platformTypeArray = data['return_data'];
    });

    this.tradeTakeConfigForm = this.form.group({
      platformType: ['1', [Validators.required]],
      receiverName: [null, [Validators.required]],
      receiverAccount: [null, [Validators.required]],
      receiverRatio: [100, [Validators.required]],

      subReceiverName: [null, [Validators.required]],
      subReceiverAccount: [null, [Validators.required]],
      subReceiverRatio: [{ value: 0, disabled: true }, [Validators.required]],
      subReceiverObjectId: [null, [Validators.required]],
      agentId: [null],
    });

    this.searchForm = this.form.group({
      companyId: [null],
      name: [null],
      contactPerson: [null],
      contactPersonPhone: [null],
      status: [null],
    });
    this.requestData(1);
  }

  /**
   * 获取公司列表
   */
  getCompanyList() {
    this.companyService.selectCompanyList({pageNum: 1, pageSize: 99 }, data => {
      if (data['return_code'] === '000000') {
        this.companyArray = data['return_data']['list'];
      } else {
        this.modal.error(data['return_msg']);
      }
    });
  }

  /**
   * 请求数据
   */
  requestData(pageNum) {
    this.tableLoading = true;
    this.whereObject['pageNum'] = pageNum;
    this.whereObject['pageSize'] = 10;
    this.agentService.queryAgentList(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();
  }

  /**
   * 弹出删除对话框
   */
  showDeleteConfirm(id: number): void {
    this.modal.confirm({
      nzTitle: '警告',
      nzContent: '是否删除该代理商',
      nzOkText: '是',
      nzCancelText: '否',
      nzOnOk: () => this.deleteData(id)
    });
  }

  /**
   * 删除数据
   *
   */
  deleteData(id: number) {
    this.agentService.delAgent({ agentId : id}, data => {
      if (data['return_code'] === '000000') {
        this.requestData(this.whereObject['pageNum']);
      } else {
        this.modal.error({
          nzTitle: '提示',
          nzContent: data['return_msg']
        });
      }
    });
  }

  /**
   * 弹出删除对话框
   */
  showDisableAgentConfirm(id: number, disable: boolean): void {
    this.modal.confirm({
      nzTitle: '警告',
      nzContent: '是否' + disable ? '禁用' : '启用' + '代理商',
      nzOkText: '是',
      nzCancelText: '否',
      nzOnOk: () => this.disableAgent(id, disable)
    });
  }

  /**
   * 删除数据
   *
   */
  disableAgent(id: number, disablev: boolean) {
    this.agentService.disableAgent({ agentId : id, disable: disablev}, data => {
      if (data['return_code'] === '000000') {
        this.requestData(this.whereObject['pageNum']);
      } else {
        this.modal.error({
          nzTitle: '提示',
          nzContent: data['return_msg']
        });
      }
    });
  }


  /**
   * 展示交易分账配置
   */
  showTradeTakeConfigMadel(agentId: number) {
    this.agentId = agentId;
    this.tradeTakeConfigService.getAgentTradeTakeConfig(this.tradeTakeConfigForm.controls['platformType'].value, agentId, data => {
      if (data['return_code'] === '000000') {
        if (data['return_data'] != null) {
          data['return_data']['platformType'] = String(data['return_data']['platformType']);
          data['return_data']['receiverRatio'] = data['return_data']['receiverRatio'] * 100;
          data['return_data']['subReceiverRatio'] = data['return_data']['subReceiverRatio'] * 100;
          this.tradeTakeConfigForm.patchValue(data['return_data']);
        } else {
          this.tradeTakeConfigForm.controls['subReceiverObjectId'].setValue(agentId);
        }
      }
    });
    this.tradeTakeConfigMadel = true;
  }

  /**
   * 关闭交易分账配置
   */
  closeTradeTakeConfigMadel() {
    this.tradeTakeConfigForm.reset();
    this.tradeTakeConfigForm.controls['platformType'].setValue('4');
    this.tradeTakeConfigForm.controls['receiverRatio'].setValue('100');
    this.tradeTakeConfigForm.controls['subReceiverRatio'].setValue('0');
    this.tradeTakeConfigMadel = false;
  }

  /**
   * 提交配置
   */
  submitTradeTakeConfig() {
    for (const i in this.tradeTakeConfigForm.controls) {
      this.tradeTakeConfigForm.controls[i].markAsDirty();
      this.tradeTakeConfigForm.controls[i].updateValueAndValidity();
    }
    if (this.tradeTakeConfigForm.status == null || this.tradeTakeConfigForm.status !== 'VALID') {
      this.modal.warning({
        nzTitle: '提示',
        nzContent: '请规范填写所有的必填项信息',
      });
      return;
    }
    this.tradeTakeConfigForm.value['receiverRatio'] = this.tradeTakeConfigForm.controls['receiverRatio']['value'] / 100;
    this.tradeTakeConfigForm.value['subReceiverRatio'] = this.tradeTakeConfigForm.controls['subReceiverRatio']['value'] / 100;
    this.tradeTakeConfigService.editAgentConfig(this.tradeTakeConfigForm.value, data => {
      if (data['return_code'] === '000000') {
        this.modal.success({
          nzTitle: '提示',
          nzContent: '添加成功',
          nzOnOk: () => this.closeTradeTakeConfigMadel()
        });
      } else {
        this.modal.error({
          nzTitle: '提示',
          nzContent: data['return_msg'],
        });
      }
    });
  }

  /**
   * 计算
   * @param ratio
   * @param subRatio
   */
  compute(ratio: number) {
    // console.log(parentRatio);
    // this.tradeTakeConfigForm['receiverRatio'].value = parentRatio;
    this.tradeTakeConfigForm.controls['subReceiverRatio'].setValue(100 - ratio);
  }


  platformTypeChange(number) {
    if (number != null) {
      this.tradeTakeConfigService.getAgentTradeTakeConfig(number, this.agentId, data => {
        if (data['return_code'] === '000000') {
          if (data['return_data'] != null) {
            data['return_data']['platformType'] = String(data['return_data']['platformType']);
            data['return_data']['receiverRatio'] = data['return_data']['receiverRatio'] * 100;
            data['return_data']['subReceiverRatio'] = data['return_data']['subReceiverRatio'] * 100;
            this.tradeTakeConfigForm.patchValue(data['return_data']);
          } else {
            this.tradeTakeConfigForm.controls['subReceiverObjectId'].setValue(this.agentId);
          }
        }
      });
    }
  }
}
