package com.yc.ship.module.marketing.service.couponpackage;

import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONObject;
import com.yc.ship.framework.common.pojo.PageResult;
import com.yc.ship.framework.common.util.object.BeanUtils;
import com.yc.ship.module.infra.api.file.FileApi;
import com.yc.ship.module.marketing.controller.admin.couponpackage.vo.CouponPackagePageReqVO;
import com.yc.ship.module.marketing.controller.admin.couponpackage.vo.CouponPackageSaveReqVO;
import com.yc.ship.module.marketing.controller.app.params.vo.AppParamsSaveVo;
import com.yc.ship.module.marketing.dal.dataobject.couponpackage.CouponPackageDO;
import com.yc.ship.module.marketing.dal.dataobject.couponpackagecode.CouponPackageCodeDO;
import com.yc.ship.module.marketing.dal.mysql.couponpackage.CouponPackageMapper;
import com.yc.ship.module.marketing.dal.mysql.couponpackagecode.CouponPackageCodeMapper;
import com.yc.ship.module.marketing.service.params.MarketingParamsService;
import com.yc.ship.module.system.api.social.SocialClientApi;
import com.yc.ship.module.system.api.social.dto.SocialWxQrcodeReqDTO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

import static com.yc.ship.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.yc.ship.module.marketing.enums.ErrorCodeConstants.COUPON_PACKAGE_NOT_EXISTS;


/**
 * 优惠券-券包 Service 实现类
 *
 * @author lfy
 */
@Service
@Validated
public class CouponPackageServiceImpl implements CouponPackageService {

    @Resource
    private CouponPackageMapper couponPackageMapper;

    @Resource
    private FileApi fileApi;

    @Resource
    private SocialClientApi socialClientApi;

    @Resource
    private MarketingParamsService paramsService;

    @Resource
    private CouponPackageCodeMapper couponPackageCodeMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createCouponPackage(CouponPackageSaveReqVO createReqVO) {
        // 插入
        CouponPackageDO couponPackage = BeanUtils.toBean(createReqVO, CouponPackageDO.class);
        couponPackageMapper.insert(couponPackage);
        //生成领取券码
        createMpQrCode(couponPackage);
        // 返回
        return couponPackage.getId();
    }

    @Override
    public void updateCouponPackage(CouponPackageSaveReqVO updateReqVO) {
        // 校验存在
        validateCouponPackageExists(updateReqVO.getId());
        // 更新
        CouponPackageDO updateObj = BeanUtils.toBean(updateReqVO, CouponPackageDO.class);
        couponPackageMapper.updateById(updateObj);
    }

    @Override
    public void deleteCouponPackage(Long id) {
        // 校验存在
        validateCouponPackageExists(id);
        // 删除
        couponPackageMapper.deleteById(id);
    }

    private void validateCouponPackageExists(Long id) {
        if (couponPackageMapper.selectById(id) == null) {
            throw exception(COUPON_PACKAGE_NOT_EXISTS);
        }
    }

    @Override
    public CouponPackageDO getCouponPackage(Long id) {
        return couponPackageMapper.selectById(id);
    }

    @Override
    public PageResult<CouponPackageDO> getCouponPackagePage(CouponPackagePageReqVO pageReqVO) {
        return couponPackageMapper.selectPage(pageReqVO);
    }

    public void createMpQrCode(CouponPackageDO couponPackage) {
        List<CouponPackageCodeDO> list = new ArrayList<>();
        for (int i = 0; i < couponPackage.getCodeNum(); i++) {
            CouponPackageCodeDO couponPackageCodeDO = new CouponPackageCodeDO();
            couponPackageCodeDO.setPackageId(couponPackage.getId())
                    .setCouponId(couponPackage.getCouponId());
            long id = IdUtil.getSnowflakeNextId();
            couponPackageCodeDO.setId(id);
            String mpQrCode = createMpQrCode(id, "pages/mine/coupon/index");
            couponPackageCodeDO.setQrCode(mpQrCode);
            couponPackageCodeDO.setSurplusTimes(couponPackage.getCanReceiveNum());
            list.add(couponPackageCodeDO);
        }
        if(!list.isEmpty()) {
            couponPackageCodeMapper.insertBatch(list);
        }
     }
    private String createMpQrCode(Long id, String path) {
        JSONObject json = new JSONObject();
        //c 表示优惠券id
        json.set("c", id);
        AppParamsSaveVo params = new AppParamsSaveVo();
        params.setParams(json.toString());
        Long paramsId = paramsService.createParams(params);
        SocialWxQrcodeReqDTO reqDTO = new SocialWxQrcodeReqDTO();
        reqDTO.setScene("q="+paramsId);
        reqDTO.setPath(path);
        reqDTO.setAutoColor(true);
        reqDTO.setHyaline(false);
        reqDTO.setWidth(480);
        reqDTO.setCheckPath(false);
        byte[] imageBytes = socialClientApi.getWxaQrcode(reqDTO);
        String file = fileApi.createFile(imageBytes);
        return file;
    }

}