package com.web.controller.business;

import com.alibaba.excel.EasyExcel;
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.ResponseMsgUtil;
import com.hai.entity.HighGasOrder;
import com.hai.enum_type.MerchantStoreSourceType;
import com.hai.enum_type.UserObjectTypeEnum;
import com.hai.enum_type.UserRoleTypeEnum;
import com.hai.model.ResponseData;
import com.hai.model.UserInfoModel;
import com.hai.order.model.ExportGasOrderModel;
import com.hai.order.service.OrderService;
import com.hai.order.service.OrderServiceExt;
import com.hai.order.type.OrderOilStatus;
import com.hai.order.type.OrderPayType;
import com.hai.service.HighGasOrderService;
import com.web.config.SysConst;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

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

@Controller
@RequestMapping(value = "oil")
@Api(value = "加油订单业务")
public class OrderOilController {

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

    @Resource
    private UserCenter userCenter;

    @Resource
    private OrderService orderService;

    @Resource
    private OrderServiceExt orderServiceExt;

    @Resource
    private HighGasOrderService gasOrderService;

    @RequestMapping(value="/getOilOrderList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询油站订单列表")
    public ResponseData getOilOrderList(@RequestParam(name = "companyId", required = false) Long companyId,
                                        @RequestParam(name = "merId", required = false) Long merId,
                                        @RequestParam(name = "storeId", required = false) Long storeId,
                                        @RequestParam(name = "storeName", required = false) String storeName,
                                        @RequestParam(name = "orderNo", required = false) String orderNo,
                                        @RequestParam(name = "childOrderNo", required = false) String childOrderNo,
                                        @RequestParam(name = "memPhone", required = false) String memPhone,
                                        @RequestParam(name = "memCardType", required = false) Integer memCardType,
                                        @RequestParam(name = "memCardNo", required = false) String memCardNo,
                                        @RequestParam(name = "gasOilType", required = false) Integer gasOilType,
                                        @RequestParam(name = "payType", required = false) Integer payType,
                                        @RequestParam(name = "status", required = false) Integer status,
                                        @RequestParam(name = "gasOrgId", required = false) Long gasOrgId,
                                        @RequestParam(name = "gasAgentId", required = false) Long gasAgentId,
                                        @RequestParam(name = "gasSalesmanId", required = false) Long gasSalesmanId,
                                        @RequestParam(name = "gasStaffName", required = false) String gasStaffName,
                                        @RequestParam(name = "gasOilNo", required = false) String gasOilNo,
                                        @RequestParam(name = "gasCarLicensePlate", required = false) String gasCarLicensePlate,
                                        @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 = "refundTimeS", required = false) Long refundTimeS,
                                        @RequestParam(name = "refundTimeE", required = false) Long refundTimeE,
                                        @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("OrderBWebController -> getGasOrderList() error!", "用户身份错误或已过期");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.SEC_USER_EXPIRED, "");
            }
            Map<String, Object> param = new HashMap<>();
            param.put("gasOrgId", gasOrgId);
            param.put("gasAgentId", gasAgentId);
            param.put("gasSalesmanId", gasAgentId);
            param.put("memCardType", memCardType);
            param.put("memCardNo", memCardNo);
            param.put("memPhone", memPhone);
            param.put("gasOilNo", gasOilNo);
            param.put("gasCarLicensePlate", gasCarLicensePlate);
            param.put("orderNo", orderNo);
            param.put("childOrderNo", childOrderNo);
            param.put("payType", payType);
            param.put("status", status);
            param.put("createTimeS", createTimeS);
            param.put("createTimeE", createTimeE);
            param.put("payTimeS", payTimeS);
            param.put("payTimeE", payTimeE);
            param.put("refundTimeS", refundTimeS);
            param.put("refundTimeE", refundTimeE);

            if (userInfoModel.getSecUser().getObjectType().equals(UserObjectTypeEnum.type0.getType())) {
                param.put("companyId", companyId);
                param.put("merId", merId);
                param.put("storeId", storeId);
                param.put("storeName", storeName);
                param.put("gasOrgId", gasOrgId);
                param.put("gasAgentId", gasAgentId);
                param.put("gasStaffName", gasStaffName);

            } else if (userInfoModel.getSecUser().getObjectType().equals(UserObjectTypeEnum.type1.getType())) {
                if (userInfoModel.getSecUser().getAdminFlag().equals(0)) {
                    param.put("gasOrgId", userInfoModel.getBsOrganization().getId());
                }
                param.put("companyId", userInfoModel.getBsCompany().getId());
                param.put("merId", merId);
                param.put("storeId", storeId);
                param.put("storeName", storeName);
                param.put("gasStaffName", gasStaffName);

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

            } else if (userInfoModel.getSecUser().getObjectType().equals(UserObjectTypeEnum.type3.getType())) {
                param.put("storeId", userInfoModel.getMerchantStore().getId());
                param.put("gasStaffName", gasStaffName);

            } else if (userInfoModel.getSecUser().getObjectType().equals(UserObjectTypeEnum.type6.getType())) {
                param.put("gasAgentId", userInfoModel.getHighTyAgent().getId());
                param.put("gasSalesmanId", gasSalesmanId);
                param.put("storeId", storeId);
                param.put("storeName", storeName);
                param.put("gasStaffName", gasStaffName);

            } else if (userInfoModel.getSecUser().getObjectType().equals(UserObjectTypeEnum.type7.getType())) {
                param.put("gasSalesmanId", userInfoModel.getHighTySalesman().getId());
                param.put("storeId", storeId);
                param.put("storeName", storeName);
                param.put("gasStaffName", gasStaffName);

            } else if (userInfoModel.getSecUser().getObjectType().equals(UserObjectTypeEnum.type8.getType())) {
                param.put("gasStaffId", userInfoModel.getGasStaff().getId());
                param.put("storeId", storeId);
                param.put("storeName", storeName);

            } else {
                log.error("OrderBWebController -> getGasOrderList() error!", "未知用户身份");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知用户身份");
            }


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

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


    @RequestMapping(value="/getOrderByOrderNo",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据订单号查询")
    public ResponseData getOrderByOrderNo(@RequestParam(name = "orderNo", required = true) String orderNo) {
        try {

            return ResponseMsgUtil.success(gasOrderService.getDetailByOrderNo(orderNo));

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

    @RequestMapping(value="/getOilOrderDetail",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询油站详情")
    public ResponseData getOilOrderDetail(@RequestParam(name = "orderNo", required = true) String orderNo) {
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("tradeOrder", orderService.getOrderDetailByNo(orderNo));
            map.put("gasOrder", gasOrderService.getDetailByOrderNo(orderNo));

            return ResponseMsgUtil.success(map);

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

    @RequestMapping(value="/exportOilOrder",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "导出加油订单")
    public ResponseData exportOilOrder(@RequestParam(name = "companyId", required = false) Long companyId,
                                       @RequestParam(name = "merId", required = false) Long merId,
                                       @RequestParam(name = "storeId", required = false) Long storeId,
                                       @RequestParam(name = "storeName", required = false) String storeName,
                                       @RequestParam(name = "orderNo", required = false) String orderNo,
                                       @RequestParam(name = "childOrderNo", required = false) String childOrderNo,
                                       @RequestParam(name = "memPhone", required = false) String memPhone,
                                       @RequestParam(name = "memCardType", required = false) Integer memCardType,
                                       @RequestParam(name = "memCardNo", required = false) String memCardNo,
                                       @RequestParam(name = "gasOilType", required = false) Integer gasOilType,
                                       @RequestParam(name = "payType", required = false) Integer payType,
                                       @RequestParam(name = "status", required = false) Integer status,
                                       @RequestParam(name = "gasOrgId", required = false) Long gasOrgId,
                                       @RequestParam(name = "gasAgentId", required = false) Long gasAgentId,
                                       @RequestParam(name = "gasSalesmanId", required = false) Long gasSalesmanId,
                                       @RequestParam(name = "gasStaffName", required = false) String gasStaffName,
                                       @RequestParam(name = "gasOilNo", required = false) String gasOilNo,
                                       @RequestParam(name = "gasCarLicensePlate", required = false) String gasCarLicensePlate,
                                       @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 = "refundTimeS", required = false) Long refundTimeS,
                                       @RequestParam(name = "refundTimeE", required = false) Long refundTimeE
    ) {
        try {
            UserInfoModel userInfoModel = userCenter.getSessionModel(UserInfoModel.class);
            if (userInfoModel == null) {
                log.error("OrderBWebController -> exportGasOrderList() error!", "用户身份错误或已过期");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.SEC_USER_EXPIRED, "");
            }
            Map<String, Object> param = new HashMap<>();
            param.put("gasOrgId", gasOrgId);
            param.put("gasAgentId", gasAgentId);
            param.put("gasSalesmanId", gasAgentId);
            param.put("memCardType", memCardType);
            param.put("memCardNo", memCardNo);
            param.put("memPhone", memPhone);
            param.put("gasOilNo", gasOilNo);
            param.put("gasCarLicensePlate", gasCarLicensePlate);
            param.put("orderNo", orderNo);
            param.put("childOrderNo", childOrderNo);
            param.put("payType", payType);
            param.put("status", status);
            param.put("createTimeS", createTimeS);
            param.put("createTimeE", createTimeE);
            param.put("payTimeS", payTimeS);
            param.put("payTimeE", payTimeE);
            param.put("refundTimeS", refundTimeS);
            param.put("refundTimeE", refundTimeE);

            if (userInfoModel.getSecUser().getObjectType().equals(UserObjectTypeEnum.type0.getType())) {
                param.put("companyId", companyId);
                param.put("merId", merId);
                param.put("storeId", storeId);
                param.put("storeName", storeName);
                param.put("gasOrgId", gasOrgId);
                param.put("gasAgentId", gasAgentId);
                param.put("gasStaffName", gasStaffName);

            } else if (userInfoModel.getSecUser().getObjectType().equals(UserObjectTypeEnum.type1.getType())) {
                if (userInfoModel.getSecUser().getAdminFlag().equals(0)) {
                    param.put("gasOrgId", userInfoModel.getBsOrganization().getId());
                }
                param.put("companyId", userInfoModel.getBsCompany().getId());
                param.put("merId", merId);
                param.put("storeId", storeId);
                param.put("storeName", storeName);
                param.put("gasStaffName", gasStaffName);

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

            } else if (userInfoModel.getSecUser().getObjectType().equals(UserObjectTypeEnum.type3.getType())) {
                param.put("storeId", userInfoModel.getMerchantStore().getId());
                param.put("gasStaffName", gasStaffName);

            } else if (userInfoModel.getSecUser().getObjectType().equals(UserObjectTypeEnum.type6.getType())) {
                param.put("gasAgentId", userInfoModel.getHighTyAgent().getId());
                param.put("gasSalesmanId", gasSalesmanId);
                param.put("storeId", storeId);
                param.put("storeName", storeName);
                param.put("gasStaffName", gasStaffName);

            } else if (userInfoModel.getSecUser().getObjectType().equals(UserObjectTypeEnum.type7.getType())) {
                param.put("gasSalesmanId", userInfoModel.getHighTySalesman().getId());
                param.put("storeId", storeId);
                param.put("storeName", storeName);
                param.put("gasStaffName", gasStaffName);

            } else if (userInfoModel.getSecUser().getObjectType().equals(UserObjectTypeEnum.type8.getType())) {
                param.put("gasStaffId", userInfoModel.getGasStaff().getId());
                param.put("storeId", storeId);
                param.put("storeName", storeName);

            } else {
                log.error("OrderBWebController -> getGasOrderList() error!", "未知用户身份");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知用户身份");
            }

            // 查询数据
            List<HighGasOrder> orderList = gasOrderService.getGasOrderList(param);

            List<ExportGasOrderModel> dataList = new ArrayList<>();
            ExportGasOrderModel model;

            for (HighGasOrder gasOrder : orderList) {
                model = new ExportGasOrderModel();
                model.setOrderNo(gasOrder.getOrderNo());
                model.setStoreName(gasOrder.getStoreName());
                model.setGasStaffName(gasOrder.getGasStaffName());
                model.setGasCarLicensePlate(gasOrder.getGasCarLicensePlate());
                model.setMemPhone(gasOrder.getMemPhone());
                model.setGasRefuelPrice(gasOrder.getGasRefuelPrice());
                model.setGasOilLiters(gasOrder.getGasOilLiters());
                model.setGasDiscount(gasOrder.getGasDiscount().compareTo(new BigDecimal("1")) != 0?gasOrder.getGasDiscount().multiply(new BigDecimal("100")).setScale(2).toString():"无");
                model.setGasOilSubsidy(gasOrder.getGasOilSubsidy());
                model.setGasOilNo(gasOrder.getGasOilNo() + "#");
                model.setGasGunNo(gasOrder.getGasGunNo() + "号枪");
                model.setGasPricePlatform(gasOrder.getGasPricePlatform());
                model.setGasPriceGun(gasOrder.getGasPriceGun());
                model.setGasPriceOfficial(gasOrder.getGasPriceOfficial());
                model.setPayTypeName(gasOrder.getPayType()!=null?OrderPayType.getDataByType(gasOrder.getPayType()).getName():"未支付");
                model.setTotalDeductionPrice(gasOrder.getTotalDeductionPrice());
                model.setDeductionCouponPrice(gasOrder.getDeductionCouponPrice());
                model.setDeductionProductPrice(gasOrder.getDeductionProductPrice());
                model.setPayablePrice(gasOrder.getPayablePrice());
                model.setPayGold(gasOrder.getPayGold()==null?null:gasOrder.getPayGold()/100);
                model.setPayPrice(gasOrder.getPayPrice()!=null?gasOrder.getPayPrice().toString():"未支付");
                model.setStatus(OrderOilStatus.getNameByType(gasOrder.getStatus()));
                model.setCreateTime(gasOrder.getCreateTime());
                model.setPayTime(gasOrder.getPayTime());
                model.setRefundTime(gasOrder.getRefundTime());
                model.setCancelTime(gasOrder.getCancelTime());
                model.setCompanyName(gasOrder.getMerName());
                model.setMerName(gasOrder.getMerName());
                model.setGasSalesmanName(gasOrder.getGasSalesmanName());
                model.setGasAgentName(gasOrder.getGasAgentName());
                model.setGasOrgName(gasOrder.getGasOrgName());
                model.setChannelTypeName(MerchantStoreSourceType.getNameByType(gasOrder.getChannelType()));
                dataList.add(model);
            }

            String fileUrl = SysConst.getSysConfig().getFileUrl() + "/temporary/";
            String pathName = System.currentTimeMillis()+".xlsx";
            File file = new File(fileUrl);
            if (!file.exists()) {
                file.mkdirs();
            }

            Set<String> includeColumnFiledNames = new HashSet<String>();
            includeColumnFiledNames.add("orderNo");
            includeColumnFiledNames.add("memPhone");
            includeColumnFiledNames.add("gasCarLicensePlate");
            includeColumnFiledNames.add("gasRefuelPrice");
            includeColumnFiledNames.add("gasOilLiters");
            includeColumnFiledNames.add("gasDiscount");
            includeColumnFiledNames.add("gasOilSubsidy");
            includeColumnFiledNames.add("gasOilNo");
            includeColumnFiledNames.add("gasGunNo");
            includeColumnFiledNames.add("gasPricePlatform");
            includeColumnFiledNames.add("gasPriceGun");
            includeColumnFiledNames.add("gasPriceOfficial");
            includeColumnFiledNames.add("payTypeName");
            includeColumnFiledNames.add("totalDeductionPrice");
            includeColumnFiledNames.add("deductionCouponPrice");
            includeColumnFiledNames.add("deductionProductPrice");
            includeColumnFiledNames.add("payablePrice");
            includeColumnFiledNames.add("payGold");
            includeColumnFiledNames.add("payPrice");
            includeColumnFiledNames.add("status");
            includeColumnFiledNames.add("createTime");
            includeColumnFiledNames.add("payTime");
            includeColumnFiledNames.add("refundTime");
            includeColumnFiledNames.add("cancelTime");
            includeColumnFiledNames.add("channelTypeName");

            if (!userInfoModel.getSecRole().getRoleType().equals(UserRoleTypeEnum.type3.getType())
                && !userInfoModel.getSecRole().getRoleType().equals(UserRoleTypeEnum.type10.getType())) {
                includeColumnFiledNames.add("storeName");
            }
            if (!userInfoModel.getSecRole().getRoleType().equals(UserRoleTypeEnum.type10.getType())) {
                includeColumnFiledNames.add("gasStaffName");
            }

            if (userInfoModel.getSecRole().getRoleType().equals(UserRoleTypeEnum.type0.getType())
                || userInfoModel.getSecRole().getRoleType().equals(UserRoleTypeEnum.type1.getType())) {
                includeColumnFiledNames.add("companyName");
            }

            if (userInfoModel.getSecRole().getRoleType().equals(UserRoleTypeEnum.type0.getType())
                    || userInfoModel.getSecRole().getRoleType().equals(UserRoleTypeEnum.type1.getType())
                    || userInfoModel.getSecRole().getRoleType().equals(UserRoleTypeEnum.type5.getType())) {
                includeColumnFiledNames.add("merName");
                includeColumnFiledNames.add("gasOrgName");
                includeColumnFiledNames.add("gasAgentName");
            }

            if (userInfoModel.getSecRole().getRoleType().equals(UserRoleTypeEnum.type0.getType())
                    || userInfoModel.getSecRole().getRoleType().equals(UserRoleTypeEnum.type1.getType())
                    || userInfoModel.getSecRole().getRoleType().equals(UserRoleTypeEnum.type5.getType())
                    || userInfoModel.getSecRole().getRoleType().equals(UserRoleTypeEnum.type8.getType())) {
                includeColumnFiledNames.add("gasSalesmanName");
            }

            EasyExcel.write(fileUrl+pathName)
                    .head(ExportGasOrderModel.class)
                    .includeColumnFiledNames(includeColumnFiledNames)
                    .sheet("交易订单")
                    .doWrite(dataList);
            return ResponseMsgUtil.success(pathName);

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

}
