package com.fuint.module.backendApi.controller;

import com.alibaba.fastjson.JSONArray;
import com.fuint.common.Constants;
import com.fuint.common.dto.*;
import com.fuint.common.enums.*;
import com.fuint.common.param.RechargeParam;
import com.fuint.common.service.*;
import com.fuint.common.util.CommonUtil;
import com.fuint.common.util.TokenUtil;
import com.fuint.framework.exception.BusinessCheckException;
import com.fuint.framework.pagination.PaginationRequest;
import com.fuint.framework.pagination.PaginationResponse;
import com.fuint.framework.web.BaseController;
import com.fuint.framework.web.ResponseObject;
import com.fuint.repository.model.*;
import com.fuint.utils.StringUtil;
import io.swagger.annotations.Api;
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.*;

/**
 * 积分管理controller
 *
 * Created by FSQ
 * CopyRight https://www.fuint.cn
 */
@Api(tags="管理端-积分相关接口")
@RestController
@RequestMapping(value = "/backendApi/raffle")
public class BackendRaffleController extends BaseController {

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

    /**
     * 积分服务接口
     * */
    @Autowired
    private RaffleService raffleService;
    /**
     * 系统设置服务接口
     * */
    @Autowired
    private SettingService settingService;


    /**
     * 积分明细列表查询
     *
     * @param  request  HttpServletRequest对象
     * @return 积分明细列表
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @CrossOrigin
    public ResponseObject list(HttpServletRequest request) throws BusinessCheckException {
        String token = request.getHeader("Access-Token");
        Integer page = request.getParameter("page") == null ? Constants.PAGE_NUMBER : Integer.parseInt(request.getParameter("page"));
        Integer pageSize = request.getParameter("pageSize") == null ? Constants.PAGE_SIZE : Integer.parseInt(request.getParameter("pageSize"));
        String status = request.getParameter("status") == null ? StatusEnum.ENABLED.getKey() : request.getParameter("status");
        String title = request.getParameter("title") == null ? "" : request.getParameter("title");

        AccountInfo accountInfo = TokenUtil.getAccountInfoByToken(token);
        if (accountInfo == null) {
            return getFailureResult(1001, "请先登录");
        }
        PaginationRequest paginationRequest = new PaginationRequest();
        paginationRequest.setCurrentPage(page);
        paginationRequest.setPageSize(pageSize);

        Map<String, Object> searchParams = new HashMap<>();

        if (StringUtil.isNotEmpty(status)) {
            searchParams.put("status", status);
        }
        if (StringUtil.isNotEmpty(title)) {
            searchParams.put("title", title);
        }

        paginationRequest.setSearchParams(searchParams);
        PaginationResponse<RaffleDto> paginationResponse = raffleService.queryListByPagination(paginationRequest);

        Map<String, Object> result = new HashMap<>();
        result.put("dataList", paginationResponse);

        String imagePath = settingService.getUploadBasePath();
        result.put("imagePath", imagePath);


        return getSuccessResult(result);
    }

    /**
     * 提交保存
     *
     * @param request  HttpServletRequest对象
     * @return
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @CrossOrigin
    public ResponseObject saveRaffleHandler(HttpServletRequest request, @RequestBody Map<String, Object> param) throws BusinessCheckException {
        String token = request.getHeader("Access-Token");
        String title = param.get("title") == null ? "" : param.get("title").toString();
        String brief = param.get("brief") == null ? "" : param.get("brief").toString();
        String status = param.get("status") == null ? "A" : param.get("status").toString();
        String image = param.get("image") == null ? "" : param.get("image").toString();
        String description = param.get("description") == null ? "A" : param.get("description").toString();
        Integer rafflePoint = param.get("rafflePoint") == null ? 0 : Integer.parseInt(param.get("rafflePoint").toString());
        List<LinkedHashMap> rafList = param.get("rafData") == null ? new ArrayList<>() : (List) param.get("rafData");

        String extraImage = param.get("extraImage") == null ? "" : param.get("extraImage").toString();
        String extraType = param.get("extraType") == null ? "L" : param.get("extraType").toString();
        String extraPrize = param.get("extraPrize") == null ? "" : param.get("extraPrize").toString();

        Integer forwardPoint = 0;
        if (StringUtil.isEmpty(param.get("forwardPoint").toString())) {
            forwardPoint = Integer.parseInt(param.get("forwardPoint").toString());
        }
        String raffleType = param.get("raffleType") == null ? "pokemon" : param.get("raffleType").toString();

        AccountInfo accountInfo = TokenUtil.getAccountInfoByToken(token);
        if (accountInfo == null) {
            return getFailureResult(1001, "请先登录");
        }
        logger.info(JSONArray.toJSONString(param));

        MtRaffle dto = new MtRaffle();
        dto.setRaffleType(raffleType);
        dto.setTitle(title);
        dto.setBrief(brief);
        dto.setStatus(status);
        dto.setImage(image);
        dto.setDescription(description);
        dto.setRafflePoint(rafflePoint);
        dto.setOperator(accountInfo.getAccountName());
        dto.setCreateTime(new Date());

        dto.setExtraImage(extraImage);
        dto.setExtraType(extraType);
        dto.setExtraPrize(extraPrize);

        dto.setForwardPoint(forwardPoint);

        raffleService.addRaffle(dto);
        int allCnt = 0;
        if (rafList.size() > 0) {
            for (LinkedHashMap item: rafList) {
                Integer num = Integer.parseInt(item.get("num").toString());
                String raffleTitle = item.get("title") == null ? "" : item.get("title").toString();
                String prize = item.get("prize") == null ? "" : item.get("prize").toString();
                Integer point = item.get("point") == null ? 0 : Integer.parseInt(item.get("point").toString());
                String raffleImage = item.get("image") == null ? "" : item.get("image").toString();
                allCnt = allCnt + num;
                for (int i = 0; i < num; i++) {
                    MtRaffleItem raffleItem = new MtRaffleItem();
                    raffleItem.setRaffleId(dto.getId());
                    raffleItem.setPrize(prize);
                    raffleItem.setTitle(raffleTitle);
                    raffleItem.setPoint(point);
                    raffleItem.setImage(raffleImage);
                    raffleItem.setOperator(accountInfo.getAccountName());
                    raffleItem.setPrizeType(PrizeTypeEnum.NORMAL.getKey());

                    raffleService.addRaffleItem(raffleItem);
                }
            }
        }
        dto.setNowCnt(0);
        dto.setAllCnt(allCnt);
        raffleService.updRaffle(dto);


        return getSuccessResult(true);
    }


    /**
     * 抽奖明细
     *
     * @param request  HttpServletRequest对象
     * @return
     */
    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    @CrossOrigin
    public ResponseObject detailRaffleHandler(HttpServletRequest request) throws BusinessCheckException {
        String token = request.getHeader("Access-Token");

        String raffleId = request.getParameter("raffleId") == null ? "" : request.getParameter("raffleId");
        String userId = request.getParameter("userId") == null ? "" : request.getParameter("userId");
        String win = request.getParameter("win") == null ? "" : request.getParameter("win");
        String deal = request.getParameter("deal") == null ? "" : request.getParameter("deal");
        String userNo = request.getParameter("userNo") == null ? "" : request.getParameter("userNo");

        AccountInfo accountInfo = TokenUtil.getAccountInfoByToken(token);
        if (accountInfo == null) {
            return getFailureResult(1001, "请先登录");
        }

        RaffleItemDto raffleItemDto = new RaffleItemDto();
        if (StringUtil.isNotEmpty(raffleId)) {
            raffleItemDto.setRaffleId(Integer.parseInt(raffleId));

        }
        if (StringUtil.isNotEmpty(userId)) {
            raffleItemDto.setUserId(Integer.parseInt(userId));
        }
        if (StringUtil.isNotEmpty(win)) {
            raffleItemDto.setWin(Integer.parseInt(win));
        }
        if (StringUtil.isNotEmpty(deal)) {
            raffleItemDto.setDeal(Integer.parseInt(deal));
        }
        if (StringUtil.isNotEmpty(userNo)) {
            raffleItemDto.setUserNo(userNo);
        }
        logger.info("raffle detail condition: " + JSONArray.toJSONString(raffleItemDto));
        List<MtRaffleItem> raffleList = raffleService.queryRaffleItemByRaffleId(raffleItemDto);

        Map<String, Object> result = new HashMap<>();
        result.put("rafList", raffleList);

        String imagePath = settingService.getUploadBasePath();
        result.put("imagePath", imagePath);

        return getSuccessResult(result);
    }

