package com.cweb.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
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.BsAgentPrice;
import com.hfkj.entity.BsDiscountUser;
import com.hfkj.model.*;
import com.hfkj.service.agent.BsAgentPriceService;
import com.hfkj.service.discount.BsDiscountService;
import com.hfkj.service.discount.BsDiscountUserService;
import com.hfkj.service.gas.BsGasService;
import com.hfkj.sysenum.agent.AgentPriceTypeEnum;
import com.hfkj.sysenum.discount.DiscountUserStatusEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
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.util.*;

/**
 * @className: BsDiscountUserController
 * @author: HuRui
 * @date: 2024/8/30
 **/
@Controller
@RequestMapping(value = "/discountUser")
@Api(value = "用户优惠券管理")
public class BsDiscountUserController {
    private static Logger log = LoggerFactory.getLogger(BsDiscountUserController.class);
    @Resource
    private BsDiscountUserService discountUserService;
    @Resource
    private BsDiscountService discountService;
    @Resource
    private UserCenter userCenter;
    @Resource
    private BsGasService gasService;
    @Resource
    private BsAgentPriceService agentPriceService;

    @RequestMapping(value="/usableMerList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "可用加油站列表")
    public ResponseData usableMerList(@RequestParam(name = "discountNo", required = true) String discountNo,
                                      @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.getGasListByDiscount(discountNo,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<>());
            }
            return ResponseMsgUtil.success(pageInfo);

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


    @RequestMapping(value="/give",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "赠送")
    public ResponseData give(@RequestBody JSONObject body) {
        try {
            if (body == null
                || body.getLong("codeId") == null
                || StringUtils.isBlank(body.getString("phone"))) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            UserSessionObject userSession = userCenter.getSessionModel(UserSessionObject.class);
            if (userSession == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.ACCOUNT_LOGIN_NOT, "");
            }
            discountUserService.give(body.getLong("codeId"), userSession.getUser().getId(), body.getString("phone"));

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

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

    @RequestMapping(value="/useDiscountList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "加油优惠券列表")
    public ResponseData useDiscountList(@RequestParam(name = "useScope", required = true) Integer useScope,
                                        @RequestParam(name = "merNo", required = true) String merNo,
                                        @RequestParam(name = "refuelPrice", required = false) BigDecimal refuelPrice) {
        try {

            List<DiscountUserModel> discountList = new ArrayList<>();
            // 用户信息
            try {
                UserSessionObject userSession = userCenter.getSessionModel(UserSessionObject.class);
                if (userSession != null) {
                    Map<String,Object> param = new HashMap<>();
                    param.put("userId", userSession.getUser().getId());
                    param.put("useMerNo", merNo);
                    param.put("useScope", useScope);
                    param.put("status", DiscountUserStatusEnum.type1.getCode());
                    discountList = discountUserService.getUserDiscountList(param);
                }
            } catch (Exception e) {
                // 不做任何处理
            }
            return ResponseMsgUtil.success(discountList);

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


    @RequestMapping(value="/queryList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询列表")
    public ResponseData queryList(@RequestParam(name = "useScope", required = false) String useScope,
                                  @RequestParam(name = "status", required = false) Integer status,
                                  @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                  @RequestParam(name = "pageSize", required = true) Integer pageSize) {
        try {
            // 用户信息
            UserSessionObject userSessionObject = userCenter.getSessionModel(UserSessionObject.class);

            Map<String,Object> param = new HashMap<>();
            param.put("userId", userSessionObject.getUser().getId());
            param.put("useScope", useScope);
            param.put("status", status);

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

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

    @RequestMapping(value="/queryDetail",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询详情")
    public ResponseData queryDetail(@RequestParam(name = "id", required = true) Long id) {
        try {
            // 查询用户优惠券
            BsDiscountUser discountUser = discountUserService.getDetail(id);
            if (discountUser == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到用户优惠券");
            }
            Map<String,Object> param = new HashMap<>();
            param.put("discountUser", discountUser);
            param.put("discount", discountService.getDetail(discountUser.getDiscountNo()));
            return ResponseMsgUtil.success(param);

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

}
