package com.hfkj.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.hfkj.common.utils.DateUtil;
import com.hfkj.config.MqttProviderConfig;
import com.hfkj.device.sanmisen.PrinterTemplate;
import com.hfkj.device.spyun.SpPrinterConfig;
import com.hfkj.device.spyun.SpPrinterTemplate;
import com.hfkj.dao.BsDeviceMapper;
import com.hfkj.entity.BsDevice;
import com.hfkj.entity.BsDeviceExample;
import com.hfkj.entity.BsGasOrder;
import com.hfkj.service.BsDeviceService;
import com.hfkj.sysenum.DeviceReceiptOutContentEnum;
import com.hfkj.sysenum.DeviceTypeEnum;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("deviceService")
public class BsDeviceServiceImpl implements BsDeviceService {

    @Resource
    private BsDeviceMapper deviceMapper;
    @Resource
    private MqttProviderConfig mqttProviderConfig;
    @Override
    public void editDevice(BsDevice device) {
        if (device.getId() == null) {
            device.setCreateTime(new Date());
            device.setUpdateTime(new Date());
            device.setStatus(1);
            deviceMapper.insert(device);
        } else {
            device.setUpdateTime(new Date());
            deviceMapper.updateByPrimaryKey(device);
        }
    }

    @Override
    public BsDevice getDetailById(Long deviceId) {
        return deviceMapper.selectByPrimaryKey(deviceId);
    }

    @Override
    public List<BsDevice> getDeviceByMer(Long merId) {
        BsDeviceExample example = new BsDeviceExample();
        example.createCriteria().andMerIdEqualTo(merId).andStatusNotEqualTo(0);
        example.setOrderByClause("create_time desc");
        return deviceMapper.selectByExample(example);
    }

    @Override
    public List<BsDevice> getDeviceList(Map<String, Object> param) {
        BsDeviceExample example = new BsDeviceExample();
        BsDeviceExample.Criteria criteria = example.createCriteria().andStatusNotEqualTo(0);

        if (MapUtils.getInteger(param, "type") != null) {
            criteria.andTypeEqualTo(MapUtils.getInteger(param, "type"));
        }

        if (StringUtils.isNotBlank(MapUtils.getString(param, "merNo"))) {
            criteria.andMerNoEqualTo(MapUtils.getString(param, "merNo"));
        }

        if (StringUtils.isNotBlank(MapUtils.getString(param, "merName"))) {
            criteria.andMerNameLike("%"+MapUtils.getString(param, "merName")+"%");
        }

        if (StringUtils.isNotBlank(MapUtils.getString(param, "deviceSn"))) {
            criteria.andDeviceSnLike("%" + MapUtils.getString(param, "deviceSn") + "%");
        }

        if (StringUtils.isNotBlank(MapUtils.getString(param, "deviceName"))) {
            criteria.andDeviceNameLike("%" + MapUtils.getString(param, "deviceName") + "%");
        }

        example.setOrderByClause("create_time desc");
        return deviceMapper.selectByExample(example);
    }

