package cn.pluss.platform.controller.home;

import cn.pluss.platform.activityEnroll.ActivityEnrollService;
import cn.pluss.platform.annotation.NoRepeatSubmit;
import cn.pluss.platform.api.Result;
import cn.pluss.platform.api.ResultGenerator;
import cn.pluss.platform.deviceStock.DeviceStockService;
import cn.pluss.platform.entity.*;
import cn.pluss.platform.inviteRate.InviteRateService;
import cn.pluss.platform.merchant.MerchantBaseInfoService;
import cn.pluss.platform.merchantOrder.MerchantOrderService;
import cn.pluss.platform.merchantProfit.MerchantProfitService;
import cn.pluss.platform.merchantStore.MerchantStoreService;
import cn.pluss.platform.officialActivity.OfficialActivityService;

import cn.pluss.platform.officialGoods.OfficialGoodsService;
import cn.pluss.platform.officialGoods.exchange.OfficialGoodsExchangeService;
import cn.pluss.platform.systemConfig.SystemConfigService;
import cn.pluss.platform.userAddress.UserAddressService;
import cn.pluss.platform.userApp.UserAppService;
import cn.pluss.platform.userInfo.UserInfoService;
import cn.pluss.platform.userIntegral.UserIntegralService;
import cn.pluss.platform.userIntegralUse.UserIntegralUseService;
import cn.pluss.platform.util.*;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 官方活动
 */
@Controller
@RequestMapping("activity")
@Slf4j
@RequiredArgsConstructor
public class ActivityController {

    private final OfficialActivityService officialActivityService;

    private final MerchantOrderService merchantOrderService;

    private final UserAppService userAppService;

    private final OfficialGoodsService officialGoodsService;

    private final OfficialGoodsExchangeService officialGoodsExchangeService;

    private final MerchantStoreService merchantStoreService;

    private final MerchantBaseInfoService merchantBaseInfoService;

    private final ActivityEnrollService activityEnrollService;

    private final SystemConfigService systemConfigService;

    private final InviteRateService inviteRateService;

    private final MerchantProfitService merchantProfitService;

    private final DeviceStockService deviceStockService;

    private final UserAddressService userAddressService;

    private final UserIntegralService userIntegralService;

    private final UserIntegralUseService userIntegralUseService;

    private final UserInfoService userInfoService;


    @GetMapping("/act/detail")
    public ModelAndView actDetail(String token, Integer a, Integer c, String t, HttpServletRequest request) {
        ModelAndView view = new ModelAndView();
        UserApp app = checkToken(token, view, request);
        if (app == null) {
            view.addObject("error", "无效的用户！");
            view.setViewName("merchant/errorInfo");
            return view;
        }
        if (StringUtil.isEmpty(a)) {
            view.addObject("error", "无效的活动");
            view.setViewName("merchant/errorInfo");
            return view;
        }
        OfficialActivity act = officialActivityService.getById(a);
        if (act == null) {
            view.addObject("error", "无效的活动");
            view.setViewName("merchant/errorInfo");
            return view;
        }
        view.setViewName("activity/actDetail");
        view.addObject("token", token);
        view.addObject("act", act);
        view.addObject("marketAmtCount", "0.00");
        view.addObject("t", t);
        if (StringUtil.isEmpty(app.getMerchantCode())) {
            view.addObject("isMarket", "0");
            view.addObject("f", "1");
        } else {
            MerchantStore store = new MerchantStore();
            store.setMerchantCode(app.getMerchantCode());
            List<MerchantStore> storeList = merchantStoreService.queryMerchantStoreList(store);
            if (storeList.isEmpty()) {
                view.addObject("error", "请先开通商户");
                view.setViewName("merchant/errorInfo");
                return view;
            }

            view.addObject("isMarket", storeList.get(0).getIsMarket());

            if (StringUtil.isNotEmpty(c)) {
                BigDecimal marketQuota = new BigDecimal("500000");
                String value = "";
                if ("1".equals(String.valueOf(c))) {
                    value = systemConfigService.querySystemConfigValue("activityTransMarketQuota");
                } else if ("2".equals(String.valueOf(c))) {
                    marketQuota = new BigDecimal("250000");
                    value = systemConfigService.querySystemConfigValue("activityTransP117Quota");
                } else if ("4".equals(String.valueOf(c))) {
                    marketQuota = new BigDecimal("250000");
                    value = systemConfigService.querySystemConfigValue("activityTransCG02Quota");
                }
                if (StringUtil.isNotEmpty(value)) {
                    marketQuota = new BigDecimal(value.split("-")[0]);
                }
                view.addObject("marketQuota", marketQuota);

                QueryWrapper<ActivityEnroll> enrollQueryWrapper = new QueryWrapper<ActivityEnroll>()
                        .eq("merchantCode", app.getMerchantCode()).eq("actId", a)
                        .orderByDesc("createTime").last("limit 1");
                List<ActivityEnroll> actEnrollList = activityEnrollService.list(enrollQueryWrapper);
                if (actEnrollList.isEmpty()) {
                    view.addObject("progressNum", 0);
                    view.addObject("tradeAmt", 0);
                    view.addObject("actTitle", "您尚未参加此活动");
                    view.addObject("f", "0");
                } else {
                    ActivityEnroll activityEnroll = actEnrollList.get(0);
                    if ("0".equals(activityEnroll.getStatus())) {
                        view.addObject("progressNum", 0);
                        view.addObject("tradeAmt", 0);
                        view.addObject("actTitle", "申请成功，等待审核...");
                        view.addObject("f", "1");
                    } else if ("1".equals(activityEnroll.getStatus())) {
                        //获取商户当前已经积累的交易额度
                        String auditDate = DateUtils.formatDateDefault(activityEnroll.getAuditTime(), "yyyy-MM-dd");
                        if ("1".equals(c + "") || "2".equals(c + "") || "4".equals(c + "")) {
                            Map<String, Double> countTradeAmt = merchantOrderService.getCountTradeAmt(app.getMerchantCode(), auditDate, null, null);
                            //Double tradeAmt = countTradeAmt.get("tradeAmtCount");
                            Double dateAmt = countTradeAmt.get("dateAmt");
                            if (dateAmt == null) {
                                view.addObject("progressNum", 0);
                                view.addObject("tradeAmt", 0);
                            } else {
                                BigDecimal transAmt = new BigDecimal(Double.toString(dateAmt));
                                if (transAmt.doubleValue() == 0.00) {
                                    view.addObject("progressNum", 0);
                                    view.addObject("tradeAmt", 0);
                                } else {
                                    Double progressNum = transAmt.divide(marketQuota).multiply(new BigDecimal(100))
                                            .setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                                    view.addObject("progressNum", progressNum);
                                    view.addObject("tradeAmt", dateAmt);
                                }
                            }
                        } else if ("3".equals(String.valueOf(c))) {
                            //获取插件以获得的奖励金
                            BigDecimal countIntegral = userIntegralService.getCountIntegral(app.getUserId(), null, auditDate);
                            view.addObject("marketAmtCount", countIntegral);
                        }
                        view.addObject("actTitle", "您已成功参与此活动");
                        view.addObject("f", "1");
                    } else {
                        QueryWrapper<ActivityEnroll> activityEnrollQueryWrapper = new QueryWrapper<ActivityEnroll>()
                                .eq("merchantCode", app.getMerchantCode()).orderByDesc("createTime").last("limit 1");
                        List<ActivityEnroll> list = activityEnrollService.list(activityEnrollQueryWrapper);
                        view.addObject("progressNum", 0);
                        view.addObject("tradeAmt", 0);
                        view.addObject("actTitle", "");
                        view.addObject("checkTitle", "审核失败：" + list.get(0).getRemark());
                        view.addObject("f", "2");
                    }
                }
            }
        }
        view.addObject("userType", app.getUserType());
        view.addObject("c", c);
        return view;
    }

