package com.huiju.estateagents.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huiju.estateagents.common.CommConstant;
import com.huiju.estateagents.common.DateUtils;
import com.huiju.estateagents.common.StringUtils;
import com.huiju.estateagents.entity.*;
import com.huiju.estateagents.mapper.TaPersonMapper;
import com.huiju.estateagents.mapper.TaPointsRecordsMapper;
import com.huiju.estateagents.mapper.TdPointsRulesMapper;
import com.huiju.estateagents.service.ITaPointsRecordsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 积分消费流水表  服务实现类
 * </p>
 *
 * @author jobob
 * @since 2019-07-25
 */
@Service
public class TaPointsRecordsServiceImpl extends ServiceImpl<TaPointsRecordsMapper, TaPointsRecords> implements ITaPointsRecordsService {

    @Autowired
    TaPersonMapper taPersonMapper;

    @Autowired
    private TdPointsRulesMapper tdPointsRulesMapper;

    @Autowired
    private TaPointsRecordsMapper taPointsRecordsMapper;

    /**
     * 获取规则积分, 0 代表未启用
     *
     * @param code
     * @return
     */
    @Override
    public Integer getRulePoints(String code, Integer orgId) {
        QueryWrapper<TdPointsRules> tdPointsRulesQueryWrapper = new QueryWrapper<>();
        tdPointsRulesQueryWrapper.eq("code", code);
        tdPointsRulesQueryWrapper.eq("org_id", orgId);
        tdPointsRulesQueryWrapper.eq("status", CommConstant.STATUS_NORMAL);
        TdPointsRules rule = tdPointsRulesMapper.selectOne(tdPointsRulesQueryWrapper);
        if (null == rule) {
            return 0;
        }

        Integer status = rule.getStatus();
        return null != status && status.equals(CommConstant.POINTS_RULE_ON) ? rule.getPointsAmount() : 0;
    }

    private boolean isPointsRecordsExist(String personId, String changeType, String changeParams) {
        QueryWrapper<TaPointsRecords> query = new QueryWrapper<>();
        query.eq("person_id", personId)
                .eq("change_type", changeType)
                .like(!StringUtils.isEmpty(changeParams), "change_params", changeParams)
                .eq("status", CommConstant.STATUS_NORMAL);

        Integer count = taPointsRecordsMapper.selectCount(query);
        return null != count && count > 0;
    }

    @Override
    public void sharePoints(TaShare taShare, Integer orgId) {
        //
        String changeType = CommConstant.POINTS_CHANGE_SHARE_POSTER;

        // 是否开启积分规则
        Integer pointsAmount = getRulePoints(changeType, orgId);
        if (pointsAmount == 0) {
            return;
        }

        // 已经领取过的不会再次领取
        String[] params = {
                "shareId=" + String.valueOf(taShare.getShareId()),
                "openUser=" + taShare.getOpenUser().getPersonId()
        };
        String changeParams = String.join("&", params);
        boolean hasJoined = isPointsRecordsExist(taShare.getPersonId(), changeType, changeParams);
        if (hasJoined) {
            return;
        }

        // 发放积分
        TaPerson person = taPersonMapper.selectById(taShare.getPersonId());
        if (savePoints(person, changeType, changeParams, pointsAmount, orgId)) {
            taPersonMapper.setPointsIncrement(person.getPersonId(), pointsAmount);
        }
    }

    @Override
    public void sharePosterAll(String recommenderId, Integer orgId) {
        String changeType = CommConstant.POINTS_CHANGE_SHARE_POSTER;
        // 是否开启积分规则
        Integer pointsAmount = getRulePoints(changeType, orgId);
        if (pointsAmount == 0) {
            return;
        }

        String[] params = {
                "openUser=" + recommenderId
        };
        String changeParams = String.join("&", params);

        // 发放积分
        TaPerson person = taPersonMapper.selectById(recommenderId);
        if (savePoints(person, changeType, changeParams, pointsAmount, orgId)) {
            taPersonMapper.setPointsIncrement(person.getPersonId(), pointsAmount);
        }
    }

