package cn.pluss.platform.merchantMenber.impl;

import cn.pluss.platform.activityActivate.ActivityActivateService;
import cn.pluss.platform.api.Result;
import cn.pluss.platform.api.ResultGenerator;
import cn.pluss.platform.entity.*;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.mapper.MerchantMenberMapper;
import cn.pluss.platform.mapper.PhoneValidateCodeMapper;
import cn.pluss.platform.merchantMenber.MerchantMenberService;
import cn.pluss.platform.merchantStore.MerchantStoreService;
import cn.pluss.platform.userApp.UserAppService;
import cn.pluss.platform.util.DateUtils;
import cn.pluss.platform.util.ParametersUtil;
import cn.pluss.platform.util.StringUtil;
import cn.pluss.platform.wechat.WechatService;
import cn.pluss.platform.wechat.WxConstants;
import cn.pluss.platform.wx.WxAccessTokenRequest;
import cn.pluss.platform.wx.WxCommonService;
import cn.pluss.platform.wx.WxTemolateRequest;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@RequiredArgsConstructor
@Service("merchantMenberService")
@Slf4j
public class MerchantMenberServiceImpl extends ServiceImpl<MerchantMenberMapper, MerchantMenber> implements MerchantMenberService{

    private final PhoneValidateCodeMapper phoneValidateCodeMapper;
    private final MerchantStoreService merchantStoreService;
    private final ActivityActivateService activityActivateService;
    private final WechatService wechatService;

    @Autowired
    private UserAppService userAppService;

    @Resource
    private WxCommonService wxCommonService;

    private final String default_avatar = "https://syb-resource.oss-cn-hangzhou.aliyuncs.com/微信图片_20210408103257.png?versionId=CAEQKxiBgMCllMC9xRciIDMyZDA3Y2IzNGU5YjQ5ODk5NTlhOGI5MWJjZGNhNTYw";

    @Override
    public String queryMemberIsExist(String merchantCode, String storeId, String phone, String checkCode, String nickName, String birthday) {
        PhoneValidateCode queryPhoneValidateCode = new PhoneValidateCode();

        if (StringUtils.isEmpty(checkCode)) {
            throw new MsgException("请输入验证码！");
        }

        queryPhoneValidateCode.setPhone(phone);
        List<PhoneValidateCode> phoneValidateCodes = phoneValidateCodeMapper.queryPhoneValidateCodeList(queryPhoneValidateCode);
        if (phoneValidateCodes == null || phoneValidateCodes.size() == 0) {
            throw new MsgException("请先获取验证码！");
        }

        PhoneValidateCode existValidateCode = phoneValidateCodes.get(0);
        if (!checkCode.equals(existValidateCode.getCode())) {
            throw new MsgException("验证码错误！");
        }
        // 使用验证码之后删除验证码
        phoneValidateCodeMapper.deletePhoneValidateCode(existValidateCode);

        MerchantStore ms = new MerchantStore();
        ms.setMerchantCode(merchantCode);
        MerchantStore one = merchantStoreService.getOne(new QueryWrapper<>(ms));

        String sceneStr = merchantCode + "," + one.getStoreId() + "," + phone;
        log.error(sceneStr);
        Result<String> rQcode = wechatService.getRQcode(sceneStr);

        MerchantStore merchantStore = new MerchantStore().setMerchantCode(merchantCode);
        merchantStore = merchantStoreService.getOne(new QueryWrapper<>(merchantStore).last("limit 1"));

        storeId = merchantStore.getStoreId();

        if (rQcode.getCode() == 200) {
            MerchantMenber merchantMemberExist = new MerchantMenber();
            merchantMemberExist.setStoreId(merchantStore.getStoreId());
            merchantMemberExist.setMerchantCode(merchantCode);
            merchantMemberExist.setPhone(phone);
            List<MerchantMenber> queryMerchantMenberList = queryMerchantMenberList(merchantMemberExist);
            if (queryMerchantMenberList != null && queryMerchantMenberList.size() > 0) {
                throw new MsgException("该手机号已经是会员");
            }

            MerchantMenber merchantMenber = new MerchantMenber();
            merchantMenber.setPhone(phone);
            merchantMenber.setNickName(nickName);
            merchantMenber.setStoreId(merchantStore.getStoreId());
            merchantMenber.setBirthdayDt(birthday);

            merchantMenber.setBindingUrl(rQcode.getData());
            ActivityActivate activityActivate = new ActivityActivate();
            merchantMenber.setMerchantCode(merchantStore.getMerchantCode());
            merchantMenber.setMerchantName(merchantStore.getMerchantName());
            merchantMenber.setStoreName(merchantStore.getStoreName());
            activityActivate.setStoreId(merchantStore.getStoreId());
            activityActivate.setMerchantCode(merchantStore.getMerchantCode());
            // 查询门店的激活送
            List<ActivityActivate> queryActivityActivateList = activityActivateService.queryActivityActivateList(activityActivate);
            if (queryActivityActivateList != null && queryActivityActivateList.size() > 0) {
                activityActivate = queryActivityActivateList.get(0);
                // 赠送金额
                Double giveMoney = activityActivate.getGiveMoney();
                merchantMenber.setUsableGiveFee(giveMoney);
                merchantMenber.setTotalGiveFee(giveMoney);
            }
            merchantMenber.setMemberCode("VIP" + StringUtil.getBillno());
            merchantMenber.setCardNo("VIP" + StringUtil.getBillno());
            saveMerchantMenber(merchantMenber);
        }
        return rQcode.getData();
    }

