import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {NzMessageService, NzModalService} from 'ng-zorro-antd';
import {GasClassGroupService} from '../../../services/gas-class-group.service';
import {GasClassGroupTaskService} from '../../../services/gas-class-group-task.service';
import {LocalStorageService} from '../../../services/local-storage.service';
import {ADMIN_INFO_OBJECT} from '../../../services/local-storage.namespace';

@Component({
  selector: 'app-gas-class-group-task',
  templateUrl: './gas-class-group-task.component.html',
  styleUrls: ['./gas-class-group-task.component.scss']
})
export class GasClassGroupTaskComponent implements OnInit {
  userInfoObject: object;

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

  classGroupArray = [];

  startClassGroupModal = false;
  startClassGroupModalForm: FormGroup;

  swapClassGroupModal = false;
  swapClassGroupModalForm: FormGroup;

  currentClassGroupCountData = {
    classNum: '无',
    refuelPrice: '0',
    refuelNum: '0',
    refuelLiters: '0',
    refundPrice: '0',
    refundNum: '0',
    status: null,
  };

  classGroupCountDataModal = false;
  classGroupCountData = {};

  printModal = false;
  printData = {};
  printTaskId: number;

  constructor(private modal: NzModalService,
              private localStorageService: LocalStorageService, // 数据缓存
              private message: NzMessageService,
              private gasClassGroupService: GasClassGroupService,
              private gasClassGroupTaskService: GasClassGroupTaskService,
              private form: FormBuilder) {
    this.userInfoObject = this.localStorageService.get(ADMIN_INFO_OBJECT);
  }

  ngOnInit(): void {

    this.searchForm = this.form.group({
      name: [null],
      principalName: [null],
      principalPhone: [null],
    });

    this.startClassGroupModalForm = this.form.group({
      gasId: [null],
      gasClassGroupId: [null, [Validators.required]],
    });

    this.swapClassGroupModalForm = this.form.group({
      gasId: [null],
      gasClassGroupId: [null, [Validators.required]],
    });

    this.gasClassGroupService.getClassGroupList({pageNum: 1, pageSize: 9999}, data => {
      if (data['return_code'] === '000000') {
          this.classGroupArray = data['return_data']['list'];
      }
    });
    this.getCurrentClassGroupCountData();
    this.requestData(1);
  }

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

  /**
   * 查询当前班组数据
   */
  getCurrentClassGroupCountData() {
    this.gasClassGroupTaskService.getCurrentClassGroupTask(this.userInfoObject['merchantStore']['id'], data => {
      if (data['return_code'] === '000000') {
        this.currentClassGroupCountData = data['return_data'];
      } else {
        this.modal.warning({
          nzTitle: '提示',
          nzContent: data['return_msg'],
        });
      }
    });

    this.requestData(this.whereObject['pageNum']);
  }

  /**
   * 打开 开始班组模态框
   */
  showStartClassGroupModal() {
    this.startClassGroupModal = true;
  }

  /**
   *
   * 关闭 开始班组模态框
   */
  closeStartClassGroupModal() {
    this.startClassGroupModalForm.reset();
    this.startClassGroupModal = false;
  }

  /**
   * 提交 开始班组数据
   */
  submitStartClassGroup(){
    for (const i in this.startClassGroupModalForm.controls) {
      this.startClassGroupModalForm.controls[i].markAsDirty();
      this.startClassGroupModalForm.controls[i].updateValueAndValidity();
    }
    if (this.startClassGroupModalForm.status == null || this.startClassGroupModalForm.status !== 'VALID') {
      this.modal.warning({
        nzTitle: '提示',
        nzContent: '请填写所有必填项',
      });
      return;
    }
    this.startClassGroupModalForm.value.gasId = this.userInfoObject['merchantStore']['id'];

    // 提交数据
    this.gasClassGroupTaskService.startGroupTask(this.startClassGroupModalForm.value, data => {
      if (data['return_code'] === '000000') {
        this.modal.success({
          nzTitle: '提示',
          nzContent: '操作成功',
        });
        this.getCurrentClassGroupCountData();
        this.requestData(this.whereObject['pageNum']);
        this.closeStartClassGroupModal();
      } else {
        this.modal.warning({
          nzTitle: '提示',
          nzContent: data['return_msg'],
        });
      }
    });
  }


