package com.zhongzheng.modules.base.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.zhongzheng.common.utils.DateUtils;
import com.zhongzheng.common.utils.ServletUtils;
import com.zhongzheng.modules.base.bo.CertificateTpAddBo;
import com.zhongzheng.modules.base.bo.CertificateTpEditBo;
import com.zhongzheng.modules.base.bo.CertificateTpQueryBo;
import com.zhongzheng.modules.base.domain.CertificateTp;
import com.zhongzheng.modules.base.mapper.CertificateTpMapper;
import com.zhongzheng.modules.base.service.ICertificateTpService;
import com.zhongzheng.modules.base.vo.CertificatePhotoVo;
import com.zhongzheng.modules.base.vo.CertificateTpVo;
import com.zhongzheng.modules.course.domain.CourseBusiness;
import com.zhongzheng.modules.course.vo.CourseChapterVo;
import com.zhongzheng.modules.course.vo.CourseUserEducationTypeVo;
import com.zhongzheng.modules.goods.service.IGoodsAttachedService;
import com.zhongzheng.modules.goods.service.IGoodsService;
import com.zhongzheng.modules.goods.vo.GoodsVo;
import com.zhongzheng.modules.grade.bo.ClassGradeUserQueryBo;
import com.zhongzheng.modules.grade.service.IClassGradeUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.Page;

import javax.imageio.ImageIO;
import javax.validation.Valid;
import javax.validation.Validation;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 证书模板Service业务层处理
 *
 * @author hjl
 * @date 2022-02-16
 */
@Service
public class CertificateTpServiceImpl extends ServiceImpl<CertificateTpMapper, CertificateTp> implements ICertificateTpService {

    @Autowired
    private IGoodsService iGoodsService;
    @Autowired
    private IClassGradeUserService iClassGradeUserService;

    @Override
    public CertificateTpVo queryById(Long tpId){
        CertificateTp db = this.baseMapper.selectById(tpId);
        return BeanUtil.toBean(db, CertificateTpVo.class);
    }

    @Override
    public List<CertificateTpVo> queryList(CertificateTpQueryBo bo) {
        LambdaQueryWrapper<CertificateTp> lqw = Wrappers.lambdaQuery();
        lqw.eq(StrUtil.isNotBlank(bo.getCode()), CertificateTp::getCode, bo.getCode());
        lqw.eq(StrUtil.isNotBlank(bo.getTitle()), CertificateTp::getTitle, bo.getTitle());
        lqw.eq(StrUtil.isNotBlank(bo.getIntroduce()), CertificateTp::getIntroduce, bo.getIntroduce());
        lqw.eq(bo.getTypeId() != null, CertificateTp::getTypeId, bo.getTypeId());
        lqw.in(bo.getStatus() != null, CertificateTp::getStatus, bo.getStatus());
        return entity2Vo(this.list(lqw));
    }

    /**
    * 实体类转化成视图对象
    *
    * @param collection 实体类集合
    * @return
    */
    private List<CertificateTpVo> entity2Vo(Collection<CertificateTp> collection) {
        List<CertificateTpVo> voList = collection.stream()
                .map(any -> BeanUtil.toBean(any, CertificateTpVo.class))
                .collect(Collectors.toList());
        if (collection instanceof Page) {
            Page<CertificateTp> page = (Page<CertificateTp>)collection;
            Page<CertificateTpVo> pageVo = new Page<>();
            BeanUtil.copyProperties(page,pageVo);
            pageVo.addAll(voList);
            voList = pageVo;
        }
        return voList;
    }

    @Override
    public Boolean insertByAddBo(CertificateTpAddBo bo) {
        CertificateTp add = BeanUtil.toBean(bo, CertificateTp.class);
        validEntityBeforeSave(add);
        add.setCode(ServletUtils.getEncoded("ZM"));
        add.setCreateTime(DateUtils.getNowTime());
        add.setUpdateTime(DateUtils.getNowTime());
        return this.save(add);
    }

    @Override
    public Boolean updateByEditBo(CertificateTpEditBo bo) {
        CertificateTp update = BeanUtil.toBean(bo, CertificateTp.class);
        validEntityBeforeSave(update);
        update.setUpdateTime(DateUtils.getNowTime());
        return this.updateById(update);
    }

