package cn.iocoder.yudao.module.shop.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.shop.entity.ShopUserCar;
import cn.iocoder.yudao.module.shop.service.IShopUserCarService;
import cn.iocoder.yudao.module.system.dal.dataobject.permission.RoleDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.service.permission.PermissionService;
import cn.iocoder.yudao.module.system.service.permission.RoleService;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import cn.iocoder.yudao.util.WechatPayConfig;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.iocoder.yudao.util.DateUtils;
import cn.iocoder.yudao.module.contract.service.IInspectionContractService;
import cn.iocoder.yudao.module.inspection.entity.ShopInspectionGoods;
import cn.iocoder.yudao.module.inspection.service.AppInspectionGoodsService;
import cn.iocoder.yudao.module.shop.entity.ShopCoupon;
import cn.iocoder.yudao.module.shop.entity.ShopCouponTemplate;
import cn.iocoder.yudao.module.shop.mapper.ShopCouponMapper;
import cn.iocoder.yudao.module.shop.service.IShopCouponService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.module.appBase.config.WxMessageTemplate.YHJ_MESSAGE;
import static cn.iocoder.yudao.module.appBase.utils.WxUtil.sendCommonSubscribeMessage;

/**
 * 优惠券Service业务层处理
 *
 * @author ruoyi
 * @date 2023-07-31
 */
@Service
@Slf4j
public class ShopCouponServiceImpl extends ServiceImpl<ShopCouponMapper,ShopCoupon> implements IShopCouponService
{
    @Autowired
    private AdminUserService userService;
    @Resource
    private WechatPayConfig wechatPayConfig;
    @Autowired
    private AppInspectionGoodsService appInspectionGoodsService;
    @Autowired
    private IShopUserCarService shopUserCarService;
    @Autowired
    private IInspectionContractService contractService;
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private RoleService roleService;

    /**
     * 查询优惠券
     *
     * @param couponId 优惠券主键
     * @return 优惠券
     */
    @Override
    public ShopCoupon selectShopCouponByCouponId(Long couponId)
    {
        return baseMapper.selectShopCouponByCouponId(couponId);
    }

    /**
     * 查询优惠券列表
     *
     * @param shopCoupon 优惠券
     * @return 优惠券
     */
    @Override
    public IPage<ShopCoupon> selectShopCouponList(Page<ShopCoupon> page, ShopCoupon shopCoupon)
    {
        return baseMapper.selectShopCouponList(page,shopCoupon);
    }

    /**
     * 新增优惠券
     *
     * @param shopCoupon 优惠券
     * @return 结果
     */
    @Override
    public int insertShopCoupon(ShopCoupon shopCoupon)
    {
        // 生成code 8位UUID和当前日期时间毫秒的字符串
        String uuid = UUID.randomUUID().toString().substring(0, 8);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String formattedDateTime = LocalDateTime.now().format(formatter);
        String result =  formattedDateTime + uuid;

        shopCoupon.setCouponCode(result);
        shopCoupon.setCouponStatus("0");
        int i = baseMapper.insertShopCoupon(shopCoupon);
        try {
            AdminUserDO user = userService.getUser(shopCoupon.getUserId());
            Map<String,Object> params= new HashMap<>();
            params.put("appId",wechatPayConfig.getAppId());
            params.put("appSecret",wechatPayConfig.getAppSecret());
            params.put("touser",user.getJcOpenId());
            params.put("template_id",YHJ_MESSAGE);
            JSONObject data =new JSONObject();

            JSONObject value = new JSONObject();
            value.put("value", shopCoupon.getTitle());
            data.put("thing2",value);

            value = new JSONObject();
            value.put("value", DateUtil.format(shopCoupon.getStartTime(),"yyyy-MM-dd HH:mm:ss"));
            data.put("time5",value);

            value = new JSONObject();
            value.put("value", DateUtil.format(shopCoupon.getExpirationTime(),"yyyy-MM-dd HH:mm:ss"));
            data.put("time6",value);

            if (null==shopCoupon.getDiscount()){
                value = new JSONObject();
                value.put("value", 999+"元");
                data.put("amount8",value);
            }else{
                value = new JSONObject();
                value.put("value", BigDecimal.valueOf(shopCoupon.getDiscount()*1d/100).setScale(2)+"元");
                data.put("amount8",value);
            }

            if (shopCoupon.getCouponType().equals("cash")){
                value = new JSONObject();
                value.put("value", "现金券");
                data.put("phrase10",value);
            }else if (shopCoupon.getCouponType().equals("offset")){
                value = new JSONObject();
                value.put("value", "抵扣券");
                data.put("phrase10",value);
            }
            //订阅消息
            JSONObject jsonObject = sendCommonSubscribeMessage(params, data);
            if (jsonObject.containsKey("errcode")){
                if (jsonObject.getInteger("errcode")!=0){
                    //订阅消息发送失败，发送短息通知

                }
            }

        }catch (Exception e){
            log.error(e.getMessage());
        }

        return i;
    }