  /**
   * 打开 交换班组模态框
   */
  showSwapClassGroupModal() {
    this.swapClassGroupModal = true;
  }

  /**
   * 关闭 交换班组模态框
   */
  closeSwapClassGroupModal() {
    this.swapClassGroupModalForm.reset();
    this.swapClassGroupModal = false;
  }

  /**
   * 提交 交换班组提醒框
   */
  submitSwapClassGroupConfirm() {
    this.modal.confirm({
      nzTitle: '警告',
      nzContent: '确定交换班次吗？',
      nzOkText: '是',
      nzCancelText: '否',
      nzOkType: 'danger',
      nzOnOk: () => this.submitSwapClassGroup()
    });
  }

  /**
   * 提交 交换班组数据
   */
  submitSwapClassGroup() {
    for (const i in this.swapClassGroupModalForm.controls) {
      this.swapClassGroupModalForm.controls[i].markAsDirty();
      this.swapClassGroupModalForm.controls[i].updateValueAndValidity();
    }
    if (this.swapClassGroupModalForm.status == null || this.swapClassGroupModalForm.status !== 'VALID') {
      this.modal.warning({
        nzTitle: '提示',
        nzContent: '请填写所有必填项',
      });
      return;
    }
    this.swapClassGroupModalForm.value.gasId = this.userInfoObject['merchantStore']['id'];

    // 提交数据
    this.gasClassGroupTaskService.swapGroupTask(this.swapClassGroupModalForm.value, data => {
      if (data['return_code'] === '000000') {
        this.modal.success({
          nzTitle: '提示',
          nzContent: '操作成功',
        });
        this.getCurrentClassGroupCountData();
        this.requestData(this.whereObject['pageNum']);
        this.closeSwapClassGroupModal();
      } else {
        this.modal.warning({
          nzTitle: '提示',
          nzContent: data['return_msg'],
        });
      }
    });
  }


  /**
   * 弹出结束对话框
   */
  showEndClassGroupConfirm(): void {
    this.modal.confirm({
      nzTitle: '警告',
      nzContent: '确定结束本次班次吗？',
      nzOkText: '是',
      nzCancelText: '否',
      nzOkType: 'danger',
      nzOnOk: () => this.endClassGroupData()
    });
  }

  /**
   * 提交结束班次数据
   *
   */
  endClassGroupData() {
    this.gasClassGroupTaskService.endGroupTask( { gasId: this.userInfoObject['merchantStore']['id'] }, data => {
      if (data['return_code'] === '000000') {
        this.requestData(this.whereObject['pageNum']);
        this.getCurrentClassGroupCountData();
      } else {
        this.modal.error({
          nzTitle: '提示',
          nzContent: data['return_msg']
        });
      }
    });
  }

  /**
   * 展示班次数据统计
   */
  showClassGroupTaskDataModal(data: object) {
    this.classGroupCountData = JSON.parse(data['dataCount']);
    this.printTaskId = data['id'];
    this.classGroupCountDataModal = true;
  }

  /**
   * 关闭班次数据统计
   */
  closeClassGroupTaskDataModal() {
    this.classGroupCountDataModal = false;
  }

  /**
   * 展示打印模态框
   * @param data
   */
  showPrintModal(data: object) {
    this.printData = data;
    this.printModal = true;
  }

  /**
   * 云打印
   */
  cloudPrint() {
    this.gasClassGroupTaskService.print(this.printTaskId, dataBack => {
      if (dataBack['return_code'] === '000000') {
        this.modal.success({
          nzTitle: '提示',
          nzContent: '操作成功',
        });
        this.printModal = false;
      }
    });
  }

  /**
   * 热敏打印机
   */
  showPrintDiv() {
    this.printDiv(this.printData);
  }