    @Override
    public void checkinPoints(TaPersonSign taPersonSign, Integer orgId) {
        //
        String changeType = CommConstant.POINTS_CHANGE_CHECKIN;

        // 是否开启积分规则
        Integer pointsAmount = getRulePoints(changeType, orgId);
        if (pointsAmount == 0) {
            return;
        }

        // 已经领取过的不会再次领取
        List<String> params = new ArrayList<String>() {{
            add("date=" + DateUtils.today());
            add("user=" + taPersonSign.getPerson().getPersonId());
        }};
        String changeParams = String.join("&", params);
        boolean hasJoined = isPointsRecordsExist(taPersonSign.getPerson().getPersonId(), changeType, changeParams);
        if (hasJoined) {
            return;
        }

        // 添加参数
        params.add("recId=" + taPersonSign.getRecId());
        changeParams = String.join("&", params);


        // 增加积分
        // 1-7 天积分 1-7, 超过7天按 7 个积分算
//		Integer durationDays = taPersonSign.getDurationDays();
//		int points = durationDays >= 7 ? 7 : durationDays;

        // 发放积分
        TaPerson person = taPersonMapper.selectById(taPersonSign.getPersonId());
        if (savePoints(person, changeType, changeParams, pointsAmount, orgId)) {
            taPersonMapper.setPointsIncrement(person.getPersonId(), pointsAmount);
        }
    }

    @Override
    public void checkinActivityPoints(TaActivityDynamicEnlist taActivityDynamicEnlist, Integer orgId) {
        String changeType = CommConstant.POINTS_CHANGE_ACTIVITY_CHECKIN;
        // 是否开启积分规则
        Integer pointsAmount = getRulePoints(changeType, orgId);
        if (pointsAmount == 0) {
            return;
        }

        // 已经领取过的不会再次领取
        List<String> params = new ArrayList<String>() {{
            add("user=" + taActivityDynamicEnlist.getPersonId());
            add("targetId=" + taActivityDynamicEnlist.getEnlistId().toString());
        }};
        String changeParams = String.join("&", params);
        boolean hasJoined = isPointsRecordsExist(taActivityDynamicEnlist.getPersonId(), changeType, changeParams);
        if (hasJoined) {
            return;
        }
        // 添加参数
        params.add("enlistId=" + taActivityDynamicEnlist.getEnlistId());
        changeParams = String.join("&", params);

        // 发放积分
        TaPerson person = taPersonMapper.selectById(taActivityDynamicEnlist.getPersonId());
        if (savePoints(person, changeType, changeParams, pointsAmount, orgId)) {
            taPersonMapper.setPointsIncrement(person.getPersonId(), pointsAmount);
        }
    }

    @Override
    public void signUpPoints(TaPerson taPerson, Integer orgId) {
        //
        String changeType = CommConstant.POINTS_CHANGE_SIGNUP_AGENT;
        // 是否开启积分规则
        Integer pointsAmount = getRulePoints(changeType, orgId);
        if (pointsAmount == 0) {
            return;
        }

        // 已经领取过的不会再次领取
        List<String> params = new ArrayList<String>() {{
            add("user=" + taPerson.getPersonId());
        }};
        String changeParams = String.join("&", params);
        boolean hasJoined = isPointsRecordsExist(taPerson.getPersonId(), changeType, changeParams);
        if (hasJoined) {
            return;
        }

        // 发放积分
        if (savePoints(taPerson, changeType, changeParams, pointsAmount, orgId)) {
            taPersonMapper.setPointsIncrement(taPerson.getPersonId(), pointsAmount);
        }
    }

    @Override
    public void recommendCustPoints(TaRecommendCustomer taRecommendCustomer, Integer orgId) {
        //
        String changeType = CommConstant.POINTS_CHANGE_RECOMMEND_CUSTOMER;

        // 是否开启积分规则
        Integer pointsAmount = getRulePoints(changeType, orgId);
        if (pointsAmount == 0) {
            return;
        }

        // 已经领取过的不会再次领取
        List<String> params = new ArrayList<String>() {{
            // 推荐人
            add("person=" + taRecommendCustomer.getRecommendPerson());
            // 推荐客户手机
            add("phone=" + taRecommendCustomer.getPhone());
        }};
        String changeParams = String.join("&", params);
        boolean hasJoined = isPointsRecordsExist(taRecommendCustomer.getRecommendPerson(), changeType, changeParams);
        if (hasJoined) {
            return;
        }

        // 发放积分
        TaPerson taPerson = taPersonMapper.getById(taRecommendCustomer.getRecommendPerson());
        if (null != taPerson && savePoints(taPerson, changeType, changeParams, pointsAmount, orgId)) {
            taPersonMapper.setPointsIncrement(taPerson.getPersonId(), pointsAmount);
        }
    }

