import {Component, OnInit} from '@angular/core';
import {NzOptionComponent, NzSelectComponent} from "ng-zorro-antd/select";
import {
  NzFormControlComponent,
  NzFormDirective,
  NzFormItemComponent,
  NzFormLabelComponent,
  NzFormModule
} from "ng-zorro-antd/form";
import {NzModalComponent, NzModalModule, NzModalService} from "ng-zorro-antd/modal";
import {NzInputDirective, NzInputGroupComponent} from "ng-zorro-antd/input";
import {NzColDirective, NzRowDirective} from "ng-zorro-antd/grid";
import {BreadcrumbComponent} from "../../common/breadcrumb/breadcrumb.component";
import {FormsModule, ReactiveFormsModule, UntypedFormBuilder, UntypedFormGroup, Validators} from "@angular/forms";
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, NzSubMenuComponent} from "ng-zorro-antd/menu";
import {RouterLink, RouterOutlet} from "@angular/router";
import {NzTabComponent, NzTabSetComponent} from "ng-zorro-antd/tabs";
import {NzUploadComponent} from "ng-zorro-antd/upload";
import {MerTypePipe} from "../../../pipes/mer/mer-type.pipe";
import {NzTooltipDirective} from "ng-zorro-antd/tooltip";
import {NzContentComponent, NzHeaderComponent, NzLayoutComponent, NzSiderComponent} from "ng-zorro-antd/layout";
import {NzDrawerComponent} from "ng-zorro-antd/drawer";
import {NzSwitchComponent} from "ng-zorro-antd/switch";
import {environment} from "../../../../environments/environment";
import {NzMessageService} from "ng-zorro-antd/message";
import {CompanyService} from "../../../services/company.service";
import {AgentService} from "../../../services/agent.service";
import {SalesmanService} from "../../../services/salesman.service";
import {PayQrCodeService} from "../../../services/pay-qr-code.service";
import {ADMIN_INFO_OBJECT} from "../../../services/local-storage.namespace";
import {BrowserStorageService} from "../../../utils/localStorage.service";
import {NzSpinComponent, NzSpinModule} from "ng-zorro-antd/spin";
import {NzInputNumberComponent} from "ng-zorro-antd/input-number";
import {DeviceStatusPipe} from "../../../pipes/device/device-status.pipe";
import {NzRadioComponent, NzRadioGroupComponent} from "ng-zorro-antd/radio";
import {NzDatePickerModule} from "ng-zorro-antd/date-picker";

@Component({
  selector: 'app-pay-qr-code-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,
    NzSubMenuComponent,
    NzSiderComponent,
    NzLayoutComponent,
    NzHeaderComponent,
    NzContentComponent,
    RouterOutlet,
    NzDrawerComponent,
    NzSwitchComponent,
    FormsModule,
    NzInputGroupComponent,
    NzModalModule,
    NzSpinComponent,
    NzInputNumberComponent,
    DeviceStatusPipe,
    NzModalModule,
    NzTableModule,
    NzFormModule,
    NzSpinModule,
    NzRadioGroupComponent,
    NzRadioComponent,
    NzDatePickerModule
  ],
  templateUrl: './pay-qr-code-list.component.html',
  styleUrl: './pay-qr-code-list.component.less'
})
export class PayQrCodeListComponent implements OnInit {
  // 用户类型 0：超级管理员  1：公司  2：代理商  3：业务员  4：商户  5：门店
  userType: number;

  baseUrl = environment.baseUrl;
  FILE_URL = environment.imageUrl;
  loadingObject = {
    spinning: false,
    msg: '加载中'
  };

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

  allChecked = false;
  checkedData = [];

  generatePayQrCodeModal = false;
  generatePayQrCodeForm: UntypedFormGroup;

  companyDataArray = [];
  allocationCompanyModal = false;
  allocationCompanyForm: UntypedFormGroup;

  agentDataArray = [];
  allocationAgentModal = false;
  allocationAgentForm: UntypedFormGroup;

  salesmanDataArray = [];
  allocationSalesmanModal = false;
  allocationSalesmanForm: UntypedFormGroup;

  BTN_QRCODE_GENERATE = false;
  BTN_QRCODE_COMPANY = false;
  BTN_QRCODE_AGENT = false;
  BTN_QRCODE_SALESMAN = false;
  BTN_QRCODE_DISABLED = false;
  BTN_QRCODE_ENABLE = false;
  BTN_QRCODE_STORE_UNBIND = false;

