package com.org.hktshop.service.user.impl;

import com.org.hktshop.base.BaseService;
import com.org.hktshop.base.UserContext;
import com.org.hktshop.constant.CommonConstant;
import com.org.hktshop.dto.HktUsersScoreSearchDto;
import com.org.hktshop.dto.PageQueryDto;
import com.org.hktshop.entity.Page;
import com.org.hktshop.entity.user.HktUser;
import com.org.hktshop.entity.user.HktUsersScore;
import com.org.hktshop.service.user.HktUserService;
import com.org.hktshop.service.user.HktUsersScoreService;
import com.org.hktshop.utils.DateUtil;
import com.org.hktshop.utils.ExecSqlLib;
import com.org.hktshop.utils.MathUtil;
import com.org.hktshop.utils.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@Service
public class HktUsersScoreServiceImpl extends BaseService<HktUsersScore> implements HktUsersScoreService {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private HktUserService hktUserService;

    Integer L2Max = 2000;
    Integer L3Max = 8000;
    Integer L4Max = 20000;
    Integer L5Max = 100000;

    @Override
    public String getUpLevelStr(HktUser user) {
        try {
            Object l = null;
            double min = 0;
            switch (user.getLevel()) {
                case 1:
                    user.setLevelRemark("下单后可升级");
                    break;
                case 2: {
                    l = MathUtil.addInt(L2Max, (-1) * user.getEmpiricalPoint());
                    min = (double) user.getEmpiricalPoint() / L2Max;
                }
                break;
                case 3: {
                    l = MathUtil.addInt(L3Max, (-1) * user.getEmpiricalPoint());
                    min = (double) (user.getEmpiricalPoint() - L2Max) / (L3Max - L2Max);
                }
                break;
                case 4: {
                    l = MathUtil.addInt(L4Max, (-1) * user.getEmpiricalPoint());
                    min = (double) (user.getEmpiricalPoint() - L3Max) / (L4Max - L3Max);
                }
                break;
                case 5: {
                    l = MathUtil.addInt(L5Max, (-1) * user.getEmpiricalPoint());
                    min = (double) (user.getEmpiricalPoint() - L4Max) / (L5Max - L4Max);
                }
                break;
                case 6:
                    user.setLevelRemark("用户已是最高等级");
                    break;
            }
            if (l != null) {
                user.setLevelRemark("还差" + l + "经验值即可升级");
            }
            user.setLevelMin(min);
        } catch (Exception ex) {
            logger.error(ex.toString());
        }
        return "";
    }


    private String addScore(String userid, int ftype, String remark, int addscore, int allscore) {
        HktUsersScore score = new HktUsersScore();
        score.setUserId(userid);
        score.setAlterType(ftype);
        score.setScoreChange(addscore);
        score.setRemark(remark);
        score.setOperationTime(DateUtil.getDateTime());
        score.setTotalScore(allscore);

        return ExecSqlLib.GetInsertSql(score);
    }

