package com.iamberry.wechat.service.mothMovable;

import com.iamberry.wechat.core.entity.coupon.CouponItem;
import com.iamberry.wechat.core.entity.coupon.CouponType;
import com.iamberry.wechat.core.entity.mothMovable.MothMovable;
import com.iamberry.wechat.core.entity.mothMovable.MothPopularity;
import com.iamberry.wechat.core.entity.wx.QRCJson;
import com.iamberry.wechat.face.admin.SystemService;
import com.iamberry.wechat.face.mothMovable.MothMovableService;
import com.iamberry.wechat.file.FileUtils;
import com.iamberry.wechat.service.mapper.CouponItemMapper;
import com.iamberry.wechat.service.mapper.CouponTypeMapper;
import com.iamberry.wechat.service.mapper.MothMovableMapper;
import com.iamberry.wechat.service.mapper.MothPopularityMapper;
import com.iamberry.wechat.tools.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.awt.*;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 *  活动生成图片的内容接口
 * @author xm
 * @Date 2019-04-25
 */
@Service
public class MothMovableServiceImpl  implements MothMovableService {

    @Autowired
    private MothMovableMapper mothMovableMapper;
    @Autowired
    private MothPopularityMapper mothPopularityMapper;
    @Autowired
    private CouponTypeMapper couponTypeMapper;
    @Autowired
    private CouponItemMapper couponItemMapper;
    @Autowired
    private SystemService systemService;

    /**
     * 获取集合
     * @param  mothMovable
     * @return List
     */
    @Override
    public List<MothMovable> getMothMovableList(MothMovable  mothMovable){
        return  mothMovableMapper.getMothMovableList(mothMovable);
    }
    /**
     * 查询单条数据
     * @param  id
     * @return  mothMovable
     */
    @Override
    public  MothMovable  getMothMovableById(Integer  id){
        return  mothMovableMapper.getMothMovableById(id);
    }
    /**
     * 增加数据
     * @param  mothMovable
     * @return Integer
     */
    @Override
    @Transactional
    public  Integer  save(MothMovable  mothMovable,String rootPath){
        //生成优惠券 -- 每位参加活动的人，发送wateroT1-T2滤芯优惠券  ，优惠券限7天内使用，否则实效
        // 成功参与征集的用户，赠送wateroT1/T2滤芯优惠券，共50个，先到先得
        Integer flag = 0 ;
        String uuidStr = "";

        String begin = systemService.selectOneShopRuleByIdDynamic(238).getRuleDesc();
        Integer num = Integer.valueOf(begin);

        MothMovable mm1 = new MothMovable();
        Integer allNum = mothMovableMapper.getNum(mm1);
        if(allNum < num){
            //创建优惠券
            Integer couponId = 10001;
            CouponType couponType = couponTypeMapper.getCouponTypeById(couponId);
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DATE, 7);  //有效期7天
            calendar.set(Calendar.HOUR_OF_DAY,23);
            calendar.set(Calendar.MINUTE,59);
            calendar.set(Calendar.SECOND,59);
            CouponItem couponItem = new CouponItem();
            uuidStr = StrUtils.getUUID();
            couponItem.setCouponItemId(uuidStr);
            couponItem.setCouponItemUseropenid(mothMovable.getMothMovaOpenId());
            couponItem.setCouponId(couponId);
            couponItem.setCouponReceiveDate(new Date());
            couponItem.setCouponUseEndDate(calendar.getTime());
            couponItem.setCouponUseStatus(1);
            couponItem.setCouponItemRemark(couponType.getCouponRemark());
            flag = couponItemMapper.insertCouponItem(couponItem);
            if(flag < 1){
                throw new RuntimeException("创建优惠券失败");
            }
        }