    /**
     * 修改优惠券
     *
     * @param shopCoupon 优惠券
     * @return 结果
     */
    @Override
    public int updateShopCoupon(ShopCoupon shopCoupon)
    {
        shopCoupon.setUpdateTime(DateUtils.getNowDate());
        return baseMapper.updateShopCoupon(shopCoupon);
    }
    @Override
    public int hfStatus(ShopCoupon shopCoupon)
    {
        shopCoupon.setUpdateTime(DateUtils.getNowDate());
        return baseMapper.hfStatus(shopCoupon);
    }

    /**
     * 批量删除优惠券
     *
     * @param couponIds 需要删除的优惠券主键
     * @return 结果
     */
    @Override
    public int deleteShopCouponByCouponIds(Long[] couponIds)
    {
        return baseMapper.deleteShopCouponByCouponIds(couponIds);
    }

    /**
     * 删除优惠券信息
     *
     * @param couponId 优惠券主键
     * @return 结果
     */
    @Override
    public int deleteShopCouponByCouponId(Long couponId)
    {
        return baseMapper.deleteShopCouponByCouponId(couponId);
    }
    /* 我的优惠券 */
    @Override
    public IPage<ShopCoupon> selectShopCouponByUserId(Page<ShopCoupon> page, ShopCoupon shopCoupon){
        return baseMapper.selectShopCouponByUserId(page,shopCoupon);
    };

    /* 可用优惠券 */
    @Override
    public IPage<ShopCoupon> availableCouponsListByUserId(Page<ShopCoupon> page, ShopCoupon shopCoupon){
        return baseMapper.availableCouponsListByUserId(page,shopCoupon);
    };
    /* 不可用优惠券 */
    @Override
    public IPage<ShopCoupon> unAvailableCouponsListByUserId(Page<ShopCoupon> page, ShopCoupon shopCoupon){
        return baseMapper.unAvailableCouponsListByUserId(page,shopCoupon);
    };

    @Override
    public int getOffsetCouponCount(Long userId, Long goodId){
        return baseMapper.getOffsetCouponCount(userId,goodId);
    };

    public List<ShopCoupon> getQxCouponList(Long userId, Long goodId){
        return baseMapper.getQxCouponList(userId,goodId);
    };
    public List<ShopCoupon> unGetQxCouponList(Long userId, Long goodId){
        return baseMapper.unGetQxCouponList(userId,goodId);
    }


    //获取当前用户可用的优惠券
    @Override
    public List<ShopCoupon> canUseCoupon(Integer goodsId, String bindMoudle) {
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        ShopInspectionGoods goods = appInspectionGoodsService.getById(goodsId);
        String goodsIdStr = goodsId.toString();
        return baseMapper.canUseCoupon(userId,  goods.getPartnerId(),  goodsIdStr,  bindMoudle);
    }

    @Override
    public Integer canUseCouponCount(Integer goodsId, String bindMoudle) {
        ShopInspectionGoods goods = appInspectionGoodsService.getById(goodsId);
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        String goodsIdStr = "'"+goodsId+"'";
        return baseMapper.canUseCouponCount(userId,  goods.getPartnerId(),  goodsIdStr,  bindMoudle);
    };

