import { Component, OnInit } from '@angular/core';
import {environment} from '../../../../environments/environment';
import {FormBuilder, FormGroup} from '@angular/forms';
import {OrderService} from '../../../services/order.service';
import {IconService} from '../../../services/icon.service';
import {NzMessageService, NzModalService} from 'ng-zorro-antd';
import {Router} from '@angular/router';
import {CompanyService} from '../../../services/company.service';
import {MerchantService} from '../../../services/merchant.service';
import {LocalStorageService} from '../../../services/local-storage.service';
import {CommonsService} from '../../../services/commons.service';
import {WebsocketService} from '../../../services/websocket.service';
import {ADMIN_INFO_OBJECT} from '../../../services/local-storage.namespace';
import {MerchantStoreService} from '../../../services/merchant-store.service';
import {GasStaffService} from "../../../services/gas-staff.service";

@Component({
  selector: 'app-oil-station-order',
  templateUrl: './oil-station-order.component.html',
  styleUrls: ['./oil-station-order.component.scss']
})
export class OilStationOrderComponent implements OnInit {

    WEB_SERVE_URL = environment.baseUrl;
    FILE_URL = environment.imageUrl;
    searchForm: FormGroup; // 搜索框
    requestData = []; // 列表数据
    companyData = []; // 列表数据
    merchantData = []; // 列表数据
    data = {}; // 列表数据
    total: number; // 页码
    pageNum = 1; // 页码
    pageSize = 10; // 条码
    loading = true;
    id: number; // 订单ID
    isVisible = false;
    isVisibleDetail = false;
    refundContent: string;
    roleType: number;
    secUser: object;

    gasArray = [];

    printDataObject = {
        orderId: null,
        printData: null
    };
    printModal = false;

    userSession = {};
    gasStaffArray = [];

    oilNoArray = [];

    BTN_GAS_ORDER_REFUND = false;
    BTN_GAS_ORDER_PRINT = false;

    dataCount = {
        refuelNum: 0,
        refuelPrice: 0,
        refuelLiters: 0,
    };
    constructor(
        private form: FormBuilder,
        private order: OrderService,
        private webSocketService: WebsocketService,
        private iconService: IconService,
        private modal: NzModalService,
        private message: NzMessageService,
        private router: Router,
        private company: CompanyService,
        private merchant: MerchantService,
        private merchantStoreService: MerchantStoreService,
        private gasStaffService: GasStaffService,
        private orderService: OrderService,
        private store: LocalStorageService, // 数据请求
        private common: CommonsService
    ) {
    }

    ngOnInit(): void {

        this.BTN_GAS_ORDER_REFUND = this.common.isBtnCompetence("BTN_GAS_ORDER_REFUND");
        this.BTN_GAS_ORDER_PRINT = this.common.isBtnCompetence("BTN_GAS_ORDER_PRINT");

        this.userSession = this.store.get(ADMIN_INFO_OBJECT);
        this.secUser = this.store.get(ADMIN_INFO_OBJECT)['secUser'];
        if (this.secUser['objectType'] === 2) {
            this.merchantStoreService.getStoreListByMerchant({ pageNum: 1, pageSize: 100}, data => {
               if (data['return_code'] === '000000') {
                   this.gasArray = data['return_data']['list'];
               }
            });
        } else if (this.secUser['objectType'] === 3) {
            this.getStaffList(null);
        } else if (this.secUser['objectType'] === 8) {
            this.getStaffList(null);
        }
        this.init();
        // 接收消息
        this.webSocketService.messageSubject.subscribe(
            data => {
                console.log(data);
                this.getRequest(true, this.searchForm.value);
            },
            err => console.log(err)
        );
    }

    public init(): void {
        this.searchForm = this.form.group({
            storeId: [null],
            staffId: [null],
            orderNo: [null],
            status: [null],
            oilNo: [null],
            createTime: [null],
            payTime: [null],
        });
        this.getRequest(true, this.searchForm.value);

        // 查询油号
        this.common.getDictionary("GAS_OIL_TYPE", data => {
           if (data['return_code'] == '000000') {
               this.oilNoArray = data['return_data'];
           }
        });
    }

    // 查询列表
    public getRequest(reset: boolean = false, whereObject: object) {
        if (whereObject['createTime'] != null && whereObject['createTime'].length !== 0) {
            whereObject['createTimeS'] = whereObject['createTime'][0].getTime();
            whereObject['createTimeE'] = whereObject['createTime'][1].getTime();
        }
        if (whereObject['payTime'] != null && whereObject['payTime'].length !== 0) {
            whereObject['payTimeS'] = whereObject['payTime'][0].getTime();
            whereObject['payTimeE'] = whereObject['payTime'][1].getTime();
        }

        this.loading = false;
        if (reset) {
            this.pageNum = 1;
        }
        whereObject['pageNum'] = this.pageNum;
        whereObject['pageSize'] = this.pageSize;
        this.order.getGasOrderListByOil(whereObject, data => {
            if (data['return_code'] === '000000') {
                this.requestData = data['return_data'].list;
                this.total = data['return_data'].total;
            } else {
                this.message.error(data['return_msg']);
            }
        });
        this.countGasOrder();
    }

    // 统计订单
    public countGasOrder() {
        this.orderService.countGasOrder(this.searchForm.value, data => {
            if (data['return_code'] == '000000') {
                this.dataCount = data['return_data'];
            }
        });
    }

    // 查询列表
    public getStaffList(gasId: number) {
        const param = { pageNum: 1 , pageSize: 9999};
        if (gasId != null) {
            param['merchantStoreId'] = gasId;
        }
        this.gasStaffService.getStaffList(param, data => {
            if (data['return_code'] === '000000') {
                this.gasStaffArray = data['return_data']['list'];
            }
        });
    }