  constructor(private modal: NzModalService,
              private message: NzMessageService,
              private companyService: CompanyService,
              private agentService: AgentService,
              private salesmanService: SalesmanService,
              private payQrCodeService: PayQrCodeService,
              private store: BrowserStorageService,
              private form: UntypedFormBuilder) {
    this.userType = Number(this.store.get(ADMIN_INFO_OBJECT)['secUser']['objectType']);
  }

  ngOnInit(): void {
    this.BTN_QRCODE_GENERATE = this.store.isBtnCompetence('BTN_QRCODE_GENERATE');  // 生成二维码 按钮权限
    this.BTN_QRCODE_COMPANY = this.store.isBtnCompetence('BTN_QRCODE_COMPANY');      // 分配代理商 按钮权限
    this.BTN_QRCODE_AGENT = this.store.isBtnCompetence('BTN_QRCODE_AGENT');      // 分配代理商 按钮权限
    this.BTN_QRCODE_SALESMAN = this.store.isBtnCompetence('BTN_QRCODE_SALESMAN');   // 分配业务员 按钮权限
    this.BTN_QRCODE_DISABLED = this.store.isBtnCompetence('BTN_QRCODE_DISABLED');   // 二维码禁用 按钮权限
    this.BTN_QRCODE_ENABLE = this.store.isBtnCompetence('BTN_QRCODE_ENABLE');     // 二维码启用 按钮权限
    this.BTN_QRCODE_STORE_UNBIND = this.store.isBtnCompetence('BTN_QRCODE_STORE_UNBIND');     // 二维码门店解绑 按钮权限

    this.searchForm = this.form.group({
      companyId: [null],
      agentId: [null],
      salesmanId: [null],
      merName: [null],
      storeName: [null],
      serialNumber: [null],
      isAssignCompany: [null],
      isAssignAgent: [null],
      isAssignSalesman: [null],
      isAssignStore: [null],
    });

    this.generatePayQrCodeForm = this.form.group({
      generateNum: [50, [Validators.required]],
    });

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

    this.allocationAgentForm = this.form.group({
      agentId: [null, [Validators.required]],
    });
    this.agentService.queryAgentList({ status: 1, pageNum: 1, pageSize: 999 }, data => {
      if (data['return_code'] === '000000') {
        this.agentDataArray = data['return_data']['list'];
      }
    });

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

    if (this.userType === 0) {
      this.companyService.selectCompanyList({pageNum: 1, pageSize: 999 }, data => {
        if (data['return_code'] === '000000') {
          this.companyDataArray = data['return_data']['list'];
        }
      });
    } else if (this.userType === 2) {
      this.salesmanService.querySalesmanListByAgent({ status: 1, pageNum: 1, pageSize: 999 }, data => {
        if (data['return_code'] === '000000') {
          this.salesmanDataArray = data['return_data']['list'];
        }
      });
    }

    this.requestData(1);
  }