    @Override
    public List<ShopCouponTemplate> canLedCoupon(Long partnerId) {
        LoginUser user = SecurityFrameworkUtils.getLoginUser();
        Set<Long> userRoleIdListByUserId = permissionService.getUserRoleIdListByUserId(user.getId());
        List<RoleDO> roleList = roleService.getRoleList(userRoleIdListByUserId);
        List<String> roleKeys = roleList.stream().map(RoleDO::getCode).collect(Collectors.toList());
        if (roleKeys.contains("jcdb")){
            //如果是代办
            //再追加近十天的委托授权
            List<ShopCouponTemplate> couponWtrTemplates = baseMapper.canLedCouponWtr(partnerId, user.getId(),"jcdb");
            return  couponWtrTemplates;

        }else if(roleKeys.contains("jcdwgly")){
            //检测单位管理员

            List<ShopCouponTemplate> shopCouponTemplates = baseMapper.canLedCoupon(partnerId, user.getId(),"jcdwgly");
            if (CollectionUtil.isEmpty(shopCouponTemplates)){
                shopCouponTemplates =    new ArrayList<>();
            }
            return  shopCouponTemplates;

        }else{
            //普通用户
            List<ShopUserCar> shopUserCars = shopUserCarService.selectUserCarsByUserId(user.getId());
            if (CollectionUtil.isEmpty(shopUserCars)){
                return new ArrayList<>();
            }
            List<ShopCouponTemplate> shopCouponTemplates = baseMapper.canLedCoupon(partnerId, user.getId(),"jcyh");
            if (CollectionUtil.isNotEmpty(shopCouponTemplates)){
                return shopCouponTemplates;
            }else {
                return new ArrayList<>();
            }
        }

    }
    @Override
    public void drawDownCoupon(Long partnerId){
        LoginUser user = SecurityFrameworkUtils.getLoginUser();
        AdminUserDO user1 = userService.getUser(user.getId());
        Set<Long> userRoleIdListByUserId = permissionService.getUserRoleIdListByUserId(user.getId());
        List<RoleDO> roleList = roleService.getRoleList(userRoleIdListByUserId);
        List<String> roleKeys = roleList.stream().map(RoleDO::getCode).collect(Collectors.toList());
        if (roleKeys.contains("jcdb")){
            //如果是代办
            //整委托授权的
            List<ShopCouponTemplate> shopCouponTemplates2 = baseMapper.canLedCouponWtrResult(partnerId,user.getId(),"jcdb");
            if (CollectionUtil.isNotEmpty(shopCouponTemplates2)){
                List<ShopCoupon> coupons =new ArrayList<>();
                for (ShopCouponTemplate shopCouponTemplate : shopCouponTemplates2) {
                    ShopCoupon temp = new ShopCoupon();
                    BeanUtils.copyProperties(shopCouponTemplate, temp);
                    temp.setUserId(user.getId());
                    temp.setPartnerId(shopCouponTemplate.getBindPartnerId());
                    temp.setTemplateId(shopCouponTemplate.getId());
                    temp.setPhonenumber(user1.getMobile());
                    temp.setAllPlatform("0");
                    temp.setCouponStatus("0");
                    if (ObjectUtil.isEmpty(temp.getStartTime()) && null != shopCouponTemplate.getEffectiveDay()) {
                        temp.setStartTime(new Date());
                        temp.setExpirationTime(subtractTime(new Date(), shopCouponTemplate.getEffectiveDay()));
                    }
                    temp.setCarNum(temp.getCarNum());
                    // 生成code 8位UUID和当前日期时间毫秒的字符串
                    String uuid = UUID.randomUUID().toString().substring(0, 8);
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
                    String formattedDateTime = LocalDateTime.now().format(formatter);
                    String result =  formattedDateTime + uuid;
                    temp.setCouponCode(result);
                    coupons.add(temp);
                }
                this.saveBatch(coupons);
            }

        }else if(roleKeys.contains("jcdwgly")){
            List<ShopCouponTemplate> shopCouponTemplates = baseMapper.canLedCouponResult(partnerId,user.getId(),"jcdwgly");
            if (CollectionUtil.isEmpty(shopCouponTemplates)){
                return;
            }
            List<ShopCoupon> coupons =new ArrayList<>();
            for (ShopCouponTemplate shopCouponTemplate : shopCouponTemplates) {
                ShopCoupon temp = new ShopCoupon();
                BeanUtils.copyProperties(shopCouponTemplate, temp);
                temp.setUserId(user.getId());
                temp.setPartnerId(shopCouponTemplate.getBindPartnerId());
                temp.setTemplateId(shopCouponTemplate.getId());
                temp.setPhonenumber(user1.getMobile());
                temp.setAllPlatform("0");
                temp.setCouponStatus("0");
                if (ObjectUtil.isEmpty(temp.getStartTime()) && null != shopCouponTemplate.getEffectiveDay()) {
                    temp.setStartTime(new Date());
                    temp.setExpirationTime(subtractTime(new Date(), shopCouponTemplate.getEffectiveDay()));
                }
                temp.setCarNum(temp.getCarNum());
                // 生成code 8位UUID和当前日期时间毫秒的字符串
                String uuid = UUID.randomUUID().toString().substring(0, 8);
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
                String formattedDateTime = LocalDateTime.now().format(formatter);
                String result =  formattedDateTime + uuid;
                temp.setCouponCode(result);
                coupons.add(temp);
            }
            this.saveBatch(coupons);

        } else {
            List<ShopCouponTemplate> shopCouponTemplates = baseMapper.canLedCouponResult(partnerId,user.getId(),"jcyh");
            if (CollectionUtil.isEmpty(shopCouponTemplates)){
                return;
            }
            List<ShopCoupon> coupons =new ArrayList<>();
                for (ShopCouponTemplate shopCouponTemplate : shopCouponTemplates) {
                    ShopCoupon temp = new ShopCoupon();
                    BeanUtils.copyProperties(shopCouponTemplate, temp);
                    temp.setUserId(user.getId());
                    temp.setPartnerId(shopCouponTemplate.getBindPartnerId());
                    temp.setTemplateId(shopCouponTemplate.getId());
                    temp.setPhonenumber(user1.getMobile());
                    temp.setAllPlatform("0");
                    temp.setCouponStatus("0");
                    if (ObjectUtil.isEmpty(temp.getStartTime()) && null != shopCouponTemplate.getEffectiveDay()) {
                        temp.setStartTime(new Date());
                        temp.setExpirationTime(subtractTime(new Date(), shopCouponTemplate.getEffectiveDay()));
                    }
                    temp.setCarNum(temp.getCarNum());
                    // 生成code 8位UUID和当前日期时间毫秒的字符串
                    String uuid = UUID.randomUUID().toString().substring(0, 8);
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
                    String formattedDateTime = LocalDateTime.now().format(formatter);
                    String result =  formattedDateTime + uuid;
                    temp.setCouponCode(result);
                    coupons.add(temp);
                }
            this.saveBatch(coupons);
        }

    }

