package com.iformall.controller.sys;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.iformall.common.ErrorCode;
import com.iformall.common.IdWorker;
import com.iformall.common.ResultData;
import com.iformall.controller.base.BaseController;
import com.iformall.domain.po.*;
import com.iformall.enums.EnumMsgModel;
import com.iformall.enums.EnumScoreType;
import com.iformall.enums.EnumUserType;
import com.iformall.mapper.*;
import com.iformall.service.WxCreditHistoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 数据初始化
 */
@Slf4j
@RestController
@RequestMapping("sys")
public class DataInitController extends BaseController {


	@Resource
	private WxMallMapper mallMapper;
	@Resource
	private WxMsgSignatureMapper signatureMapper;
	@Resource
	private WxMsgValidationcodeModelMapper modelMapper;
	@Resource
	private WxCreditHistoryMapper creditHistoryMapper;
	@Resource
	private WxCreditHistoryService creditHistoryService;

	@Resource
	private WxCUserMapper cUserMapper;
	@Resource
	private WxCUserBasicInfoMapper cUserBasicInfoMapper;

	@Resource
	private WxCouponMapper couponMapper;

	@Resource
	private WxCouponOrderMapper couponOrderMapper;

	@Resource
	private WxMerchantBUserMapper merchantBUserMapper;

	@Resource
	private WxMerchantMapper wxMerchantMapper;


    @PostMapping("/createMsgModel")
	public ResultData createMsgModel(@RequestParam String content, @RequestParam Integer code) {
        try {
            MallUserInfo userInfo = getUser();
            if (userInfo.isFmSuperAdmin()) {
				addMsgModel(content, code);
                return new ResultData();
            }
        } catch (Exception e) {
            log.error("DataInitController::createMsgModel error ", e);
            return new ResultData(ErrorCode.MSG_METHOD_REQUEST_ERROR, e.getMessage());
        }

        return new ResultData();
    }

	@GetMapping("/init")
	public ResultData init() {
		try {
			MallUserInfo userInfo = getUser();
			if (userInfo.isFmSuperAdmin()) {
				addBirthDayMsgModel();
				return new ResultData();
			}

		} catch (Exception e) {
			log.error("DataInitController::init error ", e);
			return new ResultData(ErrorCode.MSG_METHOD_REQUEST_ERROR, e.getMessage());
		}

		return new ResultData();
	}

	/**
	 * 核销积分数据修复
	 *
	 * @return
	 */
	@GetMapping("/fixVerifyCredit")
	public ResultData fixVerifyCredit() {
		try {
			MallUserInfo userInfo = getUser();
			if(userInfo.isFmSuperAdmin()) {
				doFixVerifyCredit();
				return new ResultData();
			}
		} catch (Exception e) {
			log.error("DataInitController::fixCredit error ", e);
			return new ResultData(ErrorCode.MSG_METHOD_REQUEST_ERROR, e.getMessage());
		}

		return new ResultData();
	}

