package com.fuint.module.clientApi.controller;

import com.alibaba.fastjson.JSONArray;
import com.fuint.common.dto.OrderDto;
import com.fuint.common.dto.RaffleDto;
import com.fuint.common.dto.RaffleItemDto;
import com.fuint.common.dto.UserInfo;
import com.fuint.common.enums.OrderStatusEnum;
import com.fuint.common.enums.PayStatusEnum;
import com.fuint.common.enums.PayTypeEnum;
import com.fuint.common.enums.YesOrNoEnum;
import com.fuint.common.param.RaffleParam;
import com.fuint.common.param.RechargeParam;
import com.fuint.common.service.MemberService;
import com.fuint.common.service.OrderService;
import com.fuint.common.service.PaymentService;
import com.fuint.common.service.RaffleService;
import com.fuint.common.util.CommonUtil;
import com.fuint.common.util.TokenUtil;
import com.fuint.framework.exception.BusinessCheckException;
import com.fuint.framework.web.BaseController;
import com.fuint.framework.web.ResponseObject;
import com.fuint.repository.model.MtOrder;
import com.fuint.repository.model.MtRaffle;
import com.fuint.repository.model.MtRaffleItem;
import com.fuint.repository.model.MtUser;
import com.fuint.utils.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 抽奖相关controller
 *
 * Created by FSQ
 * CopyRight https://www.fuint.cn
 */