  /**
   * 请求数据
   */
  requestData(pageNum) {
    this.tableLoading = true;
    this.whereObject['pageNum'] = pageNum;
    this.whereObject['pageSize'] = 10;
    this.payQrCodeService.getQrCodeList(this.whereObject, data => {
      if (data['return_code'] === '000000') {
        this.dataObject = data['return_data'];

        let checkoutNum = 0;
        for (const dataObject of this.dataObject['list']) {
          dataObject['disabled'] = ((this.userType === 1 && dataObject.agentId != null) || (this.userType === 2 && dataObject.salesmanId != null));
          if (this.checkedData.find(o => Number(o['id']) === Number(dataObject['id'])) != null) {
            checkoutNum++;
            dataObject['checked'] = true;
          }
        }
        if (Number(checkoutNum) === this.dataObject['list'].length) {
          this.allChecked = true;
        } else {
          this.allChecked = false;
          console.log(this.allChecked);
        }
      } 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();
  }

  /**
   * 弹出禁用二维码对话框
   */
  showDisabledConfirm(data: object): void {
    this.modal.confirm({
      nzTitle: '警告',
      nzContent: '是否禁用该二维码',
      nzOkText: '是',
      nzCancelText: '否',
      nzOnOk: () => this.disabledData(data['id'])
    });
  }

  /**
   * 禁用数据
   *
   */
  disabledData(id: number) {
    this.payQrCodeService.disabled({ qrCodeId : id}, data => {
      if (data['return_code'] === '000000') {
        this.requestData(this.whereObject['pageNum']);
      } else {
        this.modal.error({
          nzTitle: '提示',
          nzContent: data['return_msg']
        });
      }
    });
  }

  /**
   * 弹出启用二维码对话框
   */
  showEnableConfirm(data: object): void {
    this.modal.confirm({
      nzTitle: '警告',
      nzContent: '是否启用该二维码',
      nzOkText: '是',
      nzCancelText: '否',
      nzOnOk: () => this.enableData(data['id'])
    });
  }

  /**
   * 启用数据
   *
   */
  enableData(id: number) {
    this.payQrCodeService.enable({ qrCodeId : id}, data => {
      if (data['return_code'] === '000000') {
        this.requestData(this.whereObject['pageNum']);
      } else {
        this.modal.error({
          nzTitle: '提示',
          nzContent: data['return_msg']
        });
      }
    });
  }

  /**
   * 弹出生成二维码模态框
   */
  showGeneratePayQrCodeModal() {
    this.generatePayQrCodeModal = true;
  }

  /**
   * 关闭生成二维码模态框
   */
  closeGeneratePayQrCodeModal() {
    this.generatePayQrCodeModal = false;
  }

  /**
   * 提交生成二维码
   */
  submitGeneratePayQrCode() {
    this.generatePayQrCodeModal = false;
    this.loadingObject.spinning = true;
    this.loadingObject.msg = '二维码生成中...';
    for (const i in this.generatePayQrCodeForm.controls) {
      this.generatePayQrCodeForm.controls[i].markAsDirty();
      this.generatePayQrCodeForm.controls[i].updateValueAndValidity();
    }
    if (this.generatePayQrCodeForm.status == null || this.generatePayQrCodeForm.status !== 'VALID') {
      this.modal.warning({
        nzTitle: '提示',
        nzContent: '请输入生成数量',
      });
      return;
    }
    this.payQrCodeService.generatePayQrCode(this.generatePayQrCodeForm.value, data => {
      if (data['return_code'] === '000000') {
        this.modal.success({
          nzTitle: '提示',
          nzContent: '生成成功',
        });
        this.loadingObject.spinning = false;
        this.requestData(this.whereObject['pageNum']);
        this.closeGeneratePayQrCodeModal();
      } else {
        this.loadingObject.spinning = false;
        this.modal.error({
          nzTitle: '提示',
          nzContent: data['return_msg'],
        });
      }
    });
  }

  /**
   * 弹出分配代理商模态框
   */
  showUnbindStore(deviceId: number): void {
    this.modal.confirm({
      nzTitle: '警告',
      nzContent: '是否解绑该设备，会影响门店使用',
      nzOkText: '是',
      nzCancelText: '否',
      nzOnOk: () => this.unbindStore(deviceId)
    });
  }

  /**
   * 门店解绑
   */
  unbindStore(id: number) {
    this.payQrCodeService.unbindStore({ qrCodeId: id}, data => {
      if (data['return_code'] === '000000') {
        this.modal.success({
          nzTitle: '提示',
          nzContent: '解绑成功',
        });
        this.requestData(this.whereObject['pageNum']);
      } else {
        this.modal.error({
          nzTitle: '提示',
          nzContent: data['return_msg'],
        });
      }
    });
  }

  /**
   * 弹出分配代理商模态框
   */
  showAllocationCompanyModal() {
    this.allocationCompanyModal = true;
  }

  /**
   * 关闭分配代理商模态框
   */
  closeAllocationCompanyModal() {
    this.allocationCompanyModal = false;
  }

  /**
   * 提交代理商
   */
  submitAllocationCompany() {
    for (const i in this.allocationCompanyForm.controls) {
      this.allocationCompanyForm.controls[i].markAsDirty();
      this.allocationCompanyForm.controls[i].updateValueAndValidity();
    }
    if (this.allocationCompanyForm.status == null || this.allocationCompanyForm.status !== 'VALID') {
      this.modal.warning({
        nzTitle: '提示',
        nzContent: '请选择公司',
      });
      return;
    }
    if (this.checkedData.length === 0) {
      this.modal.warning({
        nzTitle: '提示',
        nzContent: '请选择需要分配的二维码',
      });
      return;
    }
    this.allocationCompanyForm.value['qrCodeArray'] = this.checkedData;
    this.payQrCodeService.assignCompany(this.allocationCompanyForm.value, data => {
      if (data['return_code'] === '000000') {
        this.modal.success({
          nzTitle: '提示',
          nzContent: '分配成功',
        });
        this.checkedData = [];
        this.requestData(this.whereObject['pageNum']);
        this.closeAllocationCompanyModal();
      } else {
        this.modal.error({
          nzTitle: '提示',
          nzContent: data['return_msg'],
        });
      }
    });

  }

  /**
   * 弹出分配代理商模态框
   */
  showAllocationAgentModal() {
    this.allocationAgentModal = true;
  }

  /**
   * 关闭分配代理商模态框
   */
  closeAllocationAgentModal() {
    this.allocationAgentModal = false;
  }

  /**
   * 提交代理商
   */
  submitAllocationAgent() {
    for (const i in this.allocationAgentForm.controls) {
      this.allocationAgentForm.controls[i].markAsDirty();
      this.allocationAgentForm.controls[i].updateValueAndValidity();
    }
    if (this.allocationAgentForm.status == null || this.allocationAgentForm.status !== 'VALID') {
      this.modal.warning({
        nzTitle: '提示',
        nzContent: '请选择代理商',
      });
      return;
    }
    if (this.checkedData.length === 0) {
      this.modal.warning({
        nzTitle: '提示',
        nzContent: '请选择需要分配的二维码',
      });
      return;
    }
    this.allocationAgentForm.value['qrCodeArray'] = this.checkedData;
    this.payQrCodeService.assignAgent(this.allocationAgentForm.value, data => {
      if (data['return_code'] === '000000') {
        this.modal.success({
          nzTitle: '提示',
          nzContent: '分配成功',
        });
        this.checkedData = [];
        this.requestData(this.whereObject['pageNum']);
        this.closeAllocationAgentModal();
      } else {
        this.modal.error({
          nzTitle: '提示',
          nzContent: data['return_msg'],
        });
      }
    });

  }

  /**
   * 弹出分配业务员模态框
   */
  showAllocationSalesmanModal() {
    this.allocationSalesmanModal = true;
  }

  /**
   * 关闭分配业务员模态框
   */
  closeAllocationSalesmanModal() {
    this.allocationSalesmanModal = false;
  }

  /**
   * 提交代理商
   */
  submitAllocationSalesman() {
    for (const i in this.allocationSalesmanForm.controls) {
      this.allocationSalesmanForm.controls[i].markAsDirty();
      this.allocationSalesmanForm.controls[i].updateValueAndValidity();
    }
    if (this.allocationSalesmanForm.status == null || this.allocationSalesmanForm.status !== 'VALID') {
      this.modal.warning({
        nzTitle: '提示',
        nzContent: '请选择业务员',
      });
      return;
    }
    if (this.checkedData.length === 0) {
      this.modal.warning({
        nzTitle: '提示',
        nzContent: '请选择需要分配的二维码',
      });
      return;
    }
    this.allocationSalesmanForm.value['qrCodeArray'] = this.checkedData;
    this.payQrCodeService.assignSalesman(this.allocationSalesmanForm.value, data => {
      if (data['return_code'] === '000000') {
        this.modal.success({
          nzTitle: '提示',
          nzContent: '分配成功',
        });
        this.checkedData = [];
        this.requestData(this.whereObject['pageNum']);
        this.closeAllocationSalesmanModal();
      } else {
        this.modal.error({
          nzTitle: '提示',
          nzContent: data['return_msg'],
        });
      }
    });

  }

  /**
   * 全选
   * @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);
      }
    }
  }

  /**
   * 选中
   * @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 agentId 代理商id
   */
  agentChange(agentId: number) {
    if (agentId != null) {
      this.salesmanService.querySalesmanList({ agentId, pageNum: 1, pageSize: 9999}, data => {
        this.salesmanDataArray = data['return_data']['list'];
      });
    } else {
      this.salesmanDataArray = [];
    }
  }

  exportQrCode() {
    this.loadingObject.spinning = true;
    this.loadingObject.msg = '导出中...';
    this.payQrCodeService.exportQrCodeList(this.whereObject, data => {
      if (data['return_code'] === '000000') {
        window.location.href = this.FILE_URL + 'temporary/' + data['return_data'];
      } else {
        this.message.error(data['return_msg']);
      }
      this.loadingObject.spinning = false;
    });
  }
}