    @GetMapping("/one")
    public ModelAndView actOne(String token, String t, HttpServletRequest request) {
        ModelAndView view = new ModelAndView();
        UserApp app = checkToken(token, view, request);
        if (app == null) {
            view.addObject("error", "无效的用户！");
            view.setViewName("merchant/errorInfo");
            return view;
        }
        if (StringUtil.isEmpty(app.getMerchantCode())) {
            view.addObject("error", "暂无活动资格！");
            view.setViewName("merchant/errorInfo");
            return view;
        }
        if (StringUtil.isEmpty(t)) {
            view.addObject("error", "缺失参数！");
            view.setViewName("merchant/errorInfo");
            return view;
        }

        if (app == null) {
            view.addObject("error", "无效的用户！");
            view.setViewName("merchant/errorInfo");
            return view;
        }
        Map<String, Object> result = getActRateParam(t);

        UserInfo byId = userInfoService.getById(app.getUserId());
        if (byId != null) {
            view.addObject("loginName", byId.getLoginName());
        }
        Map<String, Object> hashMap = new HashMap<>(1);
        hashMap.put("userId", app.getUserId());
        hashMap.put("startDate", result.get("startDate"));
        hashMap.put("endDate", result.get("endDate"));
        Map<String, Object> profitMap = merchantProfitService.getProfitCount(hashMap);
        view.addObject("shareAmountCount", profitMap.get("shareAmountCount"));

        Map<String, BigDecimal> saveMap = merchantOrderService.getSaveMoneyCount(app.getMerchantCode(), null, result.get("startDate").toString(), result.get("endDate").toString());
        view.addObject("saveAmtCount", saveMap.get("saveAmtCount"));
        //TODO 获取下级用户
        Integer count = userAppService.getSubUserCount(app.getUserId(), result.get("startDate").toString(), result.get("endDate").toString());
        view.addObject("userCount", count);
        view.addObject("merchantCode", app.getMerchantCode());
        view.addObject("token", token);
        view.addObject("t", t);
        view.addObject("inviteRateList", result.get("inviteRateList"));
        view.setViewName("activity/act-one");
        return view;
    }

    private Map<String, Object> getActRateParam(String t) {
        Map<String, Object> result = new HashMap<>(3);
        String startDate = "2020-12-01";
        String endDate = "2021-02-01";
        List<InviteRate> inviteRateList = inviteRateService.list(new QueryWrapper<InviteRate>().orderByAsc("number").eq("type", t));
        if (!inviteRateList.isEmpty()) {
            result.put("inviteRateList", inviteRateList);
            InviteRate rate = inviteRateList.get(0);
            OfficialActivity act = officialActivityService.getById(rate.getActId());
            if (act != null) {
                startDate = DateUtils.formatDateDefault(act.getStartTime(), "yyyy-MM-dd");
                endDate = DateUtils.formatDateDefault(act.getEndTime(), "yyyy-MM-dd");
            }
        }
        result.put("startDate", startDate);
        result.put("endDate", endDate);
        return result;
    }