@Api(tags="会员端-抽奖相关接口")
@RestController
@RequestMapping(value = "/clientApi/raffle")
public class ClientRaffleController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(ClientRaffleController.class);

    /**
     * 抽奖服务接口
     */
    @Autowired
    private RaffleService raffleService;
    /**
     * 订单服务接口
     * */
    @Autowired
    private OrderService orderService;

    /**
     * 会员服务接口
     */
    @Autowired
    private MemberService memberService;


    /**
     * 支付服务接口
     * */
    @Autowired
    private PaymentService paymentService;

    /**
     * 查询我的积分明细
     *
     * @param request Request对象
     */
    @ApiOperation(value = "抽奖列表")
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @CrossOrigin
    public ResponseObject list(HttpServletRequest request, @RequestBody RaffleParam raffleParam) throws BusinessCheckException {
        String token = request.getHeader("Access-Token");

        logger.info("微信一番赏一览数据：" + JSONArray.toJSONString(raffleParam));

        if (StringUtil.isEmpty(token)) {
            return getFailureResult(1001);
        }

        UserInfo mtUser = TokenUtil.getUserInfoByToken(token);
        if (null == mtUser) {
            return getFailureResult(1001);
        }


        ResponseObject rafList = raffleService.findRaffleList(raffleParam);

        return getSuccessResult(rafList.getData());

    }

    /**
     * 最新抽奖
     */
    @ApiOperation(value = "最新抽奖")
    @RequestMapping(value = "/latest", method = RequestMethod.GET)
    @CrossOrigin
    public ResponseObject latest(HttpServletRequest request) throws BusinessCheckException {
        String token = request.getHeader("Access-Token");

        if (StringUtil.isEmpty(token)) {
            return getFailureResult(1001);
        }

        UserInfo mtUser = TokenUtil.getUserInfoByToken(token);
        if (null == mtUser) {
            return getFailureResult(1001);
        }

        List<RaffleDto> list = raffleService.getLatestRaffles(5);
        return getSuccessResult(list);
    }

    /**
     * 最新中奖
     */
    @ApiOperation(value = "最新中奖")
    @RequestMapping(value = "/latestWins", method = RequestMethod.GET)
    @CrossOrigin
    public ResponseObject latestWins(HttpServletRequest request) throws BusinessCheckException {
        String token = request.getHeader("Access-Token");

        if (StringUtil.isEmpty(token)) {
            return getFailureResult(1001);
        }

        UserInfo mtUser = TokenUtil.getUserInfoByToken(token);
        if (null == mtUser) {
            return getFailureResult(1001);
        }

        List<RaffleItemDto> list = raffleService.getLatestWinItems(20);
        return getSuccessResult(list);
    }

    /**
     * 抽奖详情
     *
     * @param request Request对象
     */
    @ApiOperation(value = "抽奖详情")
    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    @CrossOrigin
    public ResponseObject detailRaffle(HttpServletRequest request) {
        String token = request.getHeader("Access-Token");

        if (StringUtil.isEmpty(token)) {
            return getFailureResult(1001);
        }

        UserInfo mtUser = TokenUtil.getUserInfoByToken(token);
        if (null == mtUser) {
            return getFailureResult(1001);
        }
        Integer raffleId = request.getParameter("raffleId") == null ? 0:Integer.parseInt(request.getParameter("raffleId"));

        try {
            Map<String, Object> result = new HashMap<>();

            List<RaffleItemDto> detail = raffleService.queryRaffleItemByRaffleId2wechat(raffleId);
            result.put("detail", detail);

            MtRaffle raffle = raffleService.queryRaffle(raffleId);
            MtRaffle updClick = new MtRaffle();
            updClick.setId(raffle.getId());
            if (raffle.getClick() == null) {
                updClick.setClick(1);
            } else {
                updClick.setClick(raffle.getClick() + 1);
            }
            updClick.setUpdateTime(raffle.getUpdateTime());
            raffleService.updRaffle(updClick);
            result.put("raffle", raffle);

            Integer point = raffleService.userPoint(mtUser.getId());
            result.put("point", point);

            result.put("userId", mtUser.getId());

            return getSuccessResult(result);

        } catch (BusinessCheckException e) {
            return getFailureResult(3008, e.getMessage());
        }
    }

    /**
     * 抽一发
     *
     * @param request Request对象
     */
    @ApiOperation(value = "抽一发")
    @RequestMapping(value = "/doRaffle", method = RequestMethod.GET)
    @CrossOrigin
    public ResponseObject doRaffle(HttpServletRequest request) {
        String token = request.getHeader("Access-Token");

        if (StringUtil.isEmpty(token)) {
            return getFailureResult(1001);
        }

        UserInfo mtUser = TokenUtil.getUserInfoByToken(token);
        if (null == mtUser) {
            return getFailureResult(1001);
        }
        Integer raffleId = request.getParameter("raffleId") == null ? 0:Integer.parseInt(request.getParameter("raffleId"));
        Integer num = request.getParameter("num") == null ? 0:Integer.parseInt(request.getParameter("num"));

        logger.info("抽一抽："+raffleId+"，"+ num+"抽");

        Integer forwardUserId = 0;
        try {
            forwardUserId = Integer.parseInt(request.getParameter("forwardUserId"));
        } catch (NumberFormatException ne) {
            logger.info("抽一抽 forwardUserId："+forwardUserId);
        }
        logger.info("抽一抽转发人："+forwardUserId);

        try {
            List<MtRaffleItem> item = raffleService.doRaffleByRaffleId(raffleId, num, mtUser, forwardUserId);
            Map<String, Object> result = new HashMap<>();
            result.put("stat", "yes");
            result.put("item", item);

            return getSuccessResult(result);

        } catch (BusinessCheckException e) {
            return getFailureResult(3008, e.getMessage());
        }
    }

    /**
     * 排队
     *
     * @param request Request对象
     */
    @ApiOperation(value = "排队")
    @RequestMapping(value = "/doQueue", method = RequestMethod.GET)
    @CrossOrigin
    public ResponseObject doQueue(HttpServletRequest request) {
        String token = request.getHeader("Access-Token");

        if (StringUtil.isEmpty(token)) {
            return getFailureResult(1001);
        }

        UserInfo mtUser = TokenUtil.getUserInfoByToken(token);
        if (null == mtUser) {
            return getFailureResult(1001);
        }
        Integer raffleId = request.getParameter("raffleId") == null ? 0:Integer.parseInt(request.getParameter("raffleId"));

        try {

            MtRaffle raffle = raffleService.queryRaffle(raffleId);

            long diff = 1000;
            if (raffle.getUserTime() != null) {
                long userTIme = raffle.getUserTime().getTime();
                long now = new Date().getTime();
                diff = (now - userTIme)/1000;
            }
            logger.info("diff： " + diff);
            Map<String, String> result = new HashMap<>();
            if (diff <= 60) {
                result.put("stat", "no");
                result.put("time", String.valueOf(60-diff));
                return getSuccessResult(result);

            }

            MtRaffle newRaffle = new MtRaffle();
            newRaffle.setId(raffleId);
            newRaffle.setUserId(mtUser.getId());
            newRaffle.setUserTime(new Date());
            raffleService.updRaffle(newRaffle);
            result.put("stat", "yes");
            result.put("time", "60");
            return getSuccessResult(result);


        } catch (BusinessCheckException e) {
            return getFailureResult(3008, e.getMessage());
        }
    }


    /**
     * 背包
     *
     * @param request Request对象
     */
    @ApiOperation(value = "背包")
    @RequestMapping(value = "/findBag", method = RequestMethod.GET)
    @CrossOrigin
    public ResponseObject findBag(HttpServletRequest request) {
        String token = request.getHeader("Access-Token");

        if (StringUtil.isEmpty(token)) {
            return getFailureResult(1001);
        }

        UserInfo mtUser = TokenUtil.getUserInfoByToken(token);
        if (null == mtUser) {
            return getFailureResult(1001);
        }

        try {
            List<RaffleItemDto> items = raffleService.queryRaffleItemByUserId(mtUser.getId());

            MtUser member = memberService.queryMemberById(mtUser.getId());
            Map<String,Object> result = new HashMap<>();
            result.put("item", items);
            result.put("member", member);


            return getSuccessResult(items);


        } catch (BusinessCheckException e) {
            return getFailureResult(3008, e.getMessage());
        }
    }

    /**
     * 转化积分
     *
     * @param request Request对象
     */
    @ApiOperation(value = "转化积分")
    @RequestMapping(value = "/sellPoint", method = RequestMethod.GET)
    @CrossOrigin
    public ResponseObject sellPoint(HttpServletRequest request) {
        String token = request.getHeader("Access-Token");

        if (StringUtil.isEmpty(token)) {
            return getFailureResult(1001);
        }

        UserInfo mtUser = TokenUtil.getUserInfoByToken(token);
        if (null == mtUser) {
            return getFailureResult(1001);
        }
        Integer raffleItemId = request.getParameter("raffleItemId") == null ? 0:Integer.parseInt(request.getParameter("raffleItemId"));

        try {

            boolean result = raffleService.tranfer2Point(raffleItemId,mtUser.getId());

            return getSuccessResult(result);


        } catch (BusinessCheckException e) {
            return getFailureResult(3008, e.getMessage());
        }
    }


    /**
     * 充值积分
     * */
    @RequestMapping(value = "/doCharge", method = RequestMethod.POST)
    @CrossOrigin
    public ResponseObject doCharge(HttpServletRequest request, @RequestBody RechargeParam rechargeParam) throws BusinessCheckException {
        Integer storeId = request.getHeader("storeId") == null ? 0 : Integer.parseInt(request.getHeader("storeId"));
        String platform = request.getHeader("platform") == null ? "" : request.getHeader("platform");

        String token = request.getHeader("Access-Token");
        if (StringUtil.isEmpty(token)) {
            return getFailureResult(1001);
        }

        UserInfo userInfo = TokenUtil.getUserInfoByToken(token);
        if (null == userInfo) {
            return getFailureResult(1001);
        }

        String rechargeAmount = rechargeParam.getRechargeAmount() == null ? "" : rechargeParam.getRechargeAmount();
        String customAmount = rechargeParam.getCustomAmount() == null ? "" : rechargeParam.getCustomAmount();
        if (StringUtil.isEmpty(rechargeAmount) && StringUtil.isEmpty(customAmount)) {
            return getFailureResult(2000, "请确认充值金额");
        }
        logger.info("rechargeAmount: " + rechargeAmount);
        logger.info("customAmount: " + customAmount);

        String ruleParam = "";
        // 自定义充值没有赠送金额
        if (StringUtil.isEmpty(rechargeAmount)) {
            ruleParam = customAmount + "_0";
        }

        BigDecimal amount = new BigDecimal(customAmount);
        logger.info("amount: " + amount);

        OrderDto orderDto = new OrderDto();
        orderDto.setType("pointChange");
        orderDto.setUserId(userInfo.getId());
        orderDto.setStoreId(storeId);
        orderDto.setAmount(amount);
        orderDto.setUsePoint(0);
        orderDto.setRemark("积分充值");
        orderDto.setParam(ruleParam);
        orderDto.setStatus(OrderStatusEnum.CREATED.getKey());
        orderDto.setPayStatus(PayStatusEnum.WAIT.getKey());
        orderDto.setPointAmount(new BigDecimal("0"));
        orderDto.setOrderMode("");
        orderDto.setCouponId(0);
        orderDto.setPlatform(platform);

        MtOrder orderInfo = orderService.saveOrder(orderDto);

        MtUser mtUser = memberService.queryMemberById(userInfo.getId());

        String ip = CommonUtil.getIPFromHttpRequest(request);
        BigDecimal pay = amount.multiply(new BigDecimal("100"));
        orderInfo.setPayType(PayTypeEnum.JSAPI.getKey());
        ResponseObject paymentInfo = paymentService.createPrepayOrder(mtUser, orderInfo, (pay.intValue()), "", 0, ip, platform, YesOrNoEnum.YES.getKey());
        if (paymentInfo.getData() == null) {
            return getFailureResult(201, "抱歉，发起支付失败");
        }

        Object payment = paymentInfo.getData();

        Map<String, Object> data = new HashMap();
        data.put("payment", payment);
        data.put("orderInfo", orderInfo);

        return getSuccessResult(data);
    }
}
