import { Component, OnInit } from '@angular/core';
import {environment} from '../../../../environments/environment';
import {LocalStorageService} from '../../../services/local-storage.service';
import {OilCardService} from '../../../services/oil-card.service';
import {OrganizationService} from '../../../services/organization.service';
import {CompanyAccountService} from '../../../services/company-account.service';
import {ADMIN_INFO_OBJECT} from '../../../services/local-storage.namespace';
import {ValidatorsService} from '../../../services/validators.service';
import {DeviceService} from "../../../services/device.service";
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {NzMessageService, NzModalService} from 'ng-zorro-antd';
import {ActivatedRoute} from '@angular/router';

@Component({
  selector: 'app-device-list',
  templateUrl: './device-list.component.html',
  styleUrls: ['./device-list.component.scss']
})
export class DeviceListComponent implements OnInit {
  roleType;
  adminFlag;
  loadingObject = {
    spinning: false,
    msg: '加载中'
  };

  dataObject: any = {};
  tableLoading = true;
  searchForm: FormGroup;
  whereObject: any = {};

  configDeviceModalTitle: string;
  configDeviceModal = false;
  configDeviceForm: FormGroup;
  merStoreId: number;

  orgArray = [];

  constructor(private modal: NzModalService,
              private message: NzMessageService,
              private store: LocalStorageService,
              private deviceService: DeviceService,
              private organizationService: OrganizationService,
              private activatedRoute: ActivatedRoute,
              private form: FormBuilder) {
    this.roleType = Number(this.store.get(ADMIN_INFO_OBJECT)['secRole'].roleType);
    this.adminFlag = Number(this.store.get(ADMIN_INFO_OBJECT)['secUser'].adminFlag);
  }

  ngOnInit(): void {
    this.activatedRoute.queryParams.subscribe(queryParams => {
      if (queryParams['merStoreId'] != null) {
        this.merStoreId = queryParams['merStoreId'];
      }
    });

    this.searchForm = this.form.group({
      companyId: [null],
      merId: [null],
      storeId: [null],
      deviceName: [null],
    });

    this.configDeviceForm = this.form.group({
      id: [null],
      merStoreId: [null],
      type: [null, [Validators.required]],
      // deviceName: [null, [Validators.required]],
      deviceSn: [null],
      deviceKey: [null],
      deviceImei: [null],
      deviceIccid: [null],
      receiptTop: [null],
      receiptSource: [null],
      receiptBottom: [null],
    });

    this.requestData(1);
  }

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

  /**
   * 展示配置设备模态框
   */
  showConfigDeviceModal(deviceData: object) {
    if (deviceData != null) {
      this.configDeviceModalTitle = '修改设备';
      deviceData['type'] = String(deviceData['type']);
      this.configDeviceForm.patchValue(deviceData);

      this.configDeviceForm.controls.type.disable();
      this.configDeviceForm.controls.deviceSn.disable();
      this.configDeviceForm.controls.deviceKey.disable();
      this.configDeviceForm.controls.deviceImei.disable();
      this.configDeviceForm.controls.deviceIccid.disable();
    }
    if (deviceData == null) {
      this.configDeviceModalTitle = '新增设备';
    }
    this.configDeviceModal = true;
  }

  /**
   * 关闭配置设备模态框
   */
  closeConfigDeviceModal() {
    this.configDeviceForm.controls.type.enable();
    this.configDeviceForm.controls.deviceSn.enable();
    this.configDeviceForm.controls.deviceKey.enable();
    this.configDeviceForm.controls.deviceImei.enable();
    this.configDeviceForm.controls.deviceIccid.enable();
    this.configDeviceForm.reset();
    this.configDeviceModal = false;
  }

  /**
   * 提交生成数量
   */
  submitConfigDevice() {
    for (const i in this.configDeviceForm.controls) {
      this.configDeviceForm.controls[i].markAsDirty();
      this.configDeviceForm.controls[i].updateValueAndValidity();
    }
    if (this.configDeviceForm.status == null || this.configDeviceForm.status !== 'VALID') {
      this.modal.warning({
        nzTitle: '提示',
        nzContent: '请填写所有必填项',
      });
      return;
    }
    this.configDeviceForm.controls.type.enable();
    this.configDeviceForm.controls.deviceSn.enable();
    this.configDeviceForm.controls.deviceKey.enable();
    this.configDeviceForm.controls.deviceImei.enable();
    this.configDeviceForm.controls.deviceIccid.enable();
    this.configDeviceForm.value.merStoreId = this.merStoreId;
    this.deviceService.editDevice(this.configDeviceForm.value, data => {
      if (data['return_code'] === '000000') {
        this.modal.success({
          nzTitle: '提示',
          nzContent: '操作成功',
        });
        this.closeConfigDeviceModal();
        this.requestData(this.whereObject['pageNum']);
      } else {
        this.modal.error({
          nzTitle: '提示',
          nzContent: data['return_msg'],
        });
        this.configDeviceForm.controls.type.disable();
        this.configDeviceForm.controls.deviceSn.disable();
        this.configDeviceForm.controls.deviceKey.disable();
        this.configDeviceForm.controls.deviceImei.disable();
        this.configDeviceForm.controls.deviceIccid.disable();
      }
      this.loadingObject.spinning = false;
    });
  }

  /**
   * 弹出删除对话框
   */
  showDelConfirm(id: number): void {
    this.modal.confirm({
      nzTitle: '警告',
      nzContent: '确定删除设备吗？',
      nzOkText: '是',
      nzCancelText: '否',
      nzOkType: 'danger',
      nzOnOk: () => this.delData(id)
    });
  }

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

}