    @GetMapping("/one/desc")
    public ModelAndView actOneDesc(String token, String t, HttpServletRequest request) {
        ModelAndView view = new ModelAndView();
        UserApp app = checkToken(token, view, request);
        if (app == null) {
            view.addObject("error", "无效的用户！");
            view.setViewName("merchant/errorInfo");
            return view;
        }
        if (StringUtil.isEmpty(t)) {
            view.addObject("error", "缺失参数！");
            view.setViewName("merchant/errorInfo");
            return view;
        }
        String actStartDate = "2020年12月01日";
        String actEndDate = "2021年02月01日";
        BigDecimal oneRate = new BigDecimal("0.30");
        BigDecimal twoRate = new BigDecimal("0.25");
        Integer oneLevel = 8;
        Integer twoLevel = 16;
        List<InviteRate> inviteRateList = inviteRateService.list(new QueryWrapper<InviteRate>().orderByAsc("number").eq("type", t));
        if (!inviteRateList.isEmpty()) {
            InviteRate one = inviteRateList.get(0);
            InviteRate two = inviteRateList.get(1);
            oneLevel = one.getNumber();
            twoLevel = two.getNumber();
            oneRate = one.getRate();
            twoRate = two.getRate();
            OfficialActivity byId = officialActivityService.getById(one.getActId());
            if (byId != null) {
                actStartDate = DateUtils.formatDateDefault(byId.getStartTime(), "yyyy年MM月dd日");
                actEndDate = DateUtils.formatDateDefault(byId.getEndTime(), "yyyy年MM月dd日");
            }
        }
        view.addObject("oneRate", oneRate);
        view.addObject("twoRate", twoRate);
        view.addObject("oneLevel", oneLevel);
        view.addObject("twoLevel", twoLevel);
        view.addObject("actStartDate", actStartDate);
        view.addObject("actEndDate", actEndDate);
        view.addObject("inviteRateList", inviteRateList);
        view.addObject("t", t);
        view.setViewName("activity/act-one-desc");
        return view;
    }

    @GetMapping("/one/bonus")
    public ModelAndView actOneBonus(String token, String t, HttpServletRequest request) {
        ModelAndView view = new ModelAndView();
        UserApp app = checkToken(token, view, request);
        if (app == null) {
            return view;
        }
        view.addObject("t", t);
        view.setViewName("activity/act-one-bonus");
        return view;
    }


    @GetMapping("/one/lay")
    public ModelAndView actOneLay(String inviteNum, String t, HttpServletRequest request) {
        ModelAndView view = new ModelAndView();
        String merchantCode = chenkInviteNum(inviteNum, view, request);
        if (StringUtil.isEmpty(merchantCode)) {
            return view;
        }
        QueryWrapper<UserApp> queryWrapper = new QueryWrapper<UserApp>().eq("merchantCode", merchantCode)
                .eq("userType", "promoter");
        if (!merchantCode.contains("M")) {
            queryWrapper = new QueryWrapper<UserApp>().eq("userId", merchantCode);
        }
        UserApp app = userAppService.getOne(queryWrapper);
        if (app == null) {
            view.addObject("error", "无效的用户！");
            view.setViewName("merchant/errorInfo");
            return view;
        }
        view.addObject("inviteNum", inviteNum);
        view.addObject("token", app.getToken());
        view.addObject("t", t);
        view.setViewName("activity/act-one-lay");
        return view;
    }

    private String chenkInviteNum(String inviteNum, ModelAndView view, HttpServletRequest request) {
        if (StringUtil.isEmpty(inviteNum)) {
            view.addObject("error", "无效的推广码");
            view.setViewName("merchant/errorInfo");
            return null;
        }
        Object code = request.getSession().getAttribute(inviteNum);
        String merchantCode = "";
        if (code == null) {
            QueryWrapper<UserApp> queryAppWrapper = new QueryWrapper<UserApp>().eq("inviteNum", inviteNum);
            UserApp app = userAppService.getOne(queryAppWrapper);
            if (app == null) {
                view.addObject("error", "无效的推广码");
                view.setViewName("merchant/errorInfo");
                return null;
            }
            if (StringUtil.isEmpty(app.getMerchantCode())) {
                merchantCode = String.valueOf(app.getUserId());
            } else {
                merchantCode = app.getMerchantCode();
            }
            request.getSession().setAttribute(inviteNum, app.getMerchantCode());
        } else {
            merchantCode = code.toString();
        }
        return merchantCode;
    }

    @GetMapping("/one/detail")
    public ModelAndView actOneDetail(String token, String t, HttpServletRequest request) {
        ModelAndView view = new ModelAndView();
        UserApp app = checkToken(token, view, request);
        if (app == null) {
            view.addObject("error", "无效的用户");
            view.setViewName("merchant/errorInfo");
            return null;
        }
        List<InviteRate> inviteRateList = inviteRateService.list(new QueryWrapper<InviteRate>().orderByAsc("number").eq("type", t));
        view.addObject("inviteRateList", inviteRateList);
        view.addObject("inviteNum", app.getInviteNum());
        view.setViewName("activity/act-one-detail");
        view.addObject("token", token);
        view.addObject("t", t);
        return view;
    }