    selectGasChange(gasId: number) {
        if (gasId != null) {
            this.getStaffList(gasId);
        } else {
            this.gasStaffArray = [];
        }
    }

    // 重置
    public resetForm(): void {
        this.searchForm.reset();
    }

    showModal(id): void {
        this.id = id;
        this.isVisible = true;
    }

    handleOk(): void {
        this.common.showConfirm('确认订单是否退款', item => {
            if (item) {
                const params = {
                    orderId: this.id ,
                    refundContent: this.refundContent
                };
                this.order.refuelingOrderRefund(params, data => {
                    if (data['return_code'] === '000000') {
                        this.getRequest(true, this.searchForm.value);
                        this.isVisible = false;
                        this.message.success('退款成功');
                    } else {
                        this.message.error(data['return_msg']);
                    }
                });
            }
        });
    }

    handleCancel(): void {
        this.isVisible = false;
    }

    getDetail(orderNo: string): void {
        this.order.getGasOrderDetail(orderNo , data => {
            if (data['return_code'] === '000000') {
                this.isVisibleDetail = true;
                this.data = data['return_data'];
            } else {
                this.message.error(data['return_msg']);
            }
        });
    }

    /**
     * 导出订单
     */
    excelOrder() {
        this.order.exportGasOrder(this.searchForm.value, data => {
            if (data['return_code'] === '000000') {
                window.location.href = this.FILE_URL + 'temporary/' + data['return_data'];
            } else {
                this.message.error(data['return_msg']);
            }
        });
    }

    showPrintModal(orderId: number, data: PrintData) {
        this.printDataObject.orderId = orderId;
        this.printDataObject.printData = data;
        this.printModal = true;
    }

    cloudPrint() {
        this.orderService.print(this.printDataObject.orderId, 2, dataBack => {
            if (dataBack['return_code'] === '000000') {
                this.modal.success({
                    nzTitle: '提示',
                    nzContent: '操作成功',
                });
                this.getRequest(false, this.searchForm.value);
            }
        });
    }

    showPrintDiv() {
        const orderId = this.printDataObject.orderId;
        const data = this.printDataObject.printData;
        data['payTime'] = new Date(data['payTime']).toLocaleString();
        this.printDiv(data);

        this.orderService.print(orderId, 1, dataBack => {
            if (dataBack['return_code'] === '000000') {
                this.getRequest(false, this.searchForm.value);
            }
        });
    }

    printDiv(data: object) {
        const headstr = '<html><head><title>打印小票</title></head><body>';
        const footstr = '</body>';
        const 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%;text-align: center;">'+data['gasName']+(data['printStatus']?'（补打）':'') + '</span>\n' +
            '            <span  style="font-size: 13px;float: left;width: 100%;margin-left: 60px;">（收银员存根）</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>' + data['orderNo'] + '</span></td>\n' +
            '            </tr>\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().toLocaleString() + '</span></td>\n' +
            '            </tr>\n' +
            '            <tr>\n' +
            '                <td style="font-size: xx-small;color: black;">支付时间：<span>' + data['payTime'] + '</span></td>\n' +
            '            </tr>\n' +
            '            <tr>\n' +
            '                <td style="font-size: xx-small;color: black;">电话：<span>' + data['merPhone'] + '</span></td>\n' +
            '            </tr>\n' +
            '            <tr>\n' +
            '                <td style="font-size: xx-small;color: black;">来源：<span>嗨森逛</span></td>\n' +
            '            </tr>\n' +
            '            <tr>\n' +
            '                <td style="font-size: xx-small;color: black;">油枪：<span>' + data['gasGunNo'] + '号</span></td>\n' +
            '            </tr>\n' +
            '            <tr>\n' +
            '                <td style="font-size: xx-small;color: black;">油品：<span>' + data['gasOilNo'] + '#</span></td>\n' +
            '            </tr>\n' +
            '            <tr>\n' +
            '                <td style="font-size: xx-small;color: black;">升数：<span>' + data['gasOilLiters'] + '升</span></td>\n' +
            '            </tr>\n' +
            '            <tr>\n' +
            '                <td style="font-size: xx-small;color: black;">实际加油升数以油站加油机为准！</td>\n' +
            '            </tr>\n' +
            '            <tr><td style="font-size: xx-small;color: black;">-------------------------------------------</td></tr>\n' +
            '            <tr><td style="float: left;margin-top: 10px;font-size: 30px;color: black">加油金额</td></tr>\n' +
            '            <tr><td style="font-size: 30px;color: black">￥' + data['totalPrice'] + '元</td></tr>\n' +
            '            <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: 25px;">开心又省钱； 来”嗨森逛“</td></tr>\n' +
            '            </tbody>\n' +
            '        </table>\n' +
            '    </div>\n' +
            '</div>';
        // const oldstr = document.body.innerHTML;
        // document.body.innerHTML = headstr + newstr + footstr;
        const newWindow = window.open('', '');
        newWindow.document.write(headstr + newstr + footstr);
        newWindow.print();
        newWindow.close();
        // document.body.innerHTML = oldstr;
        // location.reload();
        return false;
    }
}

export class PrintData {
    // 油站名称
    gasName = '';
    // 订单号
    orderNo = '';
    // 下单时间
    createTime = '';
    // 油品
    gasOilNo = '';
    // 加油抢号
    gasGunNo = '';
    // 加油升数
    gasOilLiters = 0;
    // 加油金额
    oilPrice = 0;
}