    @Override
    public IPage<TaPointsRecords> getWxRecords(Integer pageNum, Integer pageSize, String personId) {
        IPage<TaPointsRecords> pg = new Page<>(pageNum, pageSize);
        return taPointsRecordsMapper.getCustomerPointsList(pg, personId);
    }

    @Override
    public void consumeGoodsPoints(TaGoods taGoods, Integer orgId) {
        Integer minusPoints = taGoods.getPointPrice();
        if (null == minusPoints || minusPoints <= 0) {
            return;
        }

        TaPerson taPerson = taGoods.getExchanger();
        Integer origPoints = taPerson.getPoints();
        if (null == origPoints) {
            origPoints = 0;
        }

        // 积分不足
        if (minusPoints > origPoints) {
            return;
        }

        String[] params = {
                "person=" + taPerson.getPersonId(),
                "goods=" + String.valueOf(taGoods.getGoodsId()),
                "points=" + String.valueOf(minusPoints)
        };
        String changeParams = String.join("&", params);

        // 发放积分
        Integer pointsAmount = 0 - minusPoints;
        if (savePoints(taPerson, CommConstant.POINTS_CHANGE_GOODS, changeParams, pointsAmount, orgId)) {
            taPersonMapper.setPointsIncrement(taPerson.getPersonId(), pointsAmount);
        }
    }

    private boolean savePoints(TaPerson person, String changeType, String changeParams, Integer pointsAmount, Integer orgId) {
        if (null == person) {
            return true;
        }
        TaPointsRecords taPointsRecords = new TaPointsRecords();
        taPointsRecords.setPersonId(person.getPersonId());
        taPointsRecords.setPersonName(StringUtils.ifNull(person.getName(), person.getNickname()));
        taPointsRecords.setPersonType(person.getPersonType());
        taPointsRecords.setPointsAmount(pointsAmount);
        taPointsRecords.setChangeType(changeType);
        taPointsRecords.setChangeParams(changeParams);
        taPointsRecords.setStatus(CommConstant.STATUS_NORMAL);
        taPointsRecords.setCreateDate(LocalDateTime.now());
        taPointsRecords.setOrgId(orgId);

        return taPointsRecordsMapper.insert(taPointsRecords) > 0;
    }

//	@Override
//	public void authPoints(String personId) {
//		//查看是否领取过授权积分
//		QueryWrapper<TaPointsRecords> taPointsRecordsQueryWrapper = new QueryWrapper<>();
//		taPointsRecordsQueryWrapper.eq("person_id", personId);
//		taPointsRecordsQueryWrapper.eq("change_type",CommConstant.POINTS_AUTHORIZE);
//
//		List<TaPointsRecords> taPointsRecordsList = taPointsRecordsMapper.selectList(taPointsRecordsQueryWrapper);
//		if (taPointsRecordsList.size() < 1){
//			TaPerson person = taPersonMapper.selectById(personId);
//			sendPoints(person,4,CommConstant.POINTS_AUTHORIZE);
//		}
//	}

    private void sendPoints(TaPerson person, Integer rulesId, String shareType, Integer orgId) {
        //发放积分
        QueryWrapper<TdPointsRules> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("rule_id", rulesId);
        queryWrapper.eq("status", CommConstant.STATUS_NORMAL);
        TdPointsRules tdPointsRules = tdPointsRulesMapper.selectOne(queryWrapper);
        if (null != tdPointsRules) {
            //插入积分消费流水表
            TaPointsRecords taPointsRecords = new TaPointsRecords();
            taPointsRecords.setPersonId(person.getPersonId());
            taPointsRecords.setPersonName(com.huiju.estateagents.common.StringUtils.ifNull(person.getName(), person.getNickname()));
            taPointsRecords.setPersonType(person.getPersonType());
            taPointsRecords.setPointsAmount(tdPointsRules.getPointsAmount());
            taPointsRecords.setChangeType(shareType);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("person_id", person.getPersonId());
            taPointsRecords.setChangeParams(jsonObject.toJSONString());
            taPointsRecords.setCreateDate(LocalDateTime.now());
            taPointsRecords.setStatus(CommConstant.STATUS_NORMAL);
            taPointsRecords.setOrgId(orgId);
            taPointsRecordsMapper.insert(taPointsRecords);
            //添加积分
            UpdateWrapper<TaPerson> taPersonwrapper = new UpdateWrapper<>();
            taPersonwrapper.eq("person_id", person.getPersonId());
            taPersonwrapper.setSql("points = IFNULL(points, 0) + " + String.valueOf(tdPointsRules.getPointsAmount()));
            taPersonMapper.update(new TaPerson(), taPersonwrapper);
        }
    }