    @GetMapping("/one/poster")
    public ModelAndView actOnePoster(String token, String t, HttpServletRequest request) {
        ModelAndView view = new ModelAndView();
        UserApp app = checkToken(token, view, request);
        if (app == null) {
            view.addObject("error", "无效的用户");
            view.setViewName("merchant/errorInfo");
            return view;
        }
        String url = ParametersUtil.domain + "/wap/activity/one/lay?inviteNum=" + app.getInviteNum() + "&t=" + t;
        view.addObject("token", token);
        view.addObject("url", url);
        view.setViewName("activity/act-one-poster");
        return view;
    }

    @GetMapping("/one/income")
    public ModelAndView actOneIncome(String token, String t, HttpServletRequest request) {
        ModelAndView view = new ModelAndView();
        UserApp app = checkToken(token, view, request);
        if (app == null) {
            view.addObject("error", "无效的用户");
            view.setViewName("merchant/errorInfo");
            return view;
        }
        if (StringUtil.isEmpty(t)) {
            view.addObject("error", "缺失参数！");
            view.setViewName("merchant/errorInfo");
            return view;
        }
        Map<String, Object> resultMap = getActRateParam(t);
        Map<String, Object> hashMap = new HashMap<>(3);
        hashMap.put("userId", app.getUserId());
        hashMap.put("startDate", resultMap.get("startDate"));
        hashMap.put("endDate", resultMap.get("endDate"));
        //查询获得的分润
        Map<String, Object> profitMap = merchantProfitService.getProfitCount(hashMap);
        view.addObject("mercShareAmtCount", profitMap.get("mercShareAmtCount"));
        view.addObject("toUpShareAmtCount", profitMap.get("toUpShareAmtCount"));
        view.addObject("token", token);
        view.addObject("t", t);
        view.setViewName("activity/act-one-income");
        return view;
    }

    @GetMapping("/one/thrift")
    public ModelAndView actOneThrift(String token, String t, HttpServletRequest request) {
        ModelAndView view = new ModelAndView();
        UserApp app = checkToken(token, view, request);
        if (app == null) {
            view.addObject("error", "无效的用户");
            view.setViewName("merchant/errorInfo");
            return view;
        }
        if (StringUtil.isEmpty(t)) {
            view.addObject("error", "缺失参数！");
            view.setViewName("merchant/errorInfo");
            return view;
        }

        if (StringUtil.isEmpty(app.getMerchantCode())) {
            view.addObject("error", "暂不支持当前活动");
            view.setViewName("merchant/errorInfo");
            return view;
        }

        Map<String, Object> resultMap = getActRateParam(t);
        Date dateTime = new Date();
        String date = new SimpleDateFormat("yyyy-MM-dd").format(dateTime);
        String startDateStr = resultMap.get("startDate").toString();
        String endDateStr = resultMap.get("endDate").toString();


        Integer nowDateInt = Integer.parseInt(date.replace("-", ""));
        Integer startDateInt = Integer.parseInt(startDateStr.replace("-", ""));
        Integer endDateInt = Integer.parseInt(endDateStr.replace("-", ""));
        if (nowDateInt < startDateInt || nowDateInt > endDateInt) {
            date = null;
        }
        Map<String, Double> map = merchantOrderService.getCountTradeAmt(app.getMerchantCode(), date,
                startDateStr, endDateStr);
        view.addObject("map", map);

        //TODO 计算累计省钱金额和今日省钱金额
        String nowDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        Map<String, BigDecimal> result = merchantOrderService.getSaveMoneyCount(app.getMerchantCode(), nowDate, resultMap.get("startDate").toString(), resultMap.get("endDate").toString());
        view.addObject("result", result);
        view.addObject("token", token);
        view.addObject("t", t);
        view.setViewName("activity/act-one-thrift");
        return view;
    }

    @GetMapping("/one/invite")
    public ModelAndView actOneInvite(String token, String t, String count, HttpServletRequest request) {
        ModelAndView view = new ModelAndView();
        UserApp app = checkToken(token, view, request);
        if (app == null) {
            view.addObject("error", "无效的用户");
            view.setViewName("merchant/errorInfo");
            return view;
        }
        view.addObject("userCount", count);
        view.addObject("token", token);
        view.addObject("t", t);
        view.setViewName("activity/act-one-invite");
        return view;
    }

    @RequestMapping("/invite/page")
    @ResponseBody
    public Result<Map<String, Object>> invitePage(int pageNum, int pageSize, String t, String token, HttpServletRequest request) {
        ModelAndView view = new ModelAndView();
        UserApp app = checkToken(token, view, request);
        if (app == null) {
            return ResultGenerator.genFailResult(view.getModelMap().get("error").toString());
        }
        if (StringUtil.isEmpty(t)) {
            return ResultGenerator.genFailResult("缺失参数");
        }
        Map<String, Object> resultMap = getActRateParam(t);
        Date startDate = DateUtils.parse(resultMap.get("startDate").toString(), "yyyy-MM-dd");
        Date endDate = DateUtils.parse(resultMap.get("endDate").toString(), "yyyy-MM-dd");
        //TODO 获取下级用户
        Page<UserApp> page = new Page<UserApp>();
        page.setCurrent(pageNum);
        page.setSize(pageSize == 0 ? 10 : pageSize);
        UserApp userApp = new UserApp();
        userApp.setUserId(app.getUserId());
        userApp.setStartDate(startDate);
        userApp.setEndDate(endDate);
        page = userAppService.pageJoinData(page, userApp);

        Page<MerchantBaseInfo> merchantPage = new Page<MerchantBaseInfo>();
        merchantPage.setCurrent(pageNum);
        merchantPage.setSize(pageSize == 0 ? 10 : pageSize);
        merchantPage = merchantBaseInfoService.pageJoinData(merchantPage, userApp);
        Map<String, Object> result = new HashMap<>(2);
        result.put("userList", page);
        result.put("mercList", merchantPage);
        result.put("mercCount", merchantPage.getTotal());
        return ResultGenerator.genSuccessResult(result);
    }


