package cn.pluss.platform.jfShop;

import cn.pluss.platform.api.Result;
import cn.pluss.platform.api.ResultGenerator;
import cn.pluss.platform.constants.Constant;
import cn.pluss.platform.entity.*;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.mapper.MerchantQrcodeMapper;
import cn.pluss.platform.merchant.MerchantBaseInfoService;
import cn.pluss.platform.merchantOrder.MerchantOrderService;
import cn.pluss.platform.merchantQrcode.MerchantQrcodeService;
import cn.pluss.platform.other.JfShopParam;
import cn.pluss.platform.other.JfShopSyncUser;
import cn.pluss.platform.other.JfShopAccount;
import cn.pluss.platform.other.JfShopValidTask;
import cn.pluss.platform.other.enums.JfShopTaskType;
import cn.pluss.platform.transferCash.MerchantTransferCashService;
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.DateUtils;
import cn.pluss.platform.util.StringUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.pluss.platform.other.enums.JfShopTaskType.*;

/**
 * TODO
 * 新版积分商城相关处理handler
 * @author crystal
 * @date 2022/5/13 17:02
 */
@Slf4j
@Component
public class JfShopHandler {

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private UserInfoService userInfoService;

    @Resource
    private UserAppService userAppService;

    @Resource
    private UserIntegralUseService userIntegralUseService;

    @Resource
    private UserIntegralService userIntegralService;

    @Resource
    private MerchantQrcodeMapper merchantQrcodeMapper;

    @Resource
    private MerchantOrderService merchantOrderService;
    /**
     * 同步积分商城用户
     * @param userApp
     * @return
     */
    public String syncJfShopUser(UserApp userApp,UserInfo userInfo){
        try {
            if(userInfo == null){
                userInfo = userInfoService.getById(userApp.getUserId());
            }
            if(userInfo == null){
                MsgException.throwException("用户信息异常，同步失败");
            }
            JfShopSyncUser jfUser = new JfShopSyncUser(userInfo,userApp);
            String reqUrl = Constant.JF_SHOP_USER_SYNC_URL;
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            Map<String, Object> params = JSON.parseObject(JSON.toJSONString(jfUser),Map.class);
            MultiValueMap<String, String> map = new LinkedMultiValueMap();
            for (Map.Entry m:params.entrySet()) {
                map.add(m.getKey().toString(),m.getValue().toString());
            }
            HttpEntity<MultiValueMap<String, String>> request =
                    new HttpEntity<>(map, headers);
            String result = restTemplate.postForObject(reqUrl, request, String.class);
            log.info("【新版积分商城】同步用户请求成功，返回信息:{}",result);
            return result;
        }catch (Exception e){
            e.printStackTrace();
            log.info("【新版积分商城】同步用户失败，异常信息:{}",e.getMessage());
            return null;
        }
    }

    /**
     * 积分商城接口
     * @param param
     * @return
     */
    public Result<JfShopAccount> getAccount(JfShopParam param) {
        log.info("【新版积分商城】获取账户积分详情请求,请求参数:{}", JSON.toJSONString(param));
        param.check();
        String userId = param.getUserId();
        BigDecimal totalIntegral = userIntegralService.getCountIntegral(Long.valueOf(userId));
        BigDecimal useInteral = userIntegralUseService.getUseIntegral(Long.valueOf(userId));
        BigDecimal useAmt = totalIntegral.add(useInteral);
        JfShopAccount resp = new JfShopAccount(totalIntegral,useInteral,useAmt);
        return ResultGenerator.genSuccessResult("获取成功",resp);
    }

    /**
     * 接口分页查询
     * @param param
     * @return
     */
    public Object page(JfShopParam param) {
        param.check();
        Page page = new Page();
        page.setCurrent(param.getCurrent());
        page.setSize(param.getSize());
        if(JfShopParam.LIST_TYPE_ADD.equals(param.getListType())){
            UserIntegral query = new UserIntegral();
            query.setUserId(Long.valueOf(param.getUserId()));
            query.setType(param.getType());
            query.setOrderNumber(param.getOrderNumber());
            page = userIntegralService.pageInfo(page,query);
        }else{
            UserIntegralUse query = new UserIntegralUse();
            query.setUserId(Long.valueOf(param.getUserId()));
            page = userIntegralUseService.pageInfo(page,query);
        }
        return ResultGenerator.genSuccessResult("获取成功",page);
    }

    /**
     * 增加积分接口
     * @param param
     * @return
     */
//    public Result<Object> addIntegral(JfShopParam param) {
//        param.check(JfShopParam.OPTION_ADD);
//        UserInfo info = userInfoService.getById(param.getUserId());
//        MsgException.checkNull(info,"用户信息不存在或用户ID有误！");
//        UserIntegral integral = new UserIntegral(Long.valueOf(param.getUserId()),param.getIntegral(),param.getType(),param.getType(),param.getRemark());
//        userIntegralService.save(integral);
//        return ResultGenerator.genSuccessResult("操作成功",null);
//    }