    /****
     * 修改用户积分
     * @param hktUser
     * @param type  1 积分消费  2 购物消费 3 日常签到 4 完善账户信息
     * @param addScore 添加积分数
     */
    @Override
    public void AddUserScore(HktUser hktUser, Integer type, int addScore) {
        try {
            List<String> sqls = new ArrayList<>();

            String remark = "";
            switch (type) {
                case 1:
                    remark = "积分消费";
                    break;
                case 2:
                    remark = "购物消费";
                    break;
                case 3:
                    remark = "日常签到";
                    break;
                case 4:
                    remark = "完善账户信息";
                    break;
                case 5:
                    remark = "卡卷兑换";
                    break;
            }
            hktUser.setTotalPoint(MathUtil.addInt(hktUser.getTotalPoint(), addScore));
            sqls.add(addScore(hktUser.getId(), type, remark, addScore, hktUser.getTotalPoint()));

            Integer count = this.baseJdbcDao.selectCount("select count(1) as count " +
                    "from hkt_users_score where user_id = '" + hktUser.getId() + "' and alter_type = 3 and  date_format(operation_time, '%Y-%m') = DATE_FORMAT(now(), '%Y-%m')");

            count = count + 1;
            if(type == 3 && count == 7){
                int scoreChange = 200;
                hktUser.setTotalPoint(MathUtil.addInt(hktUser.getTotalPoint(), scoreChange));
                sqls.add(addScore(hktUser.getId(), type, "本月签到7天", scoreChange, hktUser.getTotalPoint()));
            }

            if(type == 2 && addScore != 0){
                hktUser.setEmpiricalPoint(hktUser.getEmpiricalPoint()+addScore);
                hktUser.setTotalPoint(MathUtil.addInt(hktUser.getTotalPoint(), addScore));
                if(addScore >=0){
                    sqls.add(addScore(hktUser.getId(), type, "购物消费", addScore, hktUser.getTotalPoint()));
                }else {
                    sqls.add(addScore(hktUser.getId(), type, "退款消费", addScore, hktUser.getTotalPoint()));
                }
                if(hktUser.getEmpiricalPoint() >=L5Max ){
                    hktUser.setLevel(5);
                }else if(hktUser.getEmpiricalPoint() >=L4Max ){
                    hktUser.setLevel(4);
                }else if(hktUser.getEmpiricalPoint() >=L3Max ){
                    hktUser.setLevel(3);
                }else if(hktUser.getEmpiricalPoint() >=L2Max ){
                    hktUser.setLevel(2);
                }else{
                    hktUser.setLevel(1);
                }
            }

           /* if(type == 5 && addScore != 0){
                hktUser.setEmpiricalPoint(hktUser.getEmpiricalPoint()+addScore);
                hktUser.setTotalPoint(MathUtil.addInt(hktUser.getTotalPoint(), addScore));

                sqls.add(addScore(hktUser.getId(), type, "卡卷兑换", addScore, hktUser.getTotalPoint()));

                if(hktUser.getEmpiricalPoint() >=L5Max ){
                    hktUser.setLevel(5);
                }else if(hktUser.getEmpiricalPoint() >=L4Max ){
                    hktUser.setLevel(4);
                }else if(hktUser.getEmpiricalPoint() >=L3Max ){
                    hktUser.setLevel(3);
                }else if(hktUser.getEmpiricalPoint() >=L2Max ){
                    hktUser.setLevel(2);
                }else{
                    hktUser.setLevel(1);
                }
            }*/
           /* switch (hktUser.getLevel()) {
                case 1://青铜会员
                    switch (type) {
                        case 3: {
                            if (count == 10) {
                                int ScoreChange = 10;
                                hktUser.setTotalPoint(MathUtil.addInt(hktUser.getTotalPoint(), ScoreChange));
                                sqls.add(AddScore(hktUser.getId(), type, "本月签到10天", ScoreChange, hktUser.getTotalPoint()));
                            }
                        }
                        break;
                        case 2: {
                            if (addScore > 0) {
                                hktUser.setLevel(2);
                                int ScoreChange = 100;
                                hktUser.setTotalPoint(MathUtil.addInt(hktUser.getTotalPoint(), ScoreChange));
                                sqls.add(AddScore(hktUser.getId(), type, "等级升级", ScoreChange, hktUser.getTotalPoint()));
                            }
                        }
                        break;
                    }
                    break;
                case 2://黄金会员
                    switch (type) {
                        case 3: {
                            if (count == 10) {
                                int ScoreChange = 100;
                                hktUser.setTotalPoint(MathUtil.addInt(hktUser.getTotalPoint(), ScoreChange));
                                sqls.add(AddScore(hktUser.getId(), type, "本月签到10天", ScoreChange, hktUser.getTotalPoint()));
                            }
                        }
                        break;
                        case 2: {
                            if (hktUser.getTotalPoint() > 2000) {
                                hktUser.setLevel(3);
                                int ScoreChange = 200;
                                hktUser.setTotalPoint(MathUtil.addInt(hktUser.getTotalPoint(), ScoreChange));
                                sqls.add(AddScore(hktUser.getId(), type, "等级升级", ScoreChange, hktUser.getTotalPoint()));
                            }
                        }
                        break;
                    }
                    break;
                case 3://铂金会员
                    switch (type) {
                        case 3: {
                            if (count == 15) {
                                int ScoreChange = 500;
                                hktUser.setTotalPoint(MathUtil.addInt(hktUser.getTotalPoint(), ScoreChange));
                                sqls.add(AddScore(hktUser.getId(), type, "本月签到15天", ScoreChange, hktUser.getTotalPoint()));
                            }
                        }
                        break;
                        case 2: {
                            if (hktUser.getTotalPoint() > 8000) {
                                hktUser.setLevel(4);
                                int ScoreChange = 1000;
                                hktUser.setTotalPoint(MathUtil.addInt(hktUser.getTotalPoint(), ScoreChange));
                                sqls.add(AddScore(hktUser.getId(), type, "等级升级", ScoreChange, hktUser.getTotalPoint()));
                            }
                        }
                        break;
                    }
                    break;
                case 4://钻石会员
                    switch (type) {
                        case 3: {
                            if (count == 15) {
                                int ScoreChange = 1000;
                                hktUser.setTotalPoint(MathUtil.addInt(hktUser.getTotalPoint(), ScoreChange));
                                sqls.add(AddScore(hktUser.getId(), type, "本月签到15天", ScoreChange, hktUser.getTotalPoint()));
                            }
                        }
                        break;
                        case 2: {
                            if (hktUser.getTotalPoint() > 20000) {
                                hktUser.setLevel(5);
                                int ScoreChange = 1000;
                                hktUser.setTotalPoint(MathUtil.addInt(hktUser.getTotalPoint(), ScoreChange));
                                sqls.add(AddScore(hktUser.getId(), type, "等级升级", ScoreChange, hktUser.getTotalPoint()));
                            }
                        }
                        break;
                    }
                    break;
                case 5://星耀会员
                    switch (type) {
                        case 3: {
                            if (count == 15) {
                                int ScoreChange = 1500;
                                hktUser.setTotalPoint(MathUtil.addInt(hktUser.getTotalPoint(), ScoreChange));
                                sqls.add(AddScore(hktUser.getId(), type, "本月签到15天", ScoreChange, hktUser.getTotalPoint()));
                            }
                        }
                        break;
                        case 2: {
                            if (hktUser.getTotalPoint() > 100000) {
                                hktUser.setLevel(6);
                                int ScoreChange = 1000;
                                hktUser.setTotalPoint(MathUtil.addInt(hktUser.getTotalPoint(), ScoreChange));
                                sqls.add(AddScore(hktUser.getId(), type, "等级升级", ScoreChange, hktUser.getTotalPoint()));
                            }
                        }
                        break;
                    }
                    break;
                case 6://皇冠会员
                    switch (type) {
                        case 3: {
                            if (count == 15) {
                                int ScoreChange = 2000;
                                hktUser.setTotalPoint(MathUtil.addInt(hktUser.getTotalPoint(), ScoreChange));
                                sqls.add(AddScore(hktUser.getId(), type, "本月签到15天", ScoreChange, hktUser.getTotalPoint()));
                            }
                        }
                    }
                    break;
            }*/
            if (sqls.size() > 0) {
                sqls.add(ExecSqlLib.GetUpdateSql(hktUser));
                this.baseJdbcDao.executeTransaction(sqls);
                HktUser hktUser1 = new HktUser();
                hktUser1.setId(hktUser.getId());
                HktUser hktUser2 = hktUserService.queryUser(hktUser1);
                HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
                String header = request.getHeader("access-token");
                if(com.org.hktshop.utils.StringUtils.isNull(header)){
                    redisUtil.set(CommonConstant.HKT_SHOP_USER+hktUser2.getMobile(),hktUser2);
                }else {
                    redisUtil.set(CommonConstant.HKT_SHOP_USER+header,hktUser2);
                }
            }
        } catch (Exception ex) {
            logger.error("用户积分: user = {}  type={} score={}", hktUser.getId(), type, addScore);
        }
    }