    @RequestMapping("/income/page")
    @ResponseBody
    public Result<Page<MerchantProfit>> incomePage(int pageNum, int pageSize, String t, String token, HttpServletRequest request) {
        ModelAndView view = new ModelAndView();
        UserApp app = checkToken(token, view, request);
        if (app == null) {
            return ResultGenerator.genFailResult(view.getModelMap().get("error").toString());
        }
        if (StringUtil.isEmpty(t)) {
            return ResultGenerator.genFailResult("缺失参数");
        }
        Map<String, Object> resultMap = getActRateParam(t);
        Date startDate = DateUtils.parse(resultMap.get("startDate").toString() + " 00:00:00", "yyyy-MM-dd HH:mm:ss");
        Date endDate = DateUtils.parse(resultMap.get("endDate").toString() + " 23:59:59", "yyyy-MM-dd HH:mm:ss");

        Page<MerchantProfit> page = new Page<MerchantProfit>();
        page.setCurrent(pageNum);
        page.setSize(pageSize == 0 ? 10 : pageSize);
        QueryWrapper<MerchantProfit> profitWrapper = new QueryWrapper<MerchantProfit>()
                .ne("price", 0.0)
                .between("createDt", startDate, endDate)
                .eq("userId", app.getUserId()).orderByDesc("createDt");

        page = merchantProfitService.page(page, profitWrapper);
        return ResultGenerator.genSuccessResult(page);
    }


    @RequestMapping("/thrift/page")
    @ResponseBody
    public Result<Page<MerchantOrder>> thriftPage(int pageNum, int pageSize, String t, String token, HttpServletRequest request) {
        ModelAndView view = new ModelAndView();
        UserApp app = checkToken(token, view, request);
        if (app == null) {
            return ResultGenerator.genFailResult(view.getModelMap().get("error").toString());
        }
        if (StringUtil.isEmpty(t)) {
            return ResultGenerator.genFailResult("缺失参数");
        }

        if (StringUtil.isEmpty(app.getMerchantCode())) {
            return ResultGenerator.genFailResult("暂不支持当前活动");
        }
        Map<String, Object> resultMap = getActRateParam(t);
        Date startDate = DateUtils.parse(resultMap.get("startDate").toString() + " 00:00:00", "yyyy-MM-dd HH:mm:ss");
        Date endDate = DateUtils.parse(resultMap.get("endDate").toString() + " 23:59:59", "yyyy-MM-dd HH:mm:ss");

        Page<MerchantOrder> page = new Page<MerchantOrder>();
        page.setCurrent(pageNum);
        page.setSize(pageSize == 0 ? 10 : pageSize);
        MerchantOrder order = new MerchantOrder();
        order.setMerchantCode(app.getMerchantCode());
        order.setStatus("1");
        order.setStartTime(startDate);
        order.setEndTime(endDate);
        page = merchantOrderService.pageWapInfo(page, order);
        return ResultGenerator.genSuccessResult(page);
    }


    @GetMapping("/index")
    public ModelAndView index(String token, String t, HttpServletRequest request) {
        ModelAndView view = new ModelAndView();
        UserApp app = checkToken(token, view, request);
        if (app == null) {
            view.addObject("error", "无效的用户");
            view.setViewName("merchant/errorInfo");
            return view;
        }
        String activityGroupNo = null;
        if (StringUtil.isNotEmpty(t)) {
            activityGroupNo = t;
        } else {
            if ("agent".equals(app.getUserType())) {
                activityGroupNo = "super";
            } else {
                activityGroupNo = "general";
            }
        }
        view.setViewName("activity/activity");
        view.addObject("token", token);
        BigDecimal countIntegral = userIntegralService.getCountIntegral(app.getUserId());
        BigDecimal useIntegral = userIntegralUseService.getUseIntegral(app.getUserId());
        BigDecimal useAmt = countIntegral.add(useIntegral);
        if (useAmt.compareTo(BigDecimal.ZERO) < 0) {
            useAmt = new BigDecimal("0.00");
        }
        view.addObject("useAmt", useAmt);
        view.addObject("marketAmtCount", countIntegral);
        OfficialActivity condition = new OfficialActivity();
        condition.setActivityGroupNo(activityGroupNo);
        condition.setStatus("2");
        condition.setRoleType(app.getRoleCode());
        List<OfficialActivity> list = officialActivityService.getListByRole(condition);
        view.addObject("activityList", list);
        condition.setStatus("3");
        List<OfficialActivity> oldList = officialActivityService.getListByRole(condition);
        view.addObject("activitOldList", oldList);
        view.addObject("t", activityGroupNo);
        view.addObject("domain",ParametersUtil.domain);
        return view;
    }

    private UserApp checkToken(String token, ModelAndView view, HttpServletRequest request) {
        if (StringUtil.isEmpty(token)) {
            view.addObject("error", "无效的token");
            view.setViewName("merchant/errorInfo");
            return null;
        }

        Object obj = request.getSession().getAttribute(token);
        if ((obj instanceof UserApp)) {
            return (UserApp) obj;
        } else {
            QueryWrapper<UserApp> queryAppWrapper = new QueryWrapper<>();
            queryAppWrapper.eq("token", token);
            UserApp app = userAppService.getOne(queryAppWrapper);
            if (app == null) {
                view.addObject("error", "无效的token");
                view.setViewName("merchant/errorInfo");
                return null;
            }
            request.getSession().setAttribute(token, app);
            return app;
        }
    }

