import {Component, OnInit} from '@angular/core';
import {environment} from "../../../../environments/environment";
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 {CompanyService} from "../../../services/company.service";
import {CommonsService} from "../../../services/commons.service";
import {SalesmanService} from "../../../services/salesman.service";
import {AgentService} from "../../../services/agent.service";
import {DeviceService} from "../../../services/device.service";
import {ADMIN_INFO_OBJECT} from "../../../services/local-storage.namespace";
import {NzColDirective, NzRowDirective} from "ng-zorro-antd/grid";
import {NzFormDirective, NzFormItemComponent, NzFormLabelComponent, NzFormModule} 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, NzTableModule,
  NzTdAddOnComponent,
  NzThMeasureDirective,
  NzThSelectionComponent
} 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 {NzSpinComponent, NzSpinModule} from "ng-zorro-antd/spin";
import {DeviceTypePipe} from "../../../pipes/device/device-type.pipe";
import {NzUploadComponent} from "ng-zorro-antd/upload";
import {DeviceStatusPipe} from "../../../pipes/device/device-status.pipe";
import {BrowserStorageService} from "../../../utils/localStorage.service";
import {NzRadioComponent, NzRadioGroupComponent} from "ng-zorro-antd/radio";
import {NzDatePickerModule} from "ng-zorro-antd/date-picker";

@Component({
  selector: 'app-device-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,
    NzSpinComponent,
    NzTdAddOnComponent,
    DeviceTypePipe,
    NzUploadComponent,
    DeviceStatusPipe,
    NzThSelectionComponent,
    NzModalModule,
    NzTableModule,
    NzFormModule,
    NzSpinModule,
    NzRadioGroupComponent,
    NzRadioComponent,
    NzDatePickerModule
  ],
  templateUrl: './device-list.component.html',
  styleUrl: './device-list.component.less'
})
export class DeviceListComponent implements OnInit {
  // 角色类型 0：超级管理员  1：公司  2：代理商  3：业务员  4：商户  5：门店
  roleType: number;
  baseUrl = environment.baseUrl;

  loadingObject = {
    spinning: false,
    msg: '加载中'
  };

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

  checkedData = [];

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

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

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

  importDeviceErrorModal = false;
  importDeviceErrorData = [];

  importDeviceModal = false;
  importDeviceForm: UntypedFormGroup;
  deviceTypeArray = [];

  BTN_IMPORT_DEVICE = false;
  BTN_DOWN_DEVICE = false;
  BTN_COMPANY_ALLOCATION;
  BTN_AGENT_ALLOCATION;
  BTN_SALESMAN_ALLOCATION;
  BTN_STORE_UNBIND;
  BTN_DEVICE_ENABLE;
  BTN_DEVICE_DISABLE;
  BTN_DEVICE_DEL;
  isCollapse = false;

  constructor(private modal: NzModalService,
              private message: NzMessageService,
              private companyService: CompanyService,
              private commonsService: CommonsService,
              private salesmanService: SalesmanService,
              private agentService: AgentService,
              private deviceService: DeviceService,
              private store: BrowserStorageService,
              private form: UntypedFormBuilder) {
    this.roleType = this.store.get(ADMIN_INFO_OBJECT)['secRole'].roleType;
  }