    /**
     * 抽奖基础信息
     *
     * @param request  HttpServletRequest对象
     * @return
     */
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    @CrossOrigin
    public ResponseObject info(HttpServletRequest request) throws BusinessCheckException {
        String token = request.getHeader("Access-Token");
        Integer id = request.getParameter("id") == null ? 0 : Integer.parseInt(request.getParameter("id"));

        AccountInfo accountInfo = TokenUtil.getAccountInfoByToken(token);
        if (accountInfo == null) {
            return getFailureResult(1001, "请先登录");
        }
        MtRaffle raffle = raffleService.queryRaffle(id);
        if (raffle == null) {
            return getFailureResult(201, "抽奖不存在");
        }

        Map<String, Object> result = new HashMap<>();
        result.put("dataList", raffle);
        String imagePath = settingService.getUploadBasePath();
        result.put("imagePath", imagePath);

        return getSuccessResult(result);
    }

    @RequestMapping(value = "/deal", method = RequestMethod.GET)
    @CrossOrigin
    public ResponseObject deal(HttpServletRequest request) throws BusinessCheckException {
        String token = request.getHeader("Access-Token");

        Integer id = request.getParameter("id") == null ? 0 : Integer.parseInt(request.getParameter("id"));

        AccountInfo accountInfo = TokenUtil.getAccountInfoByToken(token);
        if (accountInfo == null) {
            return getFailureResult(1001, "请先登录");
        }

        logger.info("deal id: " + id);
        raffleService.dealRaffleItem(id, accountInfo.getAccountName());

        Map<String, Object> result = new HashMap<>();
        result.put("deal", "succ");

        return getSuccessResult(result);
    }

    /**
     * 更新会员状态
     *
     * @return
     */
    @RequestMapping(value = "/change", method = RequestMethod.GET)
    @CrossOrigin
    public ResponseObject updateStatus(HttpServletRequest request) throws BusinessCheckException {
        String token = request.getHeader("Access-Token");
        Integer id = request.getParameter("id") == null ? 0 : Integer.parseInt(request.getParameter("id").toString());
        String status = request.getParameter("status") == null ? StatusEnum.ENABLED.getKey() : request.getParameter("status").toString();

        AccountInfo accountInfo = TokenUtil.getAccountInfoByToken(token);
        if (accountInfo == null) {
            return getFailureResult(1001, "请先登录");
        }
        logger.info("changeStatus  id="+id + "  status=" + status);
        MtRaffle raffle = raffleService.queryRaffle(id);
        if (raffle == null) {
            return getFailureResult(201, "抽奖不存在");
        }
        MtRaffle updraffle = new MtRaffle();
        updraffle.setId(id);
        updraffle.setStatus(status);
        updraffle.setOperator(accountInfo.getAccountName());
        updraffle.setUpdateTime(new Date());
        raffleService.updRaffle(updraffle);

        return getSuccessResult(true);
    }


}