    @GetMapping("/desc")
    public ModelAndView desc(String token, HttpServletRequest request) {
        ModelAndView view = new ModelAndView();
        view.setViewName("activity/desc");
        return view;
    }


    @GetMapping("/good")
    public ModelAndView good(String token, HttpServletRequest request) {
        ModelAndView view = new ModelAndView();
        UserApp app = checkToken(token, view, request);
        if (app == null) {
            return view;
        }
        view.setViewName("activity/goods");
        BigDecimal countIntegral = userIntegralService.getCountIntegral(app.getUserId());
        BigDecimal useIntegral = userIntegralUseService.getUseIntegral(app.getUserId());
        BigDecimal useAmt = countIntegral.add(useIntegral);
        if (useAmt.compareTo(BigDecimal.ZERO) < 0) {
            useAmt = new BigDecimal("0.00");
        }
        QueryWrapper<OfficialGoods> queryGoodsWrapper = new QueryWrapper<OfficialGoods>().orderByDesc("createTime");
        queryGoodsWrapper.eq("status", "2");
        List<OfficialGoods> list = officialGoodsService.list(queryGoodsWrapper);
        view.addObject("useAmt", useAmt);
        view.addObject("token", token);
        view.addObject("goodList", list);
        return view;
    }

    @GetMapping("/exchange/order")
    public ModelAndView exchangeOrder(String token, Integer g, Integer aid,HttpServletRequest request) {
        ModelAndView view = new ModelAndView();
        UserApp app = checkToken(token, view, request);
        if (app == null) {
            return view;
        }
        if (StringUtil.isEmpty(g)) {
            view.addObject("error", "无效的商品");
            view.setViewName("merchant/errorInfo");
            return view;
        }
        OfficialGoods good = officialGoodsService.getById(g);
        if (StringUtil.isEmpty(good)) {
            view.addObject("error", "无效的商品");
            view.setViewName("merchant/errorInfo");
            return view;
        }
        if (!"2".equals(good.getStatus())) {
            view.addObject("error", "不可兑换的商品！");
            view.setViewName("merchant/errorInfo");
            return view;
        }
        UserAddress userAddres = null;
        if(StringUtil.isNotEmpty(aid)){
            userAddres = userAddressService.getById(aid);
        }else{
            List<UserAddress> addressList = userAddressService.getAddressList(app.getUserId(), 1, true);
            if(!addressList.isEmpty()){
                userAddres = addressList.get(0);
            }
        }
        view.addObject("userAddres", userAddres);
        view.addObject("good", good);
        view.addObject("token", token);
        if(StringUtil.isEmpty(aid) && userAddres != null){
            view.addObject("aid", userAddres.getId());
        }else{
            view.addObject("aid", aid);
        }
        view.setViewName("activity/order");
        return view;
    }

    @GetMapping("/address")
    public ModelAndView address(String token, Integer g, HttpServletRequest request) {
        ModelAndView view = new ModelAndView();
        UserApp app = checkToken(token, view, request);
        if (app == null) {
            return view;
        }
        List<UserAddress> addressList = userAddressService.getAddressList(app.getUserId(), 1,false);
        view.addObject("addressList", addressList);
        view.addObject("token", token);
        view.addObject("g", g);
        view.setViewName("activity/address");
        return view;
    }

    @PostMapping("/address/del/{id}")
    @ResponseBody
    public Result addressDel(@PathVariable("id") Integer id) {
        userAddressService.removeById(id);
        return ResultGenerator.genSuccessResult("操作成功",null);
    }

    @PostMapping("/address/save")
    @ResponseBody
    public Result addressSave(@RequestParam Map<String,String> params, HttpServletRequest request) {
        ModelAndView view = new ModelAndView();
        UserApp app = checkToken(params.get("token"), view, request);
        if (app == null) {
            return ResultGenerator.genFailResult(view.getModelMap().get("error").toString());
        }
        UserAddress userAddress = new UserAddress();
        if(StringUtil.isNotEmpty(params.get("id"))){
            userAddress.setId(Integer.valueOf(params.get("id")));
        }
        userAddress.setUserId(Integer.valueOf(app.getUserId().toString()));
        userAddress.setName(params.get("name"));
        userAddress.setPhone(params.get("phone"));
        userAddress.setAddress(params.get("address"));
        userAddress.setAreaCode(params.get("areaCode"));
        userAddress.setAreaName(params.get("areaName"));
        userAddress.setType(1);
        userAddress.setDefFlag(params.get("defFlag"));
        userAddressService.saveOrUpdate(userAddress);
        return ResultGenerator.genSuccessResult("操作成功",userAddress);
    }

    @GetMapping("/address/add")
    public ModelAndView addressAdd(String token, Integer g,Integer aid, HttpServletRequest request) {
        ModelAndView view = new ModelAndView();
        UserApp app = checkToken(token, view, request);
        if (app == null) {
            return view;
        }
        if(StringUtil.isNotEmpty(aid)){
            UserAddress userAddress = userAddressService.getById(aid);
            view.addObject("userAddress", userAddress);
        }
        view.addObject("token", token);
        view.addObject("g", g);
        view.setViewName("activity/addressPost");
        return view;
    }