  ngOnInit(): void {
    this.BTN_IMPORT_DEVICE = this.store.isBtnCompetence('BTN_import_device');              // 导入设备 按钮权限
    this.BTN_DOWN_DEVICE = this.store.isBtnCompetence('BTN_down_device');                  // 下载设备 按钮权限
    this.BTN_COMPANY_ALLOCATION = this.store.isBtnCompetence('BTN_company_allocation');    // 分配代理商 按钮权限
    this.BTN_AGENT_ALLOCATION = this.store.isBtnCompetence('BTN_agent_allocation');        // 分配代理商 按钮权限
    this.BTN_SALESMAN_ALLOCATION = this.store.isBtnCompetence('BTN_salesman_allocation');  // 分配业务员 按钮权限
    this.BTN_DEVICE_ENABLE = this.store.isBtnCompetence('BTN_device_enable');              // 启用 按钮权限
    this.BTN_DEVICE_DISABLE = this.store.isBtnCompetence('BTN_device_disable');            // 禁用 按钮权限
    this.BTN_DEVICE_DEL = this.store.isBtnCompetence('BTN_device_del');                    // 删除 按钮权限
    this.BTN_STORE_UNBIND = this.store.isBtnCompetence('BTN_store_unbind');                // 门店解绑 按钮权限

    this.searchForm = this.form.group({
      companyName: [null],
      agentName: [null],
      salesmanName: [null],
      merName: [null],
      storeName: [null],
      deviceType: [null],
      deviceNo: [null],
      status: [null],
    });


    this.commonsService.getDictionary('DEVICE_TYPE', data => {
      this.deviceTypeArray = data['return_data'];
    });

    this.importDeviceForm = this.form.group({
      deviceType: ['1', [Validators.required]],
      file: [null],
    });


    this.allocationCompanyForm = this.form.group({
      companyId: [null, [Validators.required]],
    });
    this.companyService.selectCompanyList({ pageNum: 1, pageSize: 999 }, data => {
      if (data['return_code'] === '000000') {
        this.companyDataArray = data['return_data']['list'];
      }
    });

    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]],
    });
    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.deviceService.getDeviceList(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(data: object): void {
    this.modal.confirm({
      nzTitle: '警告',
      nzContent: '设备编号：' + data['deviceNo'] + ',是否删除该设备？',
      nzOkText: '是',
      nzCancelText: '否',
      nzOnOk: () => this.deleteData(data['id'])
    });
  }

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

  /**
   * 下载导入设备模板
   */
  downloadDeviceTemplate() {
    window.location.href = environment.imageUrl + 'template/设备导入模板.xlsx';
  }

  /**
   * 打开导入设备模态框
   */
  showImportDevice() {
    this.importDeviceModal = true;
  }

  /**
   * 导入设备回调
   * @param fileInfo
   */
  importDeviceChange(fileInfo) {
    if (fileInfo.file.status !== 'uploading') {

    }

    if (fileInfo.file.status === 'done') {
      this.loadingObject.spinning = false;
      if (fileInfo.file.response.return_code === '000000') {
        if (fileInfo.file.response.return_data == null || fileInfo.file.response.return_data.length === 0) {
          this.modal.error({
            nzTitle: '提示',
            nzContent: '文件上传失败',
          });
        } else {
          this.importDeviceForm.controls['file'].setValue(fileInfo.file.response.return_data[0]);
        }
      } else {
        this.modal.error({
          nzTitle: '提示',
          nzContent: fileInfo.file.response.return_msg,
        });
      }
    } else if (fileInfo.file.status === 'error') {
      this.loadingObject.spinning = false;
      this.modal.error({
        nzTitle: '提示',
        nzContent: '导入失败'
      });
    }
  }

  /**
   * 提交导入设备
   */
  submitImportDevice() {
    this.loadingObject.spinning = true;
    this.loadingObject.msg = '导入中...';
    for (const i in this.importDeviceForm.controls) {
      this.importDeviceForm.controls[i].markAsDirty();
      this.importDeviceForm.controls[i].updateValueAndValidity();
    }
    if (this.importDeviceForm.value.file == null) {
      this.modal.warning({
        nzTitle: '提示',
        nzContent: '请上传文件',
      });
      this.loadingObject.spinning = false;
      return;
    }

    if (this.importDeviceForm.status == null || this.importDeviceForm.status !== 'VALID') {
      this.modal.warning({
        nzTitle: '提示',
        nzContent: '请填写所有的必填项',
      });
      this.loadingObject.spinning = false;
      return;
    }
    this.importDeviceModal = false;

    this.deviceService.importDevice(this.importDeviceForm.value, data => {
      this.loadingObject.spinning = false;
      if (data['return_code'] === '000000') {
        if (data['return_data'].length === 0) {
          this.modal.success({
            nzTitle: '提示',
            nzContent: '成功',
            nzOnOk: () => this.requestData(1)
          });
        } else {
          this.modal.warning({
            nzTitle: '提示',
            nzOkText: '导入失败数据',
            nzContent: '只有部分数据导入成功',
            nzOnOk: () => this.showDeviceErrorModal(data['return_data'])
          });
        }
      } else {
        this.importDeviceModal = true;
        this.modal.error({
          nzTitle: '提示',
          nzContent: data['return_msg'],
        });
      }
    });
  }
  /**
   * 打开模态框
   */
  showDeviceErrorModal(data: []) {
    this.requestData(this.whereObject['pageNum']);
    this.importDeviceErrorData = data;
    this.importDeviceErrorModal = true;
  }

  /**
   * 关闭模态框
   */
  handleCancel() {
    this.importDeviceErrorModal = false;
  }

  /**
   * 弹出分配代理商模态框
   */
  showDisable(deviceId: number): void {
    this.modal.confirm({
      nzTitle: '警告',
      nzContent: '是否停用该设备？设备停用后无法使用！',
      nzOkText: '是',
      nzCancelText: '否',
      nzOnOk: () => this.disable(deviceId)
    });
  }
  disable(id: number) {
    this.deviceService.disableDevice({ deviceId: 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'],
        });
      }
    });
  }

  /**
   * 弹出分配代理商模态框
   */
  showEnable(deviceId: number): void {
    this.modal.confirm({
      nzTitle: '警告',
      nzContent: '是否启用该设备？',
      nzOkText: '是',
      nzCancelText: '否',
      nzOnOk: () => this.enable(deviceId)
    });
  }
  enable(id: number) {
    this.deviceService.enableDevice({ deviceId: 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'],
        });
      }
    });
  }

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

  /**
   * 门店解绑
   */
  unbindStore(id: number) {
    this.deviceService.unbindStore({ deviceId: 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['deviceArray'] = this.checkedData;
    this.deviceService.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['deviceArray'] = this.checkedData;
    this.deviceService.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['deviceArray'] = this.checkedData;
    this.deviceService.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
   * @param checked
   */
  checkedChange(data: object, checked: boolean) {
    if (checked === true) {
      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);
    }
  }

  toggleCollapse(): void {
    this.isCollapse = !this.isCollapse;
  }

}