    @Override
    public List<ShopCouponTemplate> canLedCouponPlatform() {
        LoginUser user = SecurityFrameworkUtils.getLoginUser();
        Set<Long> userRoleIdListByUserId = permissionService.getUserRoleIdListByUserId(user.getId());
        List<RoleDO> roleList = roleService.getRoleList(userRoleIdListByUserId);
        List<String> roleKeys = roleList.stream().map(RoleDO::getCode).collect(Collectors.toList());
        List<ShopCouponTemplate> couponWtrTemplates = new ArrayList<>();
        if (roleKeys.contains("jcdb")){
            //如果是代办
            //再追加近十天的委托授权
            couponWtrTemplates = baseMapper.canLedCouponPlatform(user.getId(),"jcdb");

        }else if(roleKeys.contains("jcdwgly")){
            //检测单位管理员

            couponWtrTemplates = baseMapper.canLedCouponPlatform(user.getId(),"jcdwgly");

        }else{
            //普通用户
            couponWtrTemplates = baseMapper.canLedCouponPlatform(user.getId(),"jcyh");

        }
        if (CollectionUtil.isEmpty(couponWtrTemplates)){
            couponWtrTemplates =new ArrayList<>();
        }
        return  couponWtrTemplates;
    }

    @Override
    public void drawDownCouponPlatform() {
        LoginUser user = SecurityFrameworkUtils.getLoginUser();
        AdminUserDO user1 = userService.getUser(user.getId());
        List<ShopCouponTemplate> shopCouponTemplates = this.canLedCouponPlatform();
        List<ShopCoupon> coupons =new ArrayList<>();
        for (ShopCouponTemplate shopCouponTemplate : shopCouponTemplates) {
            ShopCoupon temp = new ShopCoupon();
            BeanUtils.copyProperties(shopCouponTemplate, temp);
            temp.setUserId(user.getId());
            temp.setTemplateId(shopCouponTemplate.getId());
            temp.setPhonenumber(user1.getMobile());
            temp.setAllPlatform("1");
            temp.setCouponStatus("0");
            if (ObjectUtil.isEmpty(temp.getStartTime()) && null != shopCouponTemplate.getEffectiveDay()) {
                temp.setStartTime(new Date());
                temp.setExpirationTime(subtractTime(new Date(), shopCouponTemplate.getEffectiveDay()));
            }
            // 生成code 8位UUID和当前日期时间毫秒的字符串
            String uuid = UUID.randomUUID().toString().substring(0, 8);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
            String formattedDateTime = LocalDateTime.now().format(formatter);
            String result =  formattedDateTime + uuid;
            temp.setCouponCode(result);
            temp.setPartnerId(0L);
            coupons.add(temp);
        }
        this.saveBatch(coupons);
    }

    private Date subtractTime(Date date, int amount) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String strTime = sdf.format(date.getTime() + amount);
            Date time = sdf.parse(strTime);
            return time;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }



}