    @Override
    public String queryMemberIsExistV2(String merchantCode, String storeId, String phone, String checkCode, String nickName, String birthday) {
        UserApp tokenUa = userAppService.queryUserAppByToken();
        merchantCode = tokenUa.getMerchantCode();

        PhoneValidateCode queryPhoneValidateCode = new PhoneValidateCode();

        if (StringUtils.isEmpty(checkCode)) {
            throw new MsgException("请输入验证码！");
        }

        queryPhoneValidateCode.setPhone(phone);
        List<PhoneValidateCode> phoneValidateCodes = phoneValidateCodeMapper.queryPhoneValidateCodeList(queryPhoneValidateCode);
        if (phoneValidateCodes == null || phoneValidateCodes.size() == 0) {
            throw new MsgException("请先获取验证码！");
        }

        PhoneValidateCode existValidateCode = phoneValidateCodes.get(0);
        if (!checkCode.equals(existValidateCode.getCode())) {
            throw new MsgException("验证码错误！");
        }
        // 使用验证码之后删除验证码
        phoneValidateCodeMapper.deletePhoneValidateCode(existValidateCode);

        MerchantStore ms = new MerchantStore();
        ms.setMerchantCode(merchantCode);
        MerchantStore merchantStore = merchantStoreService.getOne(new QueryWrapper<>(ms));

        storeId = merchantStore.getStoreId();

        String sceneStr = merchantCode + "," + merchantStore.getStoreId() + "," + phone;
        log.error(sceneStr);
        Result<String> rQcode = wechatService.getNewRQcode(sceneStr);
        if (rQcode.getCode() == 200) {
            MerchantMenber merchantMenber1 = new MerchantMenber();
            merchantMenber1.setStoreId(storeId);
            merchantMenber1.setMerchantCode(merchantCode);
            merchantMenber1.setPhone(phone);
            List<MerchantMenber> queryMerchantMenberList = queryMerchantMenberList(merchantMenber1);
            if (queryMerchantMenberList != null && queryMerchantMenberList.size() > 0) {
                throw new MsgException("该手机号已经是会员");
            }
            MerchantMenber merchantMenber = new MerchantMenber();
            merchantMenber.setPhone(phone);
            merchantMenber.setNickName(nickName);
            merchantMenber.setStoreId(storeId);
            merchantMenber.setBirthdayDt(birthday);
            merchantMenber.setBindingUrl(rQcode.getData());
            ActivityActivate activityActivate = new ActivityActivate();
            merchantStore.setStoreId(merchantMenber.getStoreId());
            merchantMenber.setMerchantCode(merchantStore.getMerchantCode());
            merchantMenber.setMerchantName(merchantStore.getMerchantName());
            merchantMenber.setStoreName(merchantStore.getStoreName());
            activityActivate.setStoreId(merchantStore.getStoreId());
            activityActivate.setMerchantCode(merchantStore.getMerchantCode());
            // 查询门店的激活送
            List<ActivityActivate> queryActivityActivateList = activityActivateService.queryActivityActivateList(activityActivate);
            if (queryActivityActivateList != null && queryActivityActivateList.size() > 0) {
                activityActivate = queryActivityActivateList.get(0);
                Double giveMoney = activityActivate.getGiveMoney();// 赠送金额
                merchantMenber.setUsableGiveFee(giveMoney);
                merchantMenber.setTotalGiveFee(giveMoney);
            }
            merchantMenber.setMemberCode("VIP" + StringUtil.getBillno());
            merchantMenber.setCardNo("VIP" + StringUtil.getBillno());
            saveMerchantMenber(merchantMenber);
        }
        return rQcode.getData();
    }