    @GetMapping("/good/detail")
    public ModelAndView goodDetail(String token, Integer g, HttpServletRequest request) {
        ModelAndView view = new ModelAndView();
        UserApp app = checkToken(token, view, request);
        if (app == null) {
            return view;
        }
        if (StringUtil.isEmpty(g)) {
            view.addObject("error", "无效的商品");
            view.setViewName("merchant/errorInfo");
            return view;
        }
        OfficialGoods good = officialGoodsService.getById(g);
        if (StringUtil.isEmpty(good)) {
            view.addObject("error", "无效的商品");
            view.setViewName("merchant/errorInfo");
            return view;
        }
        if (!"2".equals(good.getStatus())) {
            view.addObject("error", "不可兑换的商品！");
            view.setViewName("merchant/errorInfo");
            return view;
        }
        BigDecimal countIntegral = userIntegralService.getCountIntegral(app.getUserId());
        BigDecimal useIntegral = userIntegralUseService.getUseIntegral(app.getUserId());
        BigDecimal useAmt = countIntegral.add(useIntegral);
        if (good.getGoodPrice().compareTo(useAmt) > 0) {
            view.addObject("flag", "0");
        }else{
            view.addObject("flag", "1");
        }
        view.addObject("good", good);
        view.addObject("token", token);
        view.setViewName("activity/goodDetail");
        return view;
    }

    @GetMapping("/exchange/view")
    public ModelAndView goodDetail(Page<OfficialGoodsExchange> page, String token, HttpServletRequest request) {
        ModelAndView view = new ModelAndView();
        UserApp app = checkToken(token, view, request);
        if (app == null) {
            return view;
        }
        QueryWrapper<OfficialGoodsExchange> queryExchangeQuery = new QueryWrapper<OfficialGoodsExchange>().orderByDesc("createTime");
        queryExchangeQuery.eq("userId", app.getUserId());
        page = officialGoodsExchangeService.page(page, queryExchangeQuery);
        view.addObject("goodExchange", page);

        BigDecimal countIntegral = userIntegralService.getCountIntegral(app.getUserId());
        BigDecimal useIntegral = userIntegralUseService.getUseIntegral(app.getUserId());
        BigDecimal useAmt = countIntegral.add(useIntegral);
        view.addObject("token", token);
        view.addObject("useAmt", useAmt);
        view.setViewName("activity/goodExchange");
        return view;
    }


    @PostMapping("/goods/exchange/page")
    @ResponseBody
    public Result exchangePage(int pageNum, int pageSize, String token, HttpServletRequest request) {
        ModelAndView view = new ModelAndView();
        UserApp app = checkToken(token, view, request);
        if (app == null) {
            return ResultGenerator.genFailResult(view.getModelMap().get("error").toString());
        }
        Page<OfficialGoodsExchange> page = new Page<OfficialGoodsExchange>();
        page.setCurrent(pageNum);
        page.setSize(pageSize == 0 ? 10 : pageSize);
        QueryWrapper<OfficialGoodsExchange> goodsQuery = new QueryWrapper<OfficialGoodsExchange>().eq("userId", app.getUserId());
        page = officialGoodsExchangeService.page(page, goodsQuery);
        return ResultGenerator.genSuccessResult(page);
    }

    /**
     * 活动报名
     *
     * @param token
     * @param request
     * @param actId
     * @return
     */
    @NoRepeatSubmit
    @PostMapping("/toEnroll")
    @ResponseBody
    public Result toEnroll(String token, HttpServletRequest request, Integer actId, String deviceNo, String c, ModelAndView view) {
        UserApp app = checkToken(token, view, request);
        if (app == null) {
            return ResultGenerator.genFailResult(view.getModelMap().get("error").toString());
        }
        if (StringUtil.isEmpty(deviceNo)) {
            return ResultGenerator.genFailResult("设备编号不能为空！");
        }
        if (StringUtil.isEmpty(actId)) {
            return ResultGenerator.genFailResult("请选择正确的活动报名!");
        }
        OfficialActivity activity = officialActivityService.getById(actId);
        if (activity == null) {
            return ResultGenerator.genFailResult("活动异常!");
        }
        if (!"2".equals(activity.getStatus())) {
            return ResultGenerator.genFailResult("当前活动已过期或已下架!");
        }
        QueryWrapper<MerchantBaseInfo> queryWrapper = new QueryWrapper<MerchantBaseInfo>().eq("userId", app.getUserId());
        MerchantBaseInfo merchant = merchantBaseInfoService.getOne(queryWrapper);
        if (merchant == null) {
            return ResultGenerator.genFailResult("请先认证成为商户!");
        }
        QueryWrapper<ActivityEnroll> enrollQueryWrapper = new QueryWrapper<ActivityEnroll>()
                .eq("merchantCode", app.getMerchantCode()).eq("status", "0").eq("actId", actId);
        List<ActivityEnroll> list = activityEnrollService.list(enrollQueryWrapper);
        if (!list.isEmpty()) {
            return ResultGenerator.genFailResult("您已报名此活动，请勿重复报名!");
        }

        if (!"3".equals(c)) {
            QueryWrapper<DeviceStock> stockWrapper = new QueryWrapper<DeviceStock>().eq("deviceNo", deviceNo);
            List<DeviceStock> stockList = deviceStockService.list(stockWrapper);
            if (stockList.isEmpty()) {
                return ResultGenerator.genFailResult("设备SN号有误，请重新输入!");
            }
        }
        String startDateStr = DateUtils.formatDateDefault(activity.getStartTime(), "yyyyMMdd");
        String endDateStr = DateUtils.formatDateDefault(activity.getEndTime(), "yyyyMMdd");
        String nowDateStr = DateUtils.formatDateDefault(new Date(), "yyyyMMdd");
        if (Integer.valueOf(startDateStr) <= Integer.valueOf(nowDateStr)
                && Integer.valueOf(endDateStr) >= Integer.valueOf(nowDateStr)) {
            ActivityEnroll enroll = new ActivityEnroll();
            enroll.setActId(actId);
            enroll.setActType(activity.getActType());
            enroll.setActName(activity.getOfficName());
            enroll.setMerchantCode(merchant.getMerchantCode());
            enroll.setMerchantName(merchant.getAlias());
            enroll.setStatus("0");
            enroll.setCreateTime(new Date());
            enroll.setDeviceNo(deviceNo);
            activityEnrollService.save(enroll);
            return ResultGenerator.genSuccessResult("申请成功，等待审核...", null);
        } else {
            return ResultGenerator.genFailResult("活动已过期，无法报名", null);
        }
    }