  printDiv(data: object) {
    const headstr = '<html><head><title>打印小票</title></head><body>';
    const footstr = '</body>';
    let newstr = '<div id="div_print" style="font-size: 16px;">\n' +
        '    <div style="float: left;margin-bottom: 50px;">\n' +
        '        <div style="line-height: 30px; color:#000;">\n' +
        '            <span  style="font-size: 13px;float: left;width: 100%;margin-left: 65px;">'+data['classNum']+'班结流水（补打）</span>\n' +
        '        </div>\n' +
        '        <table style="width: 100%;">\n' +
        '            <tbody>\n' +
        '            <tr><td style="font-size: xx-small;color: black;">===========================================</td></tr>\n' +
        '            <tr>\n' +
        '                <td style="font-size: xx-small;color: black;">开始时间：<span>' + new Date(data['startTime']).toLocaleString() + '</span></td>\n' +
        '            </tr>\n' +
        '            <tr>\n' +
        '                <td style="font-size: xx-small;color: black;">结束时间：<span>' + new Date(data['endTime']).toLocaleString() + '</span></td>\n' +
        '            </tr>\n' +
        '            <tr><td  style="font-size: xx-small;color: black;"></td></tr>' +
        '            <tr>\n' +
        '                <td style="font-size: xx-small;color: black;">加油金额汇总：<span>' + data['refuelPrice'] + '元</span></td>\n' +
        '            </tr>\n' +
        '            <tr>\n' +
        '                <td style="font-size: xx-small;color: black;">加油笔数汇总：<span>' + data['refuelNum'] + '笔</span></td>\n' +
        '            </tr>\n' +
        '            <tr>\n' +
        '                <td style="font-size: xx-small;color: black;">加油升数汇总：<span>' + data['refuelLiters'] + '升</span></td>\n' +
        '            </tr><br/>\n' +
        '            <tr><td  style="font-size: xx-small;color: black;"></td></tr>' +

        '            <tr>\n' +
        '                <td style="font-size: xx-small;color: black;">退款金额汇总：<span>' + data['refundPrice'] + '元</span></td>\n' +
        '            </tr>\n' +
        '            <tr>\n' +
        '                <td style="font-size: xx-small;color: black;">退款笔数汇总：<span>' + data['refundNum'] + '笔</span></td>\n' +
        '            </tr>\n' +
        '            <tr>\n' +
        '                <td style="font-size: xx-small;color: black;">退款升数汇总：<span>' + data['refundLiters'] + '升</span></td>\n' +
        '            </tr>\n' +
        '            <tr><td  style="font-size: xx-small;color: black;"></td></tr>' +

        '            <tr><td style="font-size: xx-small;color: black;">---------------------收款-------------------</td></tr>\n' +
        '            <tr><td style="font-size: xx-small;color: black;">油号&ensp; &ensp; &ensp; 金额(元) &ensp; &ensp; &ensp; 升数&ensp; &ensp; &ensp; &ensp; 笔数</td></tr>\n';
                for (let item of data['groupTaskOilCountList']) {
                    newstr += '<tr><td style="font-size: xx-small;color: black;">' + item['oilNo'] +'#&ensp; &ensp; &ensp; '+ item['refuelPrice'] +'&ensp; &ensp; &ensp; '+ item['refuelLiters'] +'&ensp; &ensp; &ensp;'+ item['refuelNum'] +'</td></tr>\n';

                }
        newstr += '<tr><td style="font-size: xx-small;color: black;">===========================================</td></tr>\n' +
        '            <tr><td style="float: left;font-size: xx-small;color: black;margin-left: 80px;">' + new Date().toLocaleString() +'</td></tr>\n' +
        '            </tbody>\n' +
        '        </table>\n' +
        '    </div>\n' +
        '</div>';
    const newWindow = window.open('', '');
    newWindow.document.write(headstr + newstr + footstr);
    newWindow.print();
    newWindow.close();
    return false;
  }
}