    /**
     * 生成用户证书
     * @param bo
     * @return
     */
    @Override
    public String makeCertificatePhoto(ClassGradeUserQueryBo bo) {
        GoodsVo goodsVo = iGoodsService.selectDetail(bo.getGoodsId());
        List<CourseChapterVo> chapterList =  iClassGradeUserService.findChapterList(bo);
        if(Validator.isNotEmpty(goodsVo.getCertificateIds())){
            String[] s = goodsVo.getCertificateIds().split(",");
            List<Long> tpIds = new ArrayList<>();
            for(String each : s) {
                tpIds.add(Long.valueOf(each));
            }
            CertificateTpQueryBo queryBo = new CertificateTpQueryBo();
            queryBo.setTpIds(tpIds);
            List<CertificateTpVo> list = queryList(queryBo);
            for(CertificateTpVo tpVo : list){
                if("certificate01".equals(tpVo.getKeyValue())){
                    CertificatePhotoVo vo = new CertificatePhotoVo();
                    vo.setCode("XYZC21011234");
                    vo.setRealname("李盛仁");
                    vo.setIdCard("445224199901040003");
                    String date = DateUtils.timestampToDate(goodsVo.getCreateTime());
                    vo.setYear(date.substring(0, 4));
                    vo.setType("专业");
                    vo.setMajor("网络班");
                    vo.setClassHours(goodsVo.getClassHours()+"");

                    vo.setDateY(date.substring(0, 4));
                    vo.setDateM(date.substring(5, 2));
                    vo.setDateD(date.substring(7, 2));
                  /*  List<String> chapterList = new ArrayList<>();
                    chapterList.add("①.绿色施工");
                    chapterList.add("②.绿色施工");
                    chapterList.add("③.绿色施工");
                    chapterList.add("④.绿色施工");
                    chapterList.add("⑤.绿色施工");
                    chapterList.add("⑥.绿色施工");
                    chapterList.add("⑦.绿色施工");
                    chapterList.add("⑧.绿色施工");
                    vo.setChapterList(chapterList);
                    drawPic(vo);*/

                }
            }

        }
        return null;
    }

    private  String drawPic(CertificatePhotoVo entity){
        Font font = new Font("微软雅黑", Font.PLAIN, 45);// 添加字体的属性设置

        String projectUrl = "D:\\test\\";
        String imgName = projectUrl + "out01.jpg";
        try {
            // 加载本地图片
            String imageLocalUrl = projectUrl + "002.jpg";
            BufferedImage imageLocal = ImageIO.read(new File(imageLocalUrl));
            // 以本地图片为模板
            Graphics2D g = imageLocal.createGraphics();

            // 设置文本样式
            g.setFont(font);
            g.setColor(Color.BLACK);

            g.drawString(entity.getCode(), 445, 290);
            g.drawString(entity.getRealname(), 488, 562);
            g.drawString(entity.getIdCard(), 1030, 562);
            g.drawString(entity.getYear(), 1865, 562);
            g.drawString(entity.getType(), 780, 679);
            g.drawString(entity.getMajor(), 1175, 679);
            g.drawString(entity.getClassHours(), 953, 788);
            g.drawString(entity.getDateY(), 2280, 1599);
            g.drawString(entity.getDateM(), 2505, 1599);
            g.drawString(entity.getDateD(), 2712, 1599);
            int x = 493;
            int y = 999;
            int i=0;
            for(String chapterName :entity.getChapterList() ){
                g.drawString(chapterName, x, y);
                i++;
                if(i%2==1){
                    x=1650;
                }else{
                    x=493;
                    y+=80;
                }
                if(i>7){
                    break;
                }
            }
            // 完成模板修改
            g.dispose();
            // 获取新文件的地址
            File outputfile = new File(imgName);
            // 生成新的合成过的用户二维码并写入新图片
            ImageIO.write(imageLocal, "jpg", outputfile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 返回给页面的图片地址(因为绝对路径无法访问)
        //    imgName = Constants.PROJECT_URL + "codeImg/" + userId + ".png";

        return imgName;
    }

    @Override
    public List<CertificateTpVo> selectList(CertificateTpQueryBo bo) {
        return this.baseMapper.selectList(bo);
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(CertificateTp entity){
        //TODO 做一些数据校验,如唯一约束
        if(Validator.isNull(entity.getTypeId())&&Validator.isNotEmpty(entity.getTpId())){
            //删除类型ID
            LambdaUpdateWrapper<CertificateTp> objectLambdaUpdateWrapper = Wrappers.lambdaUpdate();
            objectLambdaUpdateWrapper.eq(CertificateTp::getTpId,entity.getTpId());
            objectLambdaUpdateWrapper.set(CertificateTp::getTypeId, null);
            objectLambdaUpdateWrapper.set(CertificateTp::getUpdateTime,DateUtils.getNowTime());
            this.update(null, objectLambdaUpdateWrapper);
        }
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return this.removeByIds(ids);
    }
}
