package com.cweb.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import com.hfkj.channel.gas.newlink.NewLinkGasService;
import com.hfkj.channel.gas.newlink.NewLinkRequestService;
import com.hfkj.channel.gas.shell.CqShellPetroleumGasService;
import com.hfkj.channel.gas.shell.CqShellPetroleumRequestService;
import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.common.security.UserCenter;
import com.hfkj.common.utils.ResponseMsgUtil;
import com.hfkj.entity.*;
import com.hfkj.model.*;
import com.hfkj.service.agent.BsAgentPriceService;
import com.hfkj.service.discount.BsDiscountUserService;
import com.hfkj.service.gas.BsGasChannelPriceWeekService;
import com.hfkj.service.gas.BsGasService;
import com.hfkj.service.spread.BsUserSpreadOilChannelService;
import com.hfkj.sysenum.discount.DiscountTypeEnum;
import com.hfkj.sysenum.merchant.MerchantSourceTypeEnum;
import com.hfkj.sysenum.agent.AgentPriceTypeEnum;
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.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;

@Controller
@RequestMapping(value = "/gas")
@Api(value = "油站管理")
public class BsGasController {
    private static Logger log = LoggerFactory.getLogger(BsGasController.class);
    @Resource
    private BsGasService gasService;
    @Resource
    private BsAgentPriceService agentPriceService;
    @Resource
    private NewLinkGasService newLinkGasService;
    @Resource
    private CqShellPetroleumGasService cqShellPetroleumGasService;
    @Resource
    private BsGasChannelPriceWeekService gasChannelPriceWeekService;
    @Resource
    private BsUserSpreadOilChannelService userSpreadOilChannelService;

    @RequestMapping(value="/refresh",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "refresh")
    public ResponseData refresh(@RequestParam(name = "type", required = true) Integer type) {
        try {

            if (MerchantSourceTypeEnum.type2.getNumber().equals(type)) {
                newLinkGasService.refresh();

            } else if (MerchantSourceTypeEnum.type3.getNumber().equals(type)) {
                cqShellPetroleumGasService.refresh();
            }
            return ResponseMsgUtil.success("");

        } catch (Exception e) {
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/queryGasInfoByGasId",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "queryGasInfoByMerNo")
    public ResponseData queryGasInfoByMerNo(@RequestParam(name = "type", required = true) Integer type,
                                            @RequestParam(name = "merNo", required = true) String merNo) {
        try {
            JSONObject data = null;
            if (MerchantSourceTypeEnum.type2.getNumber().equals(type)) {
                data = NewLinkRequestService.queryGasInfoByGasId(merNo);

            } else if (MerchantSourceTypeEnum.type3.getNumber().equals(type)) {
                data = CqShellPetroleumRequestService.gasStationQueryDetail(merNo);
            }
            return ResponseMsgUtil.success(data);

        } catch (Exception e) {
            return ResponseMsgUtil.exception(e);
        }
    }


    @RequestMapping(value="/oilPriceCompute",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "油价计算")
    public ResponseData oilPriceCompute(@RequestParam(name = "agentMerId", required = false) Long agentMerId,
                                        @RequestParam(name = "userDiscountId", required = false) Long userDiscountId,
                                        @RequestParam(name = "refuelPrice", required = true) BigDecimal refuelPrice,
                                        @RequestParam(name = "merNo", required = true) String merNo,
                                        @RequestParam(name = "oilNo", required = true) String oilNo) {
        try {
            // 计算价格
            return ResponseMsgUtil.success(gasService.refuelPriceCompute(refuelPrice, merNo, oilNo, agentMerId, userDiscountId));

        } catch (Exception e) {
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/queryGasList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询加油站列表")
    public ResponseData queryGasList(@RequestParam(name = "agentMerId", required = false) Long agentMerId,
                                     @RequestParam(name = "gasName", required = false) String gasName,
                                     @RequestParam(name = "distanceLimit", required = false) Integer distanceLimit,
                                     @RequestParam(name = "oilNo", required = true) String oilNo,
                                     @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 {

            PageHelper.startPage(pageNum,pageSize);
            PageInfo<GasListModel> pageInfo = new PageInfo<>(gasService.getGasList(longitude, latitude, oilNo, gasName, distanceLimit, true));

            for (GasListModel gas : pageInfo.getList()) {
                // 计算优惠
                GasPayPriceModel compute = gasService.refuelPriceCompute(new BigDecimal("100"), gas.getMerNo(), oilNo, agentMerId, null);
                gas.setPriceVip(compute.getPricePlatform());
                gas.setOilDiscount(compute.getTotalPreferences().compareTo(new BigDecimal("0")) > 0 ? Arrays.asList("加100省"+ compute.getTotalPreferences()) : new ArrayList<>());

                // 查询渠道个人推广费率
                BsUserSpreadOilChannel channel = userSpreadOilChannelService.getDetailByChannel(gas.getSourceType());
                if (channel == null) {
                    gas.setRebate(new BigDecimal("0"));
                    gas.setRebateOne(new BigDecimal("0"));
                    gas.setRebateTwo(new BigDecimal("0"));
                } else {
                    gas.setRebate(channel.getRebate());
                    gas.setRebateOne(channel.getRebateOne());
                    gas.setRebateTwo(channel.getRebateTwo());
                }
            }
            return ResponseMsgUtil.success(pageInfo);

        } catch (Exception e) {
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/queryGasDetail",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询加油站详情")
    public ResponseData queryGasDetail(@RequestParam(name = "merNo", required = true) String merNo,
                                       @RequestParam(name = "agentMerId", required = false) Long agentMerId) {
        try {
            // 查询油站详情
            GasModel gasDetail = gasService.getGasDetail(merNo);
            if (gasDetail == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的油站");
            }

            for (BsGasOilPrice oilPrice : gasDetail.getGasOilPrice()) {
                BigDecimal discount = new BigDecimal("100");
                if (agentMerId != null) {
                    // 查询代理价格
                    BsAgentPrice agentPrice = agentPriceService.getDetail(agentMerId, oilPrice.getOilNo());
                    if (agentPrice != null) {
                        discount = agentPrice.getPriceRate();
                    }
                } else {
                 /*   // 查询平台价格
                    BsAgentPrice agentPrice = agentPriceService.getDetail(AgentPriceTypeEnum.type1, merNo, oilPrice.getOilNo());
                    if (agentPrice != null) {
                        discount = agentPrice.getPriceRate();
                    }*/
                    BsGasChannelPriceWeek gasChannelPriceWeek = gasChannelPriceWeekService.getDetail(MerchantSourceTypeEnum.getDataByType(gasDetail.getSourceType()), LocalDate.now().getDayOfWeek().getValue(), oilPrice.getOilNo());
                    if (gasChannelPriceWeek != null) {
                        discount = gasChannelPriceWeek.getPriceRate();
                    }
                }
                oilPrice.setPriceVip(oilPrice.getPriceVip().multiply(discount.divide(new BigDecimal("100"))).setScale(2, BigDecimal.ROUND_HALF_UP));
            }

            return ResponseMsgUtil.success(gasDetail);

        } catch (Exception e) {
            return ResponseMsgUtil.exception(e);
        }
    }

}