        boolean fl = false;
        //生成图片
        try {
            fl = geneImg(mothMovable,rootPath);
        }catch (Exception e){
            e.printStackTrace();
        }
        if(fl){
            //添加数据
            mothMovable.setCouponItemId(uuidStr);
            flag = mothMovableMapper.save(mothMovable);
            if(flag < 1){
                throw new RuntimeException("添加活动数据失败");
            }
        }else{
            throw new RuntimeException("生成图片失败");
        }
        return flag;
    }


    /**
     *  生成图片
     * @param mothMovable
     * @param rootPath  根目录
     * @return
     */
    private boolean geneImg(MothMovable mothMovable,String rootPath)throws Exception{
        Integer type = 0;
        if(mothMovable.getMothMovaBackType() == 5){
            type = 1;   //头像放在中间
        }
        PosterNumUtils pnu = new PosterNumUtils(type);
        //  ****/common/images/movable/
        String uuid = UUID.randomUUID().toString().substring(0,8);
        String codeName  = uuid + "_code.jpg";
        String headName  = uuid + "_head.jpg";
        String imgName  = uuid + "_img.jpg";
        String path  = rootPath + pnu.IMG_PATH;

        File targetFile = new File(path);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }

        //生成机器二维码
        String json = String.format(NameUtils.QR_SCENE_STR, 2592000, ResultInfo.barCodeMothMovable + mothMovable.getMothMovaOpenId());
        QRCJson qrc = WeixinUtil.createQrcode(json);

       /*下载二维码*/
        DownloadWXCodeUtil.downloadByNIO2(qrc.getUrl(),codeName,path,pnu.CODE_WIDTH,pnu.CODE_HEIGHT,false);

        if(mothMovable.getMothMovaHead() == null || "".equals(mothMovable.getMothMovaHead())){
            String headImg = path+headName;
            String oldheadImg = path+PosterNumUtils.getBackPath(0);
            FileUtils.copyFile(oldheadImg,headImg);
        }else{
            DownloadWXCodeUtil.downloadByNIO2(mothMovable.getMothMovaHead(),headName,path,pnu.HEAD_WIDTH,pnu.HEAD_HEIGHT,pnu.HEAD_IS_CIRCLE);
        }


        /*海报位置*/
        String newImg = path+imgName;
		/*二维码位置*/
        String codeImg = path + codeName;
		/*头像位置*/
        String headImg = path + headName;

		/*复制海报*/ //common/images/activity/ditu.jpg
        String oldImgPath = path + PosterNumUtils.getBackPath(mothMovable.getMothMovaBackType());
        FileUtils.copyFile(oldImgPath,newImg);

        mothMovable.setMothMovaImgUrl(pnu.IMG_PATH + imgName);
        mothMovable.setMothMovaShareUrl(qrc.getUrl());

			  /*添加文字*/
        ImageUtils.pressPost(newImg,
                headImg,pnu.HEAD_X,pnu.HEAD_Y,
                codeImg,pnu.CODE_X,pnu.CODE_Y,
                mothMovable.getMothMovaName(),pnu.TEXT_X,pnu.TEXT_Y,new Color(0,0,0),pnu.TEXT_FONT_SIZE,
                mothMovable.getMothMovaText(),pnu.TEXT_CONTENT_X,pnu.TEXT_CONTENT_Y,new Color(0,0,0),pnu.TEXT_CONTENT_FONT_SIZE,
                pnu.FONT_LINE_SPACING,pnu.FONT_NUMBER
        );
        return true;
    }

    /**
     * 修改数据
     * @param  mothMovable
     * @return Integer
     */
    @Override
    public  Integer  update(MothMovable  mothMovable){
        return  mothMovableMapper.update(mothMovable);
    }
    /**
     * 删除数据
     * @param  id
     * @return Integer
     */
    @Override
    public  Integer  delete(Integer  id){
        return  mothMovableMapper.delete(id);
    }

    @Override
    public Integer scanInfo(String mothMovaOpenId, String openId) {
        MothMovable mothMovable = new MothMovable();
        mothMovable.setMothMovaOpenId(mothMovaOpenId);
        List<MothMovable> mothMovableList = mothMovableMapper.getMothMovableList(mothMovable);
        if(mothMovableList == null || mothMovableList.size() < 1){
            return 0;
        }
        mothMovable = mothMovableList.get(0);
        MothPopularity mothPopularity = new MothPopularity();
        mothPopularity.setMothMovaId(mothMovable.getMothMovaId());
        mothPopularity.setMothPopuOpenId(openId);
        return mothPopularityMapper.save(mothPopularity);
    }
}