    @Override
    public void printGasOrder(Long merId, BsGasOrder gasOrder, boolean makeUp) {
        // 查询加油站打印机
        List<BsDevice> deviceList = getDeviceByMer(merId);
        for (BsDevice device : deviceList) {
            Map<String, Object> receiptMap = new HashMap<>();
            receiptMap.put("receiptTop", device.getReceiptTop());
            receiptMap.put("receiptSource", device.getReceiptSource());
            receiptMap.put("receiptBottom", device.getReceiptBottom());

            if (device.getType().equals(DeviceTypeEnum.type1.getType())) {
                new Thread(() -> {
                    try {
                        SpPrinterConfig sp = new SpPrinterConfig();

                        if (device.getReceiptOutContent().equals(DeviceReceiptOutContentEnum.content1.getType())
                            || device.getReceiptOutContent().equals(DeviceReceiptOutContentEnum.content2.getType())) {
                            // 加油站存根
                            sp.print(device.getDeviceSn(),
                                    SpPrinterTemplate.oilCashierStubTemp(
                                            gasOrder.getMerName(),
                                            gasOrder.getOrderNo(),
                                            DateUtil.date2String(gasOrder.getPayTime(), "yyyy-MM-dd HH:mm:ss"),
                                            gasOrder.getUserPhone(),
                                            gasOrder.getGasGunNo(),
                                            gasOrder.getGasOilNo(),
                                            gasOrder.getGasOilLiters().toString(),
                                            gasOrder.getGasRefuelPrice().toString(),
                                            gasOrder.getTotalDeductionPrice().toString(),
                                            gasOrder.getActualPayPrice().toString(),
                                            receiptMap,
                                            makeUp
                                    ), 1);
                        }

                        if (device.getReceiptOutContent().equals(DeviceReceiptOutContentEnum.content1.getType())
                                || device.getReceiptOutContent().equals(DeviceReceiptOutContentEnum.content3.getType())) {
                            // 客户存根
                            sp.print(device.getDeviceSn(),
                                    SpPrinterTemplate.oilClientStubTemp(
                                            gasOrder.getMerName(),
                                            gasOrder.getOrderNo(),
                                            DateUtil.date2String(gasOrder.getPayTime(), "yyyy-MM-dd HH:mm:ss"),
                                            gasOrder.getUserPhone(),
                                            gasOrder.getGasGunNo(),
                                            gasOrder.getGasOilNo(),
                                            gasOrder.getGasOilLiters().toString(),
                                            gasOrder.getGasRefuelPrice().toString(),
                                            gasOrder.getTotalDeductionPrice().toString(),
                                            gasOrder.getActualPayPrice().toString(),
                                            receiptMap,
                                            makeUp
                                    ), 1);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }).start();

            } else if (device.getType().equals(DeviceTypeEnum.type2.getType())) {
                new Thread(() -> {
                    try {
                        JSONObject param = new JSONObject();
                        if (device.getReceiptOutContent().equals(DeviceReceiptOutContentEnum.content1.getType())
                                || device.getReceiptOutContent().equals(DeviceReceiptOutContentEnum.content2.getType())) {
                            param.put("id", System.currentTimeMillis());
                            param.put("type", 5);
                            if (!makeUp) {
                                param.put("vType", 0);
                                param.put("vMessage", "嗨加油新订单，加油金额"+gasOrder.getGasRefuelPrice()+"元，请注意查收");
                            } else {
                                param.put("vType", 0);
                                param.put("vMessage", "补打加油小票，请注意查收");
                            }
                            param.put("contents", PrinterTemplate.oilReceipt(1, gasOrder , receiptMap, makeUp));
                            mqttProviderConfig.publish(1, false, device.getDeviceSn()+"/submsg", param.toJSONString());
                        }

                        if (device.getReceiptOutContent().equals(DeviceReceiptOutContentEnum.content1.getType())
                                || device.getReceiptOutContent().equals(DeviceReceiptOutContentEnum.content3.getType())) {
                            param.clear();
                            param.put("id", System.currentTimeMillis());
                            param.put("type", 5);
                            if (!device.getReceiptOutContent().equals(DeviceReceiptOutContentEnum.content1.getType())) {
                                if (!makeUp) {
                                    param.put("vType", 0);
                                    param.put("vMessage", "嗨加油新订单，加油金额"+gasOrder.getGasRefuelPrice()+"元，请注意查收");
                                } else {
                                    param.put("vType", 0);
                                    param.put("vMessage", "补打加油小票，请注意查收");
                                }
                            }
                            param.put("contents", PrinterTemplate.oilReceipt(2, gasOrder , receiptMap, makeUp));
                            mqttProviderConfig.publish(1, false, device.getDeviceSn()+"/submsg", param.toJSONString());
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }).start();
            }
        }

    }
}
