package com.bweb.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.RedisUtil;
import com.hfkj.common.utils.ResponseMsgUtil;
import com.hfkj.entity.*;
import com.hfkj.model.ResponseData;
import com.hfkj.model.UserSessionObject;
import com.hfkj.service.gas.BsGasOrderService;
import com.hfkj.service.gas.BsGasOrderSpreadService;
import com.hfkj.service.sec.SecDictionaryService;
import com.hfkj.service.spread.*;
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.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @className: BsUserSpreadController
 * @author: HuRui
 * @date: 2025/3/31
 **/
@Controller
@RequestMapping(value = "/userSpread")
@Api(value = "个人推广业务")
public class BsUserSpreadController {
    private static Logger log = LoggerFactory.getLogger(BsUserSpreadController.class);
    @Resource
    private BsUserSpreadOilChannelService userSpreadOilChannelService;
    @Resource
    private BsUserSpreadAccountRecordService userSpreadAccountRecordService;
    @Resource
    private BsUserSpreadAccountService userSpreadAccountService;
    @Resource
    private BsGasOrderSpreadService gasOrderSpreadService;
    @Resource
    private BsGasOrderService gasOrderService;
    @Resource
    private BsUserSpreadRelService userSpreadRelService;
    @Resource
    private SecDictionaryService secDictionaryService;