    @Override
    public Page<HktUsersScore> getHktUsersScore(PageQueryDto<HktUsersScoreSearchDto> pageQueryDto, HktUser hktUser) {
        HktUsersScoreSearchDto pageQueryDtoData = pageQueryDto.getData();
        if (pageQueryDtoData.getAlterType() == 0) {
            pageQueryDtoData.setAlterType(null);
        }
        StringBuffer sql = new StringBuffer();

        sql.append("select user_id as userId,operation_time as operationTime,alter_type as alterType,score_change as scoreChange," +
                "total_score as totalScore,remark as remark,id as id from hkt_users_score where user_id='" + hktUser.getId() + "' ");
        if (!StringUtils.isEmpty(pageQueryDtoData.getStartTime())) {
            sql.append(" and operation_time>'" + pageQueryDtoData.getStartTime().trim() + "'");
        }
        if (!StringUtils.isEmpty(pageQueryDtoData.getEndTime())) {
            String addOneDay = DateUtil.addOneDay(pageQueryDtoData.getEndTime());
            sql.append(" and operation_time<='" + addOneDay + "'");
        }
        if (!StringUtils.isEmpty(pageQueryDtoData.getAlterType())) {
            sql.append(" and alter_type=" + pageQueryDtoData.getAlterType());
        }
        sql.append(" order by operation_time DESC");
        HktUsersScore score = new HktUsersScore();
        score.setPageNum(pageQueryDto.getPageNum());
        score.setPageSize(pageQueryDto.getPageSize());
        Page<HktUsersScore> page = baseJdbcDao.queryPage(sql.toString(), score);
        return page;
    }
}