    @Override
    public List<MerchantMenber> manageMerchantMenberSum(Map<String, Object> newMemberMap) {
        return baseMapper.manageMerchantMenberSum(newMemberMap);
    }


    /**
     * 小程序会员开卡
     * @return
     */
    @Override
    public Result<JSONObject> vipOpenCard(JSONObject jsonObject) {
        JSONObject result = new JSONObject();
        Integer storeId = jsonObject.getInteger("storeId");
        if (storeId == null) {
            return ResultGenerator.genFailResult("店铺ID不能为空");
        }
        String phone = jsonObject.getString("phone");
        if (StringUtil.isEmpty(phone)) {
            return ResultGenerator.genFailResult("手机号不能为空！");
        }
        String appOpenId = jsonObject.getString("appOpenId");
        if (StringUtil.isEmpty(appOpenId)) {
            return ResultGenerator.genFailResult("appId不能为空！");
        }
        String memberName = jsonObject.getString("memberName");
        String unionid = jsonObject.getString("unionid");
        String avatar = jsonObject.getString("avatar");
        if(StringUtil.isEmpty(memberName) || memberName == "undefined"){
            memberName = "收银呗会员"+StringUtil.genRandomNum(6);
        }
        if(StringUtil.isEmpty(avatar) || avatar == "undefined"){
            avatar = default_avatar;
        }
        MerchantStore store = new MerchantStore();
        store.setId(storeId);
        MerchantStore storeInfo = merchantStoreService.queryMerchantStore(store);
        if(storeInfo == null){
            return ResultGenerator.genFailResult("店铺数据不存在！");
        }
        if("2".equals(storeInfo.getStatus())){
            return ResultGenerator.genFailResult("店铺已被禁用！");
        }
        List<Map<String,Object>> lists = activityActivateService.getNewestActivityJoin(storeInfo.getStoreId());
        List<String> titleList = getTitleTips(lists);
        QueryWrapper<MerchantMenber> queryWrapper = new QueryWrapper<MerchantMenber>()
                .eq("storeId",storeInfo.getStoreId()).eq("phone",phone);
//                .eq("phone",phone);
        MerchantMenber merchantMenber = this.baseMapper.selectOne(queryWrapper);
        if(merchantMenber != null){
            return ResultGenerator.genFailResult("当前手机号在该门店已是会员，请勿重复领取",null);
        }else{
            MerchantMenber menber = new MerchantMenber();
            menber.setNickName(memberName);
            menber.setMemberName(memberName);
            menber.setStoreId(storeInfo.getStoreId());
            menber.setMerchantCode(storeInfo.getMerchantCode());
            menber.setAppOpenId(appOpenId);
            menber.setLogo(avatar);
            menber.setPhone(phone);
            menber.setStatus(1);
            menber.setUnionId(unionid);
            //merchantMenber.setBirthdayDt(birthday);
            /*MerchantStore merchantStore = new MerchantStore();
            merchantStore.setStoreId(storeId);
            merchantStore.setMerchantCode(merchantCode);
            List<MerchantStore> queryMerchantStoreList = merchantStoreService.queryMerchantStoreList(merchantStore);*/
            menber.setMerchantName(storeInfo.getMerchantName());
            menber.setStoreName(storeInfo.getStoreName());
            //merchantMenber.setBindingUrl(rQcode.getData());
            ActivityActivate activityActivate = new ActivityActivate();
            //storeInfo.setStoreId(merchantMenber.getStoreId());
            menber.setMerchantCode(storeInfo.getMerchantCode());
            menber.setMerchantName(storeInfo.getMerchantName());
            menber.setStoreName(storeInfo.getStoreName());
            activityActivate.setStoreId(storeInfo.getStoreId());
            activityActivate.setMerchantCode(storeInfo.getMerchantCode());
            List<ActivityActivate> queryActivityActivateList = activityActivateService.queryActivityActivateList(activityActivate);// 查询门店的激活送
            if (queryActivityActivateList != null && queryActivityActivateList.size() > 0) {
                activityActivate = queryActivityActivateList.get(0);
                Double giveMoney = activityActivate.getGiveMoney();// 赠送金额
                menber.setUsableGiveFee(giveMoney);
                menber.setTotalGiveFee(giveMoney);
            }else{
                menber.setUsableGiveFee(0.00);
                menber.setTotalGiveFee(0.00);
            }
            menber.setMemberCode("VIP" + StringUtil.getBillno());
            menber.setCardNo("VIP" + StringUtil.getBillno());
            saveMerchantMenber(menber);
            result.put("title",titleList);
            Double useRechFee = menber.getUsableRechargeFee() == null ? 0.00 : menber.getUsableRechargeFee();
            Double useGiveFee = menber.getUsableGiveFee() == null ? 0.00 : menber.getUsableGiveFee();
            BigDecimal useAmt = new BigDecimal(String.valueOf(useRechFee)).add(new BigDecimal(String.valueOf(useGiveFee)));
            result.put("useAmt",useAmt);
            result.put("cardNo",menber.getCardNo());
            return ResultGenerator.genSuccessResult("开卡成功",result);
        }
    }
    @Override
    public List<String> getTitleTips(List<Map<String, Object>> lists) {
        List<String> titleList = new ArrayList<>();
        Date nowDate = new Date();
        String title = "推荐充值再支付，立享更多优惠";
        if(lists.isEmpty()){
            titleList.add(title);
        }else{
            for (Map<String,Object> map:lists) {
                Long type = (Long)map.get("type");
                if(type == 1){
                    title = "激活送"+map.get("giveMoney")+"元";
                }else if(type == 2){
                    Long timeType = (Long) map.get("timeType");
                    if(timeType == 1){
                        Date startDt = (Date) map.get("startDt");
                        Date endDt = (Date) map.get("endDt");
                        if(nowDate.compareTo(startDt) < 0 || nowDate.compareTo(endDt) > 0){
                            continue;
                        }
                    }
                    Long reType = (Long)map.get("reType");
                    if(reType == 2){
                        Double percent = (Double)map.get("percent");
                        title = "会员返任意金额的"+percent+"%";
                    }else{
                        title = "消费满"+map.get("rechargeMoney")+"元返"+map.get("giveMoney")+"元";
                    }
                }else if(type == 3){
                    title = "充值满"+map.get("rechargeMoney")+"元送"+map.get("giveMoney")+"元";
                }
                titleList.add(title);
            }
        }
        return titleList;
    }