    @RequestMapping(value = "/editOilChannel", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "编辑油站渠道")
    public ResponseData editOilChannel(@RequestBody JSONObject body) {
        try {
            if (body == null
                    || body.getInteger("channel") == null
                    || body.getBigDecimal("rebate") == null
                    || body.getBigDecimal("rebateOne") == null
            ) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            // 查询渠道
            BsUserSpreadOilChannel channel = userSpreadOilChannelService.getDetailByChannel(body.getInteger("channel"));
            if (channel == null) {
                channel = new BsUserSpreadOilChannel();
                channel.setChannel(body.getInteger("channel"));
            }
            channel.setRebate(body.getBigDecimal("rebate"));
            channel.setRebateOne(body.getBigDecimal("rebateOne"));
            channel.setRebateTwo(body.getBigDecimal("rebateTwo")!=null?body.getBigDecimal("rebateTwo"):new BigDecimal("0"));
            userSpreadOilChannelService.editData(channel);

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

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

    @RequestMapping(value = "/getOilChannelDetail", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询油站渠道详情")
    public ResponseData getOilChannelDetail(@RequestParam(value = "id", required = true) Long id) {
        try {

            return ResponseMsgUtil.success(userSpreadOilChannelService.getDetail(id));

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

    @RequestMapping(value = "/getOilChannelList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询油站渠道列表")
    public ResponseData getOilChannelList(@RequestParam(value = "channel", required = false) Integer channel) {
        try {
            Map<String,Object> param = new HashMap<>();
            param.put("channel", channel);
            return ResponseMsgUtil.success(userSpreadOilChannelService.getList(param));

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

    @RequestMapping(value = "/getUserSpreadList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询推广用户列表")
    public ResponseData getUserSpreadList(@RequestParam(value = "phone", required = false) String phone,
                                          @RequestParam(value = "pageNum", required = true) Integer pageNum,
                                          @RequestParam(value = "pageSize", required = true) Integer pageSize) {
        try {
            Map<String,Object> param = new HashMap<>();
            param.put("phone", phone);

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

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

    @RequestMapping(value = "/freezeUserSpread", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "冻结用户推广功能")
    public ResponseData freezeUserSpread(@RequestBody JSONObject body) {
        try {
            if (body == null || body.getLong("userId") == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            userSpreadAccountService.freezeUserSpread(body.getLong("userId"));
            return ResponseMsgUtil.success("操作成功");

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

    @RequestMapping(value = "/unfreezeUserSpread", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "解冻用户推广功能")
    public ResponseData unfreezeUserSpread(@RequestBody JSONObject body) {
        try {
            if (body == null || body.getLong("userId") == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            userSpreadAccountService.unfreezeUserSpread(body.getLong("userId"));
            return ResponseMsgUtil.success("操作成功");

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

    @RequestMapping(value = "/countCommission", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "统计佣金情况")
    public ResponseData countCommission() {
        try {

            return ResponseMsgUtil.success(gasOrderSpreadService.countCommission());

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


    @RequestMapping(value = "/recharge", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "充值")
    public ResponseData recharge(@RequestBody JSONObject body) {
        try {
            if (body == null || body.getBigDecimal("amount") == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            List<SecDictionary> data = secDictionaryService.getDictionary("SYS_USER_SPREAD_ACCOUNT");
            if (data != null && !data.isEmpty()) {
                SecDictionary account = data.get(0);
                account.setCodeName(new BigDecimal(account.getCodeName()).add(body.getBigDecimal("amount")).toString());
                secDictionaryService.update(account);
                // 清除缓存
                secDictionaryService.cleanCache();
            }
            return ResponseMsgUtil.success("操作成功");

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


    @RequestMapping(value = "/countAccount", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "统计金额")
    public ResponseData countAccount(@RequestParam(value = "userId", required = false) Long userId,
                                     @RequestParam(name = "orderStatus", required = false) Integer orderStatus,
                                     @RequestParam(name = "payTimeS", required = false) Long payTimeS,
                                     @RequestParam(name = "payTimeE", required = false) Long payTimeE) {
        try {
            Map<String,Object> param = new HashMap<>();
            param.put("userId", userId);
            param.put("orderStatus", orderStatus);
            param.put("payTimeS", payTimeS);
            param.put("payTimeE", payTimeE);
            return ResponseMsgUtil.success(gasOrderSpreadService.countSettleOrderPrice(param));

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

    @RequestMapping(value="/queryOilOrderSpread",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询加油推广订单")
    public ResponseData queryOilOrderSpread(@RequestParam(value = "userId", required = false) Long userId,
                                            @RequestParam(name = "orderNo", required = false) String orderNo,
                                            @RequestParam(name = "orderStatus", required = false) Integer orderStatus,
                                            @RequestParam(name = "payTimeS", required = false) Long payTimeS,
                                            @RequestParam(name = "payTimeE", required = false) Long payTimeE,
                                            @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                            @RequestParam(name = "pageSize", required = true) Integer pageSize) {
        try {
            Map<String,Object> param = new HashMap<>();
            param.put("userId", userId);
            param.put("orderNo", orderNo);
            param.put("status", orderStatus);
            param.put("payTimeS", payTimeS);
            param.put("payTimeE", payTimeE);

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

        } catch (Exception e) {
            log.error("error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/getAccount", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询余额账户")
    public ResponseData getAccount(@RequestParam(value = "userId", required = true) Long userId) {
        try {
            // 查询账户
            BsUserSpreadAccount userSpreadAccount = userSpreadAccountService.getDetailByUser(userId);
            if (userSpreadAccount == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            HashMap<String,Object> map = new HashMap<>();
            // 账户余额
            map.put("amount", userSpreadAccount.getAmount());
            map.put("cashOutAmount", userSpreadAccount.getCashOutAmount());
            map.put("notCashOutAmount", gasOrderSpreadService.getNotCashOutAmount(userSpreadAccount.getUserId()));
            return ResponseMsgUtil.success(map);

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

    @RequestMapping(value = "/getRecordList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询记录列表")
    public ResponseData getRecordList(@RequestParam(value = "userId", required = false) Long userId,
                                      @RequestParam(value = "userPhone", required = false) String userPhone,
                                      @RequestParam(value = "type", required = false) Integer type,
                                      @RequestParam(value = "sourceType", required = false) Integer sourceType,
                                      @RequestParam(value = "createTimeS", required = false) Long createTimeS,
                                      @RequestParam(value = "createTimeE", required = false) Long createTimeE,
                                      @RequestParam(value = "pageNum", required = true) Integer pageNum,
                                      @RequestParam(value = "pageSize", required = true) Integer pageSize) {
        try {
            Map<String,Object> param = new HashMap<>();
            param.put("userId", userId);
            param.put("userPhone", userPhone);
            param.put("type", type);
            param.put("sourceType", sourceType);
            param.put("createTimeS", createTimeS);
            param.put("createTimeE", createTimeE);

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

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


    @RequestMapping(value = "/countRecordAmount", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "统计记录")
    public ResponseData countRecordAmount(@RequestParam(value = "userId", required = false) Long userId,
                                          @RequestParam(value = "userPhone", required = false) String userPhone,
                                          @RequestParam(value = "type", required = false) Integer type,
                                          @RequestParam(value = "sourceType", required = false) Integer sourceType,
                                          @RequestParam(value = "createTimeS", required = false) Long createTimeS,
                                          @RequestParam(value = "createTimeE", required = false) Long createTimeE) {
        try {
            Map<String,Object> param = new HashMap<>();
            param.put("userId", userId);
            param.put("userPhone", userPhone);
            param.put("type", type);
            param.put("sourceType", sourceType);
            param.put("createTimeS", createTimeS);
            param.put("createTimeE", createTimeE);

            return ResponseMsgUtil.success(userSpreadAccountRecordService.countRecordAmount(param));

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

}
