package com.bweb.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONObject;
import com.bweb.config.SysConst;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.security.UserCenter;
import com.hai.common.utils.CoordCommonUtil;
import com.hai.common.utils.DateUtil;
import com.hai.common.utils.PageUtil;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.config.HuiLianTongUnionCardConfig;
import com.hai.config.ShellGroupService;
import com.hai.config.TuanYouConfig;
import com.hai.config.WxOrderConfig;
import com.hai.entity.*;
import com.hai.enum_type.*;
import com.hai.model.*;
import com.hai.msg.entity.MsgTopic;
import com.hai.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.File;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping(value = "/highGas")
@Api(value = "团油业务接口")
public class HighGasController {

    private static Logger log = LoggerFactory.getLogger(HighGasController.class);

    @Resource
    private HighGasOilPriceService highGasOilPriceService;

    @Resource
    private HighOrderService highOrderService;

    @Resource
    private HighMerchantStoreService merchantStoreService;

    @Resource
    private HighMerchantAccountService merchantAccountService;

    @Resource
    private HighUserService highUserService;

    @Resource
    private HighOilCardService oilCardService;

    @Autowired
    private UserCenter userCenter;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private ShellGroupService shellGroupService;

    @RequestMapping(value="/getMerGasStatistical",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "查询商户油站统计")
    public ResponseData getMerGasStatistical() {
        try {
            UserInfoModel userInfoModel = userCenter.getSessionModel(UserInfoModel.class);
            if (userInfoModel == null || userInfoModel.getMerchant() == null) {
                log.error("HighGasController -> getMerGasStatistical() error!","");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }

            BigDecimal account = new BigDecimal("0");
            // 查询商户余额
            HighMerchantAccount merchantAccount = merchantAccountService.getMerAccountDetail(userInfoModel.getMerchant().getId());
            if (merchantAccount != null) {
                account = merchantAccount.getAmounts();
            }
            Map<String, Object> param = new HashMap<>();
            param.put("amount", account.subtract(merchantAccountService.countMerGasOilAmount(userInfoModel.getMerchant().getId())));
            param.put("storeList", merchantAccountService.getStoreGasOilAmountByMer(userInfoModel.getMerchant().getId()));

            return ResponseMsgUtil.success(param);

        } catch (Exception e) {
            log.error("HighGasController -> getMerGasStatistical() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/getGasStatistical",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "查询油站统计")
    public ResponseData getGasStatistical() {
        try {
            UserInfoModel userInfoModel = userCenter.getSessionModel(UserInfoModel.class);
            if (userInfoModel == null || userInfoModel.getMerchantStore() == null) {
                log.error("HighGasController -> disabledOil() error!","");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }
            Map<String, Object> param = new HashMap<>();;
            param.put("gasName", userInfoModel.getMerchantStore().getStoreName());

            if (userInfoModel.getSecUser().getObjectType().equals(UserObjectTypeEnum.type8.getType())
                && userInfoModel.getGasStaff().getPositionType().equals(GasPositionType.status2.getStatus())) {

                Map<String, Object> history = new HashMap<>();
                // 历史加油总金额
                Map<String, Object> historyTotal = highOrderService.getGasStaffHistoryOrderCount(userInfoModel.getGasStaff().getId(), "2,3,4,6,7");
                history.put("totalPrice", historyTotal.get("price"));
                history.put("totalCount", historyTotal.get("count"));

                // 历史加油金额
                Map<String, Object> historyIncomet = highOrderService.getGasStaffHistoryOrderCount(userInfoModel.getGasStaff().getId(), "2,3,6,7");
                history.put("incomePrice", historyIncomet.get("price"));
                history.put("incomeCount", historyIncomet.get("count"));

                // 历史退款
                Map<String, Object> historyRefund = highOrderService.getGasStaffHistoryOrderCount(userInfoModel.getGasStaff().getId(), "4");
                history.put("refundPrice", historyRefund.get("price"));
                history.put("refundCount", historyRefund.get("count"));
                param.put("history", history);


                Map<String, Object> today = new HashMap<>();
                // 今日加油总金额
                Map<String, Object> todayTotal = highOrderService.getGasStaffTheDayOrderCount(userInfoModel.getGasStaff().getId(), "2,3,4,6,7");
                today.put("totalPrice", todayTotal.get("price"));
                today.put("totalCount", todayTotal.get("count"));

                // 今日加油金额
                Map<String, Object> todayIncomet = highOrderService.getGasStaffTheDayOrderCount(userInfoModel.getGasStaff().getId(), "2,3,6,7");
                today.put("incomePrice", todayIncomet.get("price"));
                today.put("incomeCount", todayIncomet.get("count"));

                // 今日退款
                Map<String, Object> todayRefund = highOrderService.getGasStaffTheDayOrderCount(userInfoModel.getGasStaff().getId(), "4");
                today.put("refundPrice", todayRefund.get("price"));
                today.put("refundCount", todayRefund.get("count"));
                param.put("today", today);

            } else {
                Map<String, Object> history = new HashMap<>();
                // 历史加油总金额
                Map<String, Object> historyTotal = highOrderService.getGasHistoryOrderCount(userInfoModel.getMerchantStore().getId(), "2,3,4,6,7");
                history.put("totalPrice", historyTotal.get("price"));
                history.put("totalCount", historyTotal.get("count"));

                // 历史加油金额
                Map<String, Object> historyIncomet = highOrderService.getGasHistoryOrderCount(userInfoModel.getMerchantStore().getId(), "2,3,6,7");
                history.put("incomePrice", historyIncomet.get("price"));
                history.put("incomeCount", historyIncomet.get("count"));

                // 历史退款
                Map<String, Object> historyRefund = highOrderService.getGasHistoryOrderCount(userInfoModel.getMerchantStore().getId(), "4");
                history.put("refundPrice", historyRefund.get("price"));
                history.put("refundCount", historyRefund.get("count"));
                param.put("history", history);


                Map<String, Object> today = new HashMap<>();
                // 今日加油总金额
                Map<String, Object> todayTotal = highOrderService.getGasTheDayOrderCount(userInfoModel.getMerchantStore().getId(), "2,3,4,6,7");
                today.put("totalPrice", todayTotal.get("price"));
                today.put("totalCount", todayTotal.get("count"));

                // 今日加油金额
                Map<String, Object> todayIncomet = highOrderService.getGasTheDayOrderCount(userInfoModel.getMerchantStore().getId(), "2,3,6,7");
                today.put("incomePrice", todayIncomet.get("price"));
                today.put("incomeCount", todayIncomet.get("count"));

                // 今日退款
                Map<String, Object> todayRefund = highOrderService.getGasTheDayOrderCount(userInfoModel.getMerchantStore().getId(), "4");
                today.put("refundPrice", todayRefund.get("price"));
                today.put("refundCount", todayRefund.get("count"));
                param.put("today", today);
            }
            return ResponseMsgUtil.success(param);

        } catch (Exception e) {
            log.error("HighGasController -> getGasStatistical() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/getGasOrderList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询油站订单列表")
    public ResponseData getGasOrderList(@RequestParam(name = "orderNo", required = false) String orderNo,
                                        @RequestParam(name = "storeId", required = false) Long storeId,
                                        @RequestParam(name = "staffId", required = false) Long staffId,
                                        @RequestParam(name = "status", required = false) Integer status,
                                        @RequestParam(name = "oilNo", required = false) Integer oilNo,
                                        @RequestParam(name = "createTimeS", required = false) Long createTimeS,
                                        @RequestParam(name = "createTimeE", required = false) Long createTimeE,
                                        @RequestParam(name = "payTimeS", required = false) Long payTimeS,
                                        @RequestParam(name = "payTimeE", required = false) Long payTimeE,
                                        @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                        @RequestParam(name = "pageSize", required = true) Integer pageSize) {
        try {
            UserInfoModel userInfoModel = userCenter.getSessionModel(UserInfoModel.class);
            if (userInfoModel == null) {
                log.error("HighGasController -> disabledOil() error!","");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }
            Map<String, Object> param = new HashMap<>();
            // 用户来源 0：超级管理员  1：公司  2：商户  3：门店 4. 代理商 5.充值后台工商  6.团油代理商   7.团油业务员   8. 加油站员工
            if (userInfoModel.getSecUser().getObjectType().equals(2)) {
                if (storeId != null) {
                    param.put("storeId", storeId);
                } else {
                    String storeIdStr = "";
                    List<HighMerchantStore> storeList = merchantStoreService.getStoreListByMer(userInfoModel.getMerchant().getId());
                    for (HighMerchantStore store : storeList) {
                        if (StringUtils.isBlank(storeIdStr)) {
                            storeIdStr += store.getId().toString();
                        } else {
                            storeIdStr += "," + store.getId().toString();
                        }
                    }

                    if (StringUtils.isNotBlank(storeIdStr)) {
                        param.put("storeId", storeIdStr);
                    } else {
                        param.put("storeId", 0);
                    }
                }
                param.put("gasStaffId", staffId);

            } else if (userInfoModel.getSecUser().getObjectType().equals(3)) {
                param.put("storeId", userInfoModel.getMerchantStore().getId());
                param.put("gasStaffId", staffId);

            } else if (userInfoModel.getSecUser().getObjectType().equals(8)) {
                if (userInfoModel.getGasStaff().getPositionType().equals(GasPositionType.status1.getStatus())) {
                    param.put("storeId", userInfoModel.getMerchantStore().getId());
                }
                if (userInfoModel.getGasStaff().getPositionType().equals(GasPositionType.status2.getStatus())) {
                    param.put("gasStaffId", userInfoModel.getGasStaff().getId());
                }
            } else {
                log.error("HighGasController -> disabledOil() error!","");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }
            param.put("orderNo", orderNo);
            param.put("gasOilNo", oilNo);
            param.put("createTimeS", createTimeS);
            param.put("createTimeE", createTimeE);
            param.put("payTimeS", payTimeS);
            param.put("payTimeE", payTimeE);

            if (status == null) {
                param.put("status", "2,3,4,6,7");
            } else {
                param.put("status", status);
            }

            PageHelper.startPage(pageNum, pageSize);
            return ResponseMsgUtil.success(new PageInfo<>(highOrderService.getGasOrderList(param)));

        } catch (Exception e) {
            log.error("HighGasController -> getGasOrderList() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/countGasOrder",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "统计加油订单")
    public ResponseData countGasOrder(@RequestParam(name = "orderNo", required = false) String orderNo,
                                        @RequestParam(name = "storeId", required = false) Long storeId,
                                        @RequestParam(name = "staffId", required = false) Long staffId,
                                        @RequestParam(name = "status", required = false) Integer status,
                                        @RequestParam(name = "oilNo", required = false) Integer oilNo,
                                        @RequestParam(name = "createTimeS", required = false) Long createTimeS,
                                        @RequestParam(name = "createTimeE", required = false) Long createTimeE,
                                        @RequestParam(name = "payTimeS", required = false) Long payTimeS,
                                        @RequestParam(name = "payTimeE", required = false) Long payTimeE) {
        try {
            UserInfoModel userInfoModel = userCenter.getSessionModel(UserInfoModel.class);
            if (userInfoModel == null) {
                log.error("HighGasController -> disabledOil() error!","");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }
            Map<String, Object> param = new HashMap<>();
            // 用户来源 0：超级管理员  1：公司  2：商户  3：门店 4. 代理商 5.充值后台工商  6.团油代理商   7.团油业务员   8. 加油站员工
            if (userInfoModel.getSecUser().getObjectType().equals(2)) {
                if (storeId != null) {
                    param.put("storeId", storeId);
                } else {
                    String storeIdStr = "";
                    List<HighMerchantStore> storeList = merchantStoreService.getStoreListByMer(userInfoModel.getMerchant().getId());
                    for (HighMerchantStore store : storeList) {
                        if (StringUtils.isBlank(storeIdStr)) {
                            storeIdStr += store.getId().toString();
                        } else {
                            storeIdStr += "," + store.getId().toString();
                        }
                    }

                    if (StringUtils.isNotBlank(storeIdStr)) {
                        param.put("storeId", storeIdStr);
                    } else {
                        param.put("storeId", 0);
                    }
                }
                param.put("gasStaffId", staffId);

            } else if (userInfoModel.getSecUser().getObjectType().equals(3)) {
                param.put("storeId", userInfoModel.getMerchantStore().getId());
                param.put("gasStaffId", staffId);

            } else if (userInfoModel.getSecUser().getObjectType().equals(8)) {
                if (userInfoModel.getGasStaff().getPositionType().equals(GasPositionType.status1.getStatus())) {
                    param.put("storeId", userInfoModel.getMerchantStore().getId());
                }
                if (userInfoModel.getGasStaff().getPositionType().equals(GasPositionType.status2.getStatus())) {
                    param.put("gasStaffId", userInfoModel.getGasStaff().getId());
                }
            } else {
                log.error("HighGasController -> disabledOil() error!","");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }
            param.put("orderNo", orderNo);
            param.put("gasOilNo", oilNo);
            param.put("createTimeS", createTimeS);
            param.put("createTimeE", createTimeE);
            param.put("payTimeS", payTimeS);
            param.put("payTimeE", payTimeE);

            if (status == null) {
                param.put("status", "2,3,4,6,7");
            } else {
                param.put("status", status);
            }
            return ResponseMsgUtil.success(highOrderService.countGasOrder(param));

        } catch (Exception e) {
            log.error("HighGasController -> countGasOrder() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/getGasOrderCount",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询油站订单列表")
    public ResponseData getGasOrderCount(@RequestParam(name = "orderNo", required = false) String orderNo,
                                        @RequestParam(name = "storeId", required = false) Long storeId,
                                        @RequestParam(name = "staffId", required = false) Long staffId,
                                        @RequestParam(name = "status", required = false) Integer status,
                                        @RequestParam(name = "createTimeS", required = false) Long createTimeS,
                                        @RequestParam(name = "createTimeE", required = false) Long createTimeE,
                                        @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                        @RequestParam(name = "pageSize", required = true) Integer pageSize) {
        try {
            UserInfoModel userInfoModel = userCenter.getSessionModel(UserInfoModel.class);
            if (userInfoModel == null) {
                log.error("HighGasController -> disabledOil() error!","");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }
            Map<String, Object> param = new HashMap<>();
            // 用户来源 0：超级管理员  1：公司  2：商户  3：门店 4. 代理商 5.充值后台工商  6.团油代理商   7.团油业务员   8. 加油站员工
            if (userInfoModel.getSecUser().getObjectType().equals(2)) {
                if (storeId != null) {
                    param.put("storeId", storeId);
                } else {
                    String storeIdStr = "";
                    List<HighMerchantStore> storeList = merchantStoreService.getStoreListByMer(userInfoModel.getMerchant().getId());
                    for (HighMerchantStore store : storeList) {
                        if (StringUtils.isBlank(storeIdStr)) {
                            storeIdStr += store.getId().toString();
                        } else {
                            storeIdStr += "," + store.getId().toString();
                        }
                    }

                    if (StringUtils.isNotBlank(storeIdStr)) {
                        param.put("storeId", storeIdStr);
                    } else {
                        param.put("storeId", 0);
                    }
                }
                param.put("gasStaffId", staffId);

            } else if (userInfoModel.getSecUser().getObjectType().equals(3)) {
                param.put("storeId", userInfoModel.getMerchantStore().getId());
                param.put("gasStaffId", staffId);

            } else if (userInfoModel.getSecUser().getObjectType().equals(8)) {
                if (userInfoModel.getGasStaff().getPositionType().equals(GasPositionType.status1.getStatus())) {
                    param.put("storeId", userInfoModel.getMerchantStore().getId());
                }
                if (userInfoModel.getGasStaff().getPositionType().equals(GasPositionType.status2.getStatus())) {
                    param.put("gasStaffId", userInfoModel.getGasStaff().getId());
                }
            } else {
                log.error("HighGasController -> disabledOil() error!","");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }
            param.put("orderNo", orderNo);
            param.put("createTimeS", createTimeS);
            param.put("createTimeE", createTimeE);

            if (status == null) {
                param.put("status", "2,3,4,6,7");
            } else {
                param.put("status", status);
            }

            Map<String, Object> map = new HashMap<>();
            return ResponseMsgUtil.success(map);

        } catch (Exception e) {
            log.error("HighGasController -> getGasOrderCount() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/getGasSelectList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询油站选择列表")
    public ResponseData getGasSelectList() {
        try {
            UserInfoModel userInfoModel = userCenter.getSessionModel(UserInfoModel.class);
            if (userInfoModel == null) {
                log.error("HighGasController -> disabledOil() error!","");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }

            Map<String, Object> param = new HashMap<>();
            param.put("type", 1);
            param.put("sourceType", 1);
            param.put("status", 1);

            if (userInfoModel.getSecUser().getObjectType().equals(UserObjectTypeEnum.type0.getType())) {
                
            } else if (userInfoModel.getSecUser().getObjectType().equals(UserObjectTypeEnum.type1.getType())) {
                param.put("companyId", userInfoModel.getBsCompany().getId());
            } else {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }

            return ResponseMsgUtil.success(merchantStoreService.getMerchantStoreList(param));

        } catch (Exception e) {
            log.error("HighGasController -> getGasSelectList() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/exportGasOrder",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "导出油站订单")
    public ResponseData exportGasOrder(@RequestParam(name = "orderNo", required = false) String orderNo,
                                        @RequestParam(name = "storeId", required = false) Long storeId,
                                        @RequestParam(name = "staffId", required = false) Long staffId,
                                        @RequestParam(name = "status", required = false) Integer status,
                                        @RequestParam(name = "createTimeS", required = false) Long createTimeS,
                                        @RequestParam(name = "createTimeE", required = false) Long createTimeE) {
        try {
            UserInfoModel userInfoModel = userCenter.getSessionModel(UserInfoModel.class);
            if (userInfoModel == null) {
                log.error("HighGasController -> disabledOil() error!","");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }
            Map<String, Object> param = new HashMap<>();
            // 用户来源 0：超级管理员  1：公司  2：商户  3：门店 4. 代理商 5.充值后台工商  6.团油代理商   7.团油业务员   8. 加油站员工
            if (userInfoModel.getSecUser().getObjectType().equals(2)) {
                if (storeId != null) {
                    param.put("storeId", storeId);
                } else {
                    String storeIdStr = "";
                    List<HighMerchantStore> storeList = merchantStoreService.getStoreListByMer(userInfoModel.getMerchant().getId());
                    for (HighMerchantStore store : storeList) {
                        if (StringUtils.isBlank(storeIdStr)) {
                            storeIdStr += store.getId().toString();
                        } else {
                            storeIdStr += "," + store.getId().toString();
                        }
                    }

                    if (StringUtils.isNotBlank(storeIdStr)) {
                        param.put("storeId", storeIdStr);
                    } else {
                        param.put("storeId", 0);
                    }
                }
                param.put("gasStaffId", staffId);

            } else if (userInfoModel.getSecUser().getObjectType().equals(3)) {
                param.put("storeId", userInfoModel.getMerchantStore().getId());
                param.put("gasStaffId", staffId);

            } else if (userInfoModel.getSecUser().getObjectType().equals(8)) {
                if (userInfoModel.getGasStaff().getPositionType().equals(GasPositionType.status1.getStatus())) {
                    param.put("storeId", userInfoModel.getMerchantStore().getId());
                }
                if (userInfoModel.getGasStaff().getPositionType().equals(GasPositionType.status2.getStatus())) {
                    param.put("gasStaffId", userInfoModel.getGasStaff().getId());
                }
            } else {
                log.error("HighGasController -> disabledOil() error!","");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }
            param.put("orderNo", orderNo);
            param.put("createTimeS", createTimeS);
            param.put("createTimeE", createTimeE);

            if (status == null) {
                param.put("status", "2,3,4,6,7");
            } else {
                param.put("status", status);
            }

            List<String> headList = new ArrayList<>();
            headList.add("订单号");
            headList.add("油站名称");
            headList.add("加油员");
            headList.add("油品类型");
            headList.add("油品油号");
            headList.add("油枪号");
            headList.add("油枪价");
            headList.add("优惠价");
            headList.add("加油升数");
            headList.add("加油金额");
            headList.add("支付金额");
            headList.add("优惠金额");
            headList.add("创建时间");
            headList.add("状态");

            List<List<Object>> dataList = new ArrayList<>();
            List<Object> data;

            List<GasOrderModel> orderList = highOrderService.getGasOrderList(param);
            for (GasOrderModel orderModel: orderList) {
                data = new ArrayList<>();
                data.add(orderModel.getOrderNo());
                data.add(orderModel.getGasName());
                data.add(StringUtils.isNotBlank(orderModel.getGasStaffName())?orderModel.getGasStaffName():"未知");
                data.add(orderModel.getGasOilType().equals("1") ? "汽油": "柴油");
                data.add(orderModel.getGasOilNo() + "#");
                data.add(orderModel.getGasGunNo() + "号");
                data.add(orderModel.getGasPriceGun());
                data.add(orderModel.getGasPricePreferences());
                data.add(orderModel.getGasOilLiters());
                data.add(orderModel.getTotalPrice());
                data.add(orderModel.getPayRealPrice());
                data.add(orderModel.getDeductionPrice());
                data.add(DateUtil.date2String(orderModel.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
                data.add(OrderStatusEnum.getNameByType(orderModel.getStatus()));
                dataList.add(data);
            }

            String fileUrl = SysConst.getSysConfig().getFileUrl() + "/temporary/";
            String pathName = System.currentTimeMillis()+".xlsx";
            File file = new File(fileUrl);
            if (!file.exists()) {
                file.mkdirs();
            }
            EasyExcel.write(fileUrl+pathName).head(generationHead(headList)).sheet("加油订单").doWrite(dataList);

            return ResponseMsgUtil.success(pathName);

        } catch (Exception e) {
            log.error("HighGasController -> getGasOrderList() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/getGasOrderDetail",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询油站订单详情")
    public ResponseData getGasOrderDetail(@RequestParam(name = "orderNo", required = true) String orderNo) {
        try {

            return ResponseMsgUtil.success(highOrderService.getGasOrderDetail(orderNo));

        } catch (Exception e) {
            log.error("HighGasController -> getGasOrderDetail() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/disabledOil",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "禁用油品")
    public ResponseData disabledOil(@RequestBody JSONObject body) {
        try {
            if (body.getLong("storeId") == null || body.getInteger("oilNo") == null) {
                log.error("HighGasController -> disabledOil() error!","");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            // 查询油品价格
            HighGasOilPrice oilNo = highGasOilPriceService.getGasOilPriceByStoreAndOilNo(body.getLong("storeId"), body.getInteger("oilNo"));
            if (oilNo == null) {
                log.error("HighGasController -> disabledOil() error!","");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            oilNo.setStatus(GasOilPriceStatusEnum.status2.getStatus());
            highGasOilPriceService.editGasOilPrice(oilNo);

            return ResponseMsgUtil.success("操作成功");

        } catch (Exception e) {
            log.error("HighGasController -> disabledOil() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/enableOil",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "启用油品")
    public ResponseData enableOil(@RequestBody JSONObject body) {
        try {
            if (body.getLong("storeId") == null || body.getInteger("oilNo") == null) {
                log.error("HighGasController -> enableOil() error!","");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            // 查询油品价格
            HighGasOilPrice oilNo = highGasOilPriceService.getGasOilPriceByStoreAndOilNo(body.getLong("storeId"), body.getInteger("oilNo"));
            if (oilNo == null) {
                log.error("HighGasController -> enableOil() error!","");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            oilNo.setStatus(GasOilPriceStatusEnum.status1.getStatus());
            highGasOilPriceService.editGasOilPrice(oilNo);

            return ResponseMsgUtil.success("操作成功");

        } catch (Exception e) {
            log.error("HighGasController -> enableOil() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/getGasStoreList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询加油站列表")
    public ResponseData getGasStoreList(@RequestParam(name = "storeName", required = false) String storeName,
                                        @RequestParam(name = "distance", required = true) Integer distanceRecent,
                                        @RequestParam(name = "regionId", required = true) Long regionId,
                                        @RequestParam(name = "oilNoName", required = true) String oilNoName,
                                        @RequestParam(name = "longitude", required = true) String longitude,
                                        @RequestParam(name = "latitude", required = true) String latitude,
                                        @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                        @RequestParam(name = "pageSize", required = true) Integer pageSize
    ) {
        try {
            if (StringUtils.isBlank(storeName)) {
                storeName = null;
            }
            List<Map<String, Object>> storeList = highGasOilPriceService.getStoreListByOilNo(storeName,regionId, oilNoName);
            for (Map<String, Object> store : storeList) {
                double distance = CoordCommonUtil.getDistance(Double.valueOf(store.get("latitude").toString()), Double.valueOf(store.get("longitude").toString()), Double.valueOf(latitude), Double.valueOf(longitude));
                store.put("distance", Math.round(distance/100d)/10d);
            }
            List<Map<String, Object>> distance = storeList.stream().sorted(Comparator.comparingDouble(entry ->  Double.valueOf(entry.get("distance").toString()))).collect(Collectors.toList());
            Iterator<Map<String, Object>> iterator = distance.iterator();
            while (iterator.hasNext()) {
                if ((int)Math.round(Double.valueOf(iterator.next().get("distance").toString()))  > distanceRecent.intValue()) {
                    iterator.remove();
                }
            }
            return ResponseMsgUtil.success(PageUtil.initPageInfoObj(pageNum,distance.size(),pageSize,new PageInfo<>(distance)));

        } catch (Exception e) {
            log.error("HighGasController -> getGasDetailByStoreKey() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/getGasDetailByStoreKey",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据门店key 查询")
    public ResponseData getGasDetailByStoreKey(@RequestParam(name = "storeKey", required = true) String storeKey,
                                               @RequestParam(name = "longitude", required = true) String longitude,
                                               @RequestParam(name = "latitude", required = true) String latitude) {
        try {

            JSONObject jsonObject = TuanYouConfig.queryGasInfoByGasId(storeKey);
            if (jsonObject != null && jsonObject.getString("code").equals("200")) {
                JSONObject result = jsonObject.getJSONObject("result");
                double distance = CoordCommonUtil.getDistance(Double.valueOf(result.get("gasAddressLatitude").toString()), Double.valueOf(result.get("gasAddressLongitude").toString()), Double.valueOf(latitude), Double.valueOf(longitude));
                result.put("distance", Math.round(distance/100d)/10d);
                return ResponseMsgUtil.success(jsonObject.get("result"));
            }
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未获取到加油站信息");

        } catch (Exception e) {
            log.error("HighGasController -> getGasDetailByStoreKey() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/getGasPriceDetail",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据门店key和油号 查询油价")
    public ResponseData getGasPriceDetail(@RequestParam(name = "storeKey", required = true) String storeKey,
                                          @RequestParam(name = "oilNo", required = true) String oilNo) {
        try {

            JSONObject jsonObject = TuanYouConfig.queryCompanyPriceDetail(storeKey,oilNo);
            if (jsonObject != null && jsonObject.getString("code").equals("200")) {
                if(jsonObject.getJSONArray("result").size() == 0) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未获取到价格信息");
                }
                return ResponseMsgUtil.success(jsonObject.get("result"));
            }
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未获取到价格信息");

        } catch (Exception e) {
            log.error("HighGasController -> getGasPriceDetail() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/getGasSelfBuiltStationList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询油站列表")
    public ResponseData getGasSelfBuiltStationList(@RequestParam(name = "companyId", required = false) Long companyId,
                                                   @RequestParam(name = "merId", required = false) Long merId,
                                                   @RequestParam(name = "gasName", required = false) String gasName,
                                                   @RequestParam(name = "prestoreType", required = false) String prestoreType,
                                                   @RequestParam(name = "amountsEarlyWarningStatus", required = false) Boolean amountsEarlyWarningStatus,
                                                   @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                                   @RequestParam(name = "pageSize", required = true) Integer pageSize) {
        try {
            Map<String, Object> param = new HashMap<>();
            param.put("gasName", gasName);
            param.put("prestoreType", prestoreType);
            param.put("amountsEarlyWarningStatus", amountsEarlyWarningStatus);

            UserInfoModel userInfoModel = userCenter.getSessionModel(UserInfoModel.class);
            if (userInfoModel == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }

            if (userInfoModel.getSecUser().getObjectType().equals(UserObjectTypeEnum.type0.getType())) {
                param.put("merId", merId);

            } else if (userInfoModel.getSecUser().getObjectType().equals(UserObjectTypeEnum.type1.getType())) {
                param.put("companyId", userInfoModel.getBsCompany().getId());
                param.put("merId", merId);

            } else if (userInfoModel.getSecUser().getObjectType().equals(UserObjectTypeEnum.type2.getType())) {
                param.put("merId", userInfoModel.getMerchant().getId());

            } else {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }

            PageHelper.startPage(pageNum,pageSize);
            return ResponseMsgUtil.success(new PageInfo<>(merchantStoreService.getGasSelfBuiltStationList(param)));

        } catch (Exception e) {
            log.error("HighGasController -> getGasPriceDetail() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }


    @RequestMapping(value="/refuelingOrderRefund",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "订单退款")
    public ResponseData refuelingOrderRefund(@RequestBody JSONObject body) {
        try {

            UserInfoModel userInfoModel = userCenter.getSessionModel(UserInfoModel.class);
            if (userInfoModel == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            if(body == null && body.getLong("orderId") == null && StringUtils.isBlank(body.getString("refundContent"))) {
                log.error("HighOrderController --> refuelingOrderRefund() error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            HighOrder order = highOrderService.getOrderById(body.getLong("orderId"));
            if(order == null) {
                log.error("HighOrderController --> refuelingOrderRefund() error!", "未找到订单信息");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到订单信息");
            }
            // 订单状态：1 待支付  2 已支付  3.已完成  4. 已退款  5.已取消   6.退款中   7.拒绝退款
            if (order.getOrderStatus() != 3) {
                log.error("HighOrderController --> refuelingOrderRefund() error!", "退款失败，订单状态准许退款");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "退款失败，订单状态准许退款");
            }

            for (HighChildOrder childOrder : order.getHighChildOrderList()) {
                if (!childOrder.getGoodsType().equals(3)) {
                    log.error("HighOrderController --> refuelingOrderRefund() error!", "退款失败，不属于加油站订单");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "退款失败，不属于加油站订单");
                }
                // 查询加油站
                HighMerchantStoreModel store = merchantStoreService.getMerchantStoreById(childOrder.getGoodsId());
                if (store == null) {
                    log.error("HighOrderController --> refuelingOrderRefund() error!", "退款失败，未找到加油站信息");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "退款失败，未找到加油站信息");
                }

                // 油站来源，根据不同的来源，请求不同的退款业务接口。
                // 团油     退款需要申请。不是实时退款
                // 加好油   实时退款，退款成功就可以退款给用户
                // 金猪加油  没有线上退款接口，线下核实后直接退款给用户。
                if (store.getSourceType().equals(MerchantStoreSourceType.type2.getNumber())) {
                    JSONObject object = TuanYouConfig.refuelingOrderRefund(order.getMemPhone(), order.getOrderNo(), body.getString("refundContent"));
                    if (object == null || !object.getString("code").equals("200")) {
                        log.error("HighOrderController --> refuelingOrderRefund() error!", "提交退款审核失败," + object.getString("message"));
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "提交退款审核失败，" + object.getString("message"));
                    }
                    order.setOrderStatus(6);
                    highOrderService.updateOrderDetail(order);
                }

                if (store.getSourceType().equals(MerchantStoreSourceType.type3.getNumber())) {
                    JSONObject object = shellGroupService.gasSyncRefund(order.getPayTime(), order.getOrderNo());
                    if (!object.getString("status").equals("SUCCESS")) {
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "退款失败，原因：" + object.getString("message"));
                    }
                    order.setOrderStatus(6);
                    highOrderService.updateOrderDetail(order);
                }


                // 用户支付金额原路退款
                // 来源类型  1：平台自建   2：团油
                if (store.getSourceType().equals(MerchantStoreSourceType.type1.getNumber())
                    || store.getSourceType().equals(MerchantStoreSourceType.type3.getNumber())
                    || store.getSourceType().equals(MerchantStoreSourceType.type4.getNumber())
                ) {

                    if (order.getPayType() == 2) {
                        OrderRefundModel orderRefundModel = WxOrderConfig.orderToRefund(order.getPaySerialNo(), order.getPayRealPrice(), order.getAccountMerchantNum(), order.getPayRealPrice());
                        if(orderRefundModel.getResult_code().equals("SUCCESS")) {
                            order.setOrderStatus(4);
                            order.setRefundTime(new Date());
                            order.setRefundPrice(order.getPayRealPrice());
                            highOrderService.updateOrderDetail(order);
                        }
                    } else if (order.getPayType() == 3){
                        String remark = "订单" + order.getOrderNo() + "退款，退还积分：" +  order.getPayGold();
                        // 积分退款
                        highUserService.goldHandle(order.getMemId(), order.getPayGold(),1, 3, order.getId() , remark);
                        order.setOrderStatus(4);
                        order.setRefundTime(new Date());
                        order.setRefundPrice(order.getPayRealPrice());
                        highOrderService.updateOrderDetail(order);

                    } else if (order.getPayType() == 4) {
                        String refundOrderNo = String.valueOf(System.currentTimeMillis());
                        JSONObject refund = HuiLianTongUnionCardConfig.refund(refundOrderNo, order.getPaySerialNo());
                        if(!refund.getString("respCode").equals("0000")) {
                            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR,refund.getString("respMessage"));
                        }
                        JSONObject consumptionResult = HuiLianTongUnionCardConfig.resolveResponse(refund.getString("data"));
                        if (consumptionResult.getBoolean("success") != true) {
                            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "交易失败!"+consumptionResult.getString("message"));
                        }
                        order.setOrderStatus(4);
                        order.setRefundTime(new Date());
                        order.setRefundPrice(order.getPayRealPrice());
                        highOrderService.updateOrderDetail(order);
                    } else if (order.getPayType().equals(OrderPayTypeEnum.type7.getType())) {
                        // 油卡退款
                        oilCardService.refund(order.getOrderNo());
                    }

                    // 预存类型  0：非预存  1：预存门店
                    if (store.getPrestoreType().equals(1)) {
                        Map<String, Object> pushParam = new HashMap<>();
                        pushParam.put("businessType", MerStoreAmountTypeEnum.type1.getType());
                        pushParam.put("storeId", store.getId());
                        pushParam.put("price", order.getTotalPrice());
                        pushParam.put("sourceType", MerStoreAmountSourceTypeEnum.type3.getType());
                        pushParam.put("sourceId", order.getId());
                        pushParam.put("sourceContent", "订单号：" + order.getOrderNo() + ",退款金额：￥" + order.getTotalPrice());
                        pushParam.put("opUserId", userInfoModel.getSecUser().getId());
                        pushParam.put("opUserName", userInfoModel.getSecUser().getUserName());
                        // 退款到预存余额
                        this.redisTemplate.boundListOps(MsgTopic.MerStoreAccount.getName()).leftPush(pushParam);
                    }

                    order.setOrderStatus(4);
                    order.setRefundTime(new Date());
                    order.setRefundContent(body.getString("refundContent"));
                    highOrderService.updateOrderDetail(order);
                }
            }
            return ResponseMsgUtil.success("操作成功");

        } catch (Exception e) {
            log.error("HighGasController -> refuelingOrderRefund() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

    /**
     * 生成头部
     * @param headList
     * @return
     */
    private static List<List<String>> generationHead(List<String> headList) {
        List<List<String>> list = new ArrayList<>();
        List<String> head;
        for (String headStr : headList) {
            head = new ArrayList<>();
            head.add(headStr);
            list.add(head);
        }
        return list;
    }

   /* @RequestMapping(value="/refuelingOrderPush",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "推送订单")
    public ResponseData refuelingOrderPush() {
        try {

            Map<String,Object> map = new HashMap<>();
            map.put("gasId", "CS000116576");
            map.put("oilNo", "92");
            map.put("gunNo", 1);
            BigDecimal priceGun = new BigDecimal("6");
            BigDecimal priceVip = new BigDecimal("4.9");
            //BigDecimal priceGun = new BigDecimal("5.58");
            //BigDecimal priceVip = new BigDecimal("5.58");
            map.put("priceGun", priceGun);  // 枪单价
            map.put("priceVip", priceVip);  // 优惠价
            map.put("driverPhone", "17726395120");
            map.put("thirdSerialNo", new Date().getTime());


            BigDecimal refuelingAmount = new BigDecimal("1200").divide(priceGun,2,BigDecimal.ROUND_HALF_UP).multiply(priceVip).setScale(2,BigDecimal.ROUND_HALF_UP);
            map.put("refuelingAmount", refuelingAmount);
            JSONObject orderPushObject = TuanYouConfig.refuelingOrderPush(map);
            if (orderPushObject == null || !orderPushObject.getString("code").equals("200")) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "提交订单，出现了未知错误");
            }
            JSONObject result = orderPushObject.getJSONObject("result");
            return ResponseMsgUtil.success(result.getString("orderNo"));
            //return ResponseMsgUtil.success(map);


        } catch (Exception e) {
            log.error("HighGasController -> refuelingOrderPush() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/queryThirdOrderDretail",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询订单信息")
    public ResponseData queryThirdOrderDretail() {
        try {


            return ResponseMsgUtil.success(TuanYouConfig.queryThirdOrderDretail("1624611159129"));
            //return ResponseMsgUtil.success(map);


        } catch (Exception e) {
            log.error("HighGasController -> queryThirdOrderDretail() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/test",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "测试")
    public ResponseData test() {
        try {

            String data = "{\"data\":\"ui2KbK5jpLtw7YaA52uSt1TzDpaE5OjeW5O6xg+saM4nN4aVnpoT1aTgJwQt/DuNSbs7LrX6q1B0cpW5T531ltYl1ERxyKXqZyMKBNWzDFuB5QSww22VGfypchGNm+oW\",\"timestamp\":1624611912047,\"companyCode\":\"208241666939552\"}";

            JSONObject jsonObject = JSONObject.parseObject(data, JSONObject.class);
            //return ResponseMsgUtil.success(AESEncodeUtil.aesDecryptByBytes(AESEncodeUtil.base64Decode(jsonObject.getString("data")), SysConst.getSysConfig().getTuanYouAppSecret()));
            return ResponseMsgUtil.success(CommonSysConst.getSysConfig().getTuanYouUrl());

        } catch (Exception e) {
            log.error("HighGasController -> queryThirdOrderDretail() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }*/

}