    /**
     * 关联分页查询
     * @param page
     * @param menber
     * @return
     */
    @Override
    public Page<MerchantMenber> pageJoinData(Page<MerchantMenber> page, MerchantMenber menber) {
        return baseMapper.pageJoinData(page,menber);
    }

    /**
     * 根据unionId 修改openid
     * @date: 2021/12/9 17:59
     * @param openid
     * @param unionId
     */
    @Override
    public void updateByUnionId(String openid,String unionId) {
        baseMapper.updateByUnionId(openid,unionId);
    }

    /**
     * 发送会员余额变动通知
     * @date: 2021/12/9 18:44
     * @param menber:
     * @param amt:
     * @param type: 1：充值 2：消费
     */
    @Override
    public void sendMenberBalanceChangeNotice(MerchantMenber menber, Double amt, String type) {
        MerchantStore store = merchantStoreService.getStoreByMerchantCode(menber.getMerchantCode());
        if(store != null && StringUtil.isNotEmpty(menber.getOpenid())){
            JSONObject miniprogram = new JSONObject();
            miniprogram.put("appid", ParametersUtil.APPLETS_APPID);
            miniprogram.put("pagepath","pages/card/index?storeId="+store.getId()+"&phone="+menber.getPhone());

            String first = "您的【"+store.getStoreName()+"】会员卡："+menber.getCardNo()+"资金有变动啦，请注意查收!";
            String remark = "如对此会员卡余额变动有疑问，可以点此进入小程序中查看！";
            String transTitle = "1".equals(type) ? "会员充值" :  "2".equals(type) ? "会员消费" :"现金充值";
            String useFee = BigDecimal.valueOf(menber.getUsableRechargeFee() + menber.getUsableGiveFee()).setScale(2,BigDecimal.ROUND_HALF_DOWN).toString();
            String[] array = {transTitle,amt.toString(), DateUtils.toString(new Date(),"yyyy-MM-dd HH:mm:ss"),useFee};
            WxAccessTokenRequest request = WxAccessTokenRequest.buidWxToken(ParametersUtil.APPID, ParametersUtil.APPSECRET, null, WxConstants.ACCESS_TOKEN_URL);
            WxTemolateRequest temolateRequest = new WxTemolateRequest(menber.getOpenid(),WxConstants.VIP_BALANCE_CHANGE_TEMPLATE_ID,null,miniprogram)
                    .buildData(first,remark,array);
            wxCommonService.sendTemplateMsg(temolateRequest,request);
        }
    }

    /**
     * 根据会员卡号获取会员信息
     * @param cardNo
     * @return
     */
    @Override
    public MerchantMenber getByCardNo(String cardNo) {
        return baseMapper.getByCardNo(cardNo);
    }
}