    @Override
    public void documentVerify(TaDocumentVerify taDocumentVerify, Integer orgId) {
        //
        String changeType = CommConstant.POINTS_CHANGE_DOCUMENT_VERIFY;
        // 是否开启积分规则
        Integer pointsAmount = getRulePoints(changeType, orgId);
        if (pointsAmount == 0) {
            return;
        }

        // 已经领取过的不会再次领取
        String[] params = {
                "shareId=" + String.valueOf(taDocumentVerify.getDocumentVerifyId()),
                "openUser=" + taDocumentVerify.getPersonId()
        };
        String changeParams = String.join("&", params);
        boolean hasJoined = isPointsRecordsExist(taDocumentVerify.getPersonId(), changeType, changeParams);
        if (hasJoined) {
            return;
        }

        // 发放积分
        TaPerson person = taPersonMapper.selectById(taDocumentVerify.getPersonId());
        if (savePoints(person, changeType, changeParams, pointsAmount, orgId)) {
            taPersonMapper.setPointsIncrement(person.getPersonId(), pointsAmount);
        }
    }

    @Override
    public void activityVerificationSign(HelpInitiateRecord helpInitiateRecord, Integer orgId) {
        //
        String changeType = CommConstant.POINTS_CHANGE_ACTIVITY_VERIFICATION;
        // 是否开启积分规则
        Integer pointsAmount = getRulePoints(changeType, orgId);
        if (pointsAmount == 0) {
            return;
        }


        // 已经领取过的不会再次领取
        String[] params = {
                "shareId=" + String.valueOf(helpInitiateRecord.getHelpRecordInitiateId()),
                "openUser=" + helpInitiateRecord.getPersonId()
        };
        String changeParams = String.join("&", params);
        boolean hasJoined = isPointsRecordsExist(helpInitiateRecord.getPersonId(), changeType, changeParams);
        if (hasJoined) {
            return;
        }

        // 发放积分
        TaPerson person = taPersonMapper.selectById(helpInitiateRecord.getPersonId());
        if (savePoints(person, changeType, changeParams, pointsAmount, orgId)) {
            taPersonMapper.setPointsIncrement(person.getPersonId(), pointsAmount);
        }
    }

    /**
     * 消费拼团积分
     *
     * @param person
     * @param integral
     * @param buildingId
     * @param groupActivityId
     */
    @Override
    public void saveGroupRecord(TaPerson person, Integer integral, String buildingId, Integer groupActivityId) {
        TaPointsRecords taPointsRecords = new TaPointsRecords();
        taPointsRecords.setPersonId(person.getPersonId());
        taPointsRecords.setPersonName(person.getNickname());
        taPointsRecords.setPersonType(person.getPersonType());
        taPointsRecords.setPointsAmount(-integral);
        taPointsRecords.setChangeType(CommConstant.POINTS_CHANGE_GROUP);
        taPointsRecords.setChangeParams("{\"group_activity_id\":" + groupActivityId + "}");
        taPointsRecords.setCreateDate(LocalDateTime.now());
        taPointsRecords.setOrgId(person.getOrgId());
        taPointsRecords.setBuildingId(buildingId);
        taPointsRecords.setStatus(CommConstant.STATUS_NORMAL);
        taPointsRecordsMapper.insert(taPointsRecords);
    }

    @Override
    public Integer sumPointByPersonId(String personId) {
        return taPointsRecordsMapper.sumPointByPersonId(personId);
    }
}