    /**
     * 积分操作接口
     * @param param
     * @return
     */
    public Result<Object> operate(JfShopParam param) {
        UserIntegral integral = null;
        UserIntegralUse userIntegralUse = null;
        switch (param.getListType()){
            case JfShopParam.LIST_TYPE_ADD:
                param.check(JfShopParam.OPERATE_ADD);
                integral = new UserIntegral(Long.valueOf(param.getUserId()),param.getIntegral(),param.getType(),param.getType(),param.getRemark());
                break;
            case JfShopParam.LIST_TUPE_USE:
                param.check(JfShopParam.OPERATE_USE);
                userIntegralUse = new UserIntegralUse(param.getName(),Long.valueOf(param.getUserId()),param.getIntegral(),param.getOrderNumber(),param.getRemark());
                break;
            default:
                MsgException.throwException("未知类型");
        }
        UserInfo info = userInfoService.getById(param.getUserId());
        MsgException.checkNull(info,"用户信息不存在或用户ID有误！");
        if(integral != null){
            userIntegralService.save(integral);
        }
        if(userIntegralUse != null){
            userIntegralUseService.save(userIntegralUse);
        }
        return ResultGenerator.genSuccessResult("操作成功",null);
    }

    /**
     * 获取积分商城任务完成进度
     * @param param
     * @return
     */
    public Result<Object> getTaskStatus(JfShopValidTask param) {
        param.check();
        UserApp userApp = checkUserInfo(param.getUserId());
        Boolean flag = false;
        List<Map<String, Object>> list = new ArrayList<>(10);
        Map<String, Object> map = new HashMap<>();
        int num = 0;
        String dateMonth = DateUtils.toString(DateUtils.currentDate(), "yyyy-MM");
        if(StringUtil.isNotEmpty(userApp.getMerchantCode())){
            String sql = " WHERE merchantCode = '"+userApp.getMerchantCode()+"' AND `status` = 1 AND DATE_FORMAT( createDate, '%Y-%m' ) = '"+dateMonth+"' GROUP BY DATE_FORMAT(createDate,'%Y-%m')";
            QueryWrapper<MerchantOrder> queryWrapper = new QueryWrapper<MerchantOrder>().last(sql);
            num = merchantOrderService.count(queryWrapper);
        }
        switch (JfShopTaskType.matchStatus(param.getTaskType())){
            case ALL:
                getAllTask(num,userApp.getMerchantCode(),list,flag);
                break;
            case PAY_FRIENDS:
                setPayFriends(userApp.getMerchantCode(),flag,map,list);
                break;
            case BIND_ORDER_PUSH:
                setOrderPush(userApp.getMerchantCode(),flag,map,list);
                break;
            case USE_HELP_CENTER:
                setNoGetStatus(USE_HELP_CENTER.getCode(),map,flag,list);
                break;
            case USE_PRODUCT_MANUAL:
                setNoGetStatus(USE_PRODUCT_MANUAL.getCode(),map,flag,list);
                break;
            case MONTH_COLLECT_3:
                setMonthCollect(num,flag,MONTH_COLLECT_3,map,list);
                break;
            case MONTH_COLLECT_7:
                setMonthCollect(num,flag,MONTH_COLLECT_7,map,list);
                break;
            case MONTH_COLLECT_15:
                setMonthCollect(num,flag,MONTH_COLLECT_15,map,list);
                break;
            default:
                MsgException.throwException("未知任务类型");
        }
        return ResultGenerator.genSuccessResult("获取成功",list);
    }

    private void setMonthCollect(int num,Boolean flag,JfShopTaskType taskType,Map<String, Object> map,List<Map<String, Object>> list) {
        if(num >= taskType.getValue()){
            flag = true;
        }
        map.put(taskType.getCode(),flag);
        map.put("num",num);
        list.add(map);
    }


    private void setNoGetStatus(String code,Map<String, Object> map,Boolean flag,List<Map<String, Object>> list) {
        map.put(code,flag);
        list.add(map);
    }

    private void setPayFriends(String merchantCode,Boolean flag,Map<String, Object> map,List<Map<String, Object>> list) {
        MerchantQrcode qrcode = merchantQrcodeMapper.getByMerchantCode(merchantCode);
        if(qrcode != null){
            flag = true;
        }
        map.put(PAY_FRIENDS.getCode(),flag);
        list.add(map);
    }

    /**
     * 获取所有权限
     * @param num
     * @param merchantCode
     */
    private void getAllTask(int num, String merchantCode,List<Map<String, Object>> list,Boolean flag) {
        for (JfShopTaskType taskType : JfShopTaskType.values()) {
            if(taskType.getCode().equals(ALL.getCode())){
                continue;
            }
            Map<String, Object> map = new HashMap<>(2);
            if(taskType.getCode().equals(PAY_FRIENDS.getCode())){
                setPayFriends(merchantCode,flag,map,list);
            }else if(taskType.getCode().equals(BIND_ORDER_PUSH.getCode())){
                setOrderPush(merchantCode,flag,map,list);
            }else if(taskType.getCode().equals(USE_HELP_CENTER.getCode()) || taskType.getCode().equals(USE_PRODUCT_MANUAL.getCode())){
                setNoGetStatus(taskType.getCode(),map,flag,list);
            }else if(
                    taskType.getCode().equals(MONTH_COLLECT_3.getCode()) ||
                    taskType.getCode().equals(MONTH_COLLECT_7.getCode()) ||
                    taskType.getCode().equals(MONTH_COLLECT_15.getCode())){
                setMonthCollect(num,flag,taskType,map,list);
            }
        }
    }

    private void setOrderPush(String merchantCode, Boolean flag, Map<String, Object> map, List<Map<String, Object>> list) {
        MerchantQrcode qrcode = merchantQrcodeMapper.getByMerchantCode(merchantCode);
        if(qrcode != null){
            flag = true;
        }
        map.put(BIND_ORDER_PUSH.getCode(),flag);
        list.add(map);
    }
    private UserApp checkUserInfo(String userId) {
        UserApp userApp = userAppService.getUserAppByUserId(userId);
        MsgException.checkNull(userApp,"用户信息异常");
        return userApp;
    }
}