    @PostMapping("/goods/exchange")
    @ResponseBody
    public Result exchange(Integer goodsId, String token,Integer aid, HttpServletRequest request) {
        ModelAndView view = new ModelAndView();
        UserApp app = checkToken(token, view, request);
        if (app == null) {
            return ResultGenerator.genFailResult(view.getModelMap().get("error").toString());
        }
        if (StringUtil.isEmpty(goodsId)) {
            return ResultGenerator.genFailResult("商品ID不能为空！");
        }
        if (StringUtil.isEmpty(aid)) {
            return ResultGenerator.genFailResult("收货地址不能为空！");
        }
        OfficialGoods goods = officialGoodsService.getById(goodsId);
        if (goods == null) {
            return ResultGenerator.genFailResult("商品不存在！");
        }
        if (!"2".equals(goods.getStatus())) {
            return ResultGenerator.genFailResult("商品已下架，请选择其他商品！");
        }
        BigDecimal goodsPrice = goods.getGoodPrice();
        BigDecimal countIntegral = userIntegralService.getCountIntegral(app.getUserId());
        BigDecimal useIntegral = userIntegralUseService.getUseIntegral(app.getUserId());
        BigDecimal useAmt = countIntegral.add(useIntegral);
        if (goodsPrice.compareTo(useAmt) > 0) {
            return ResultGenerator.genFailResult("积分不足，兑换失败！");
        }
        return officialGoodsExchangeService.exchange(goods, app,aid);
    }

    @PostMapping("/page")
    @ResponseBody
    public Result page(int pageNum, int pageSize, String token, HttpServletRequest request, String date) {
        ModelAndView view = new ModelAndView();
        UserApp app = checkToken(token, view, request);
        if (app == null) {
            return ResultGenerator.genFailResult("无效用户");
        }
        UserIntegral query = new UserIntegral();
        query.setUserId(app.getUserId());
        query.setQueryDate(date);
        Page<UserIntegral> page = new Page<>();
        page.setCurrent(pageNum);
        page.setSize(pageSize == 0 ? 10 : pageSize);
        page = userIntegralService.pageInfo(page, query);

        QueryWrapper<UserIntegralUse> queryWrapper = new QueryWrapper<UserIntegralUse>().orderByDesc("createTime");
        queryWrapper.eq("userId", app.getUserId());
        queryWrapper.eq("DATE_FORMAT(createTime,'%Y-%m')", date);
        Page<UserIntegralUse> pageCash = new Page<>();
        pageCash.setCurrent(pageNum);
        pageCash.setSize(pageSize == 0 ? 10 : pageSize);
        pageCash = userIntegralUseService.page(pageCash, queryWrapper);
        Map<String, Object> result = new HashMap<>(2);
        result.put("orderList", page);
        result.put("cashList", pageCash);
        return ResultGenerator.genSuccessResult(result);
    }


    @GetMapping("/detail")
    public ModelAndView detail(String type, String date, String token, HttpServletRequest request) {
        ModelAndView view = new ModelAndView();
        UserApp app = checkToken(token, view, request);
        if (app == null) {
            return view;
        }
        view.setViewName("activity/detail");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
        String nowDateStr = format.format(new Date());
        try {
            List<Map<String, Object>> last6Months = DateUtils.getLast6Months();
            view.addObject("monthList", JSONArray.toJSONString(last6Months));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (StringUtil.isEmpty(date)) {
            date = nowDateStr;
            view.addObject("nowYear", DateUtils.getNowYear());
            view.addObject("nowMonth", DateUtils.getNowMonth() < 10 ? "0" + DateUtils.getNowMonth() : DateUtils.getNowMonth());
        } else {
            view.addObject("nowYear", date.split("-")[0]);
            view.addObject("nowMonth", date.split("-")[1]);
        }
        BigDecimal countIntegral = userIntegralService.getCountIntegral(app.getUserId(), date, null);
        view.addObject("incomeAmt", countIntegral);
        BigDecimal useIntegral = userIntegralUseService.getUseIntegral(app.getUserId(),date);
        view.addObject("expendAmt", Math.abs(useIntegral.doubleValue()));
        view.addObject("type", type);
        view.addObject("token", token);
        return view;
    }
}