	@Transactional(rollbackFor = Exception.class)
	public void doFixVerifyCredit() {
		// 1 获取券码
		Map dateMap = new HashMap();
		dateMap.put("startDate", "2019-09-16 22:00:00");
		List<WxCouponOrder> coList = couponOrderMapper.findListOfVerifiedByDate(dateMap);
		// 2 重新计算积分，比较是否需要修复
		coList.forEach(co -> {
			WxCoupon coupon = couponMapper.selectById(co.getCouponId());

			WxMerchantBUser buUser = merchantBUserMapper.selectById(co.getBUserId());

			WxCreditHistory q = new WxCreditHistory();
			q.setTenantId(co.getTenantId());
			q.setCUserId(co.getcUserId());
			q.setMerchantId(buUser.getMerchantId());
			q.setCouponId(co.getCouponId());
			WxCreditHistory ret = null;
			try {
				ret = creditHistoryMapper.selectOne(new QueryWrapper<>(q));
			} catch (Exception e) {

			}
			if (ret != null) {
				log.debug(" : {}", ret.getId());
				return;
			}
			WxCUser cuUser = cUserMapper.selectById(co.getcUserId());
			WxCUserBasicInfo userBasicInfo = cUserBasicInfoMapper.selectById(co.getcUserId());
			//排查不存在的用户
			if (Objects.isNull(cuUser) && Objects.isNull(userBasicInfo)) {
				log.debug("用户不存在 id: {}", co.getId());
				return;
			}

			WxCreditHistory creditHistory = new WxCreditHistory();
			creditHistory.setOperatorType(EnumUserType.BUSER.getCode());
			creditHistory.setOperatorId(buUser.getId());
			creditHistory.setCUserId(co.getcUserId());
			creditHistory.setCreateDate(co.getUpdateDate());
			creditHistory.setTenantId(co.getTenantId());
			creditHistory.setCreditType(EnumScoreType.CONSUMPTION.getCode());
			creditHistory.setCouponId(coupon.getId());
			creditHistory.setBusinessId(coupon.getBusiness());
			creditHistory.setSpend(co.getCouponPrice());
			//如果券与商户一对一 则直接将消费商户更新为此商户 若一对多 则消费商户显示多商户
			creditHistory.setMerchantId(buUser.getMerchantId());
			creditHistoryService.saveOrUpdate(creditHistory);
		});
	}

    @Transactional(rollbackFor = Exception.class)
	public void addMsgModel(String context, Integer code) {
        IdWorker idWorker = IdWorker.get();
		addBirthDayMsgModelToMall(EnumMsgModel.getEnum(code), idWorker, context);
    }

	/**
	 * 增加会员生日短信模板
	 */
	@Transactional(rollbackFor = Exception.class)
	public void addBirthDayMsgModel() {
		//List<WxMsgSignature> list = signatureMapper.selectAll();
		//Map<String, String> tenantOfSignature = list.stream().collect(Collectors.toMap(WxMsgSignature::getTenantId, WxMsgSignature::getName));
		IdWorker idWorker = IdWorker.get();
		addBirthDayMsgModelToMall(EnumMsgModel.COUPON_BIRTHDAY_OPENED, idWorker, "亲到的{userName}，在您的生日到来之际，我们精心的为您准备了一份生日礼物，并在生日当天消费领取{creditScale}倍积分，赶快打开{mallName}微信小程序领取您的专属生日礼物吧！");
		addBirthDayMsgModelToMall(EnumMsgModel.COUPON_BIRTHDAY_OPENED_NO, idWorker, "亲到的{userName}，在您的生日到来之际，我们精心的为您准备了一份生日礼物，赶快打开{mallName}微信小程序领取您的专属生日礼物吧！");
	}

	private void addBirthDayMsgModelToMall(EnumMsgModel type, IdWorker idWorker, String content) {
		//查找已经添加过的接口列表
		WxMsgValidationcodeModel query = new WxMsgValidationcodeModel();
		query.setMsgType(1);
		query.setType(type.getCode());
		List<WxMsgValidationcodeModel> dbModelList = modelMapper.selectList(new QueryWrapper<>(query));
		Map<String, String> dbModelMap = dbModelList.stream().collect(Collectors.toMap(WxMsgValidationcodeModel::getTenantId, WxMsgValidationcodeModel::getName));

		List<WxMall> malls = mallMapper.findList(new WxMall());
		malls.stream().filter(wxMall -> !dbModelMap.containsKey(wxMall.getTenantId())).forEach(wxMall -> {
			addBirthDayMsgModelItem(idWorker, wxMall, type, content);
		});
	}

	private void addBirthDayMsgModelItem(IdWorker idWorker, WxMall wxMall, EnumMsgModel msgModel, String content) {
		WxMsgValidationcodeModel model = new WxMsgValidationcodeModel();
		model.setTenantId(wxMall.getTenantId());
		model.setId(idWorker.nextId());
		model.setType(msgModel.getCode());
		model.setName(msgModel.getMessage());
		model.setSignature(wxMall.getName());
		model.setContent(content);
		model.setCreatetime(new Date());
		model.setStatus(1);
		model.setMinutes(0);
		model.setOpen(0);
		model.setMsgType(1);
		model.setRoleType(3);
		modelMapper.insert(model);
	}
}
