package cn.iocoder.yudao.module.knowledge.service;

import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.knowledge.constants.Result;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.knowledge.controller.requestdto.TArchivesRequest;
import cn.iocoder.yudao.module.knowledge.controller.requestdto.TViolationRequest;
import cn.iocoder.yudao.module.knowledge.mapper.TViolationImageMapper;
import cn.iocoder.yudao.module.knowledge.entity.TViolation;
import cn.iocoder.yudao.module.knowledge.entity.TViolationImage;
import cn.iocoder.yudao.module.knowledge.mapper.TViolationMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;

/**
 * 违章表(TViolation)表服务实现类
 *
 * @author makejava
 * @since 2024-04-13 14:58:19
 */
@Service
public class TViolationService extends ServiceImpl<TViolationMapper, TViolation> {
    //    @Transactional(rollbackFor = Exception.class)
    @Autowired
    private TViolationImageMapper imageMapper;

    @Autowired
    private TArchivesService tArchivesService;
    @Autowired
    private  AdminUserApi userApi;
    private static final String msgCode ="violation";


    public IPage select(Page<TViolation> page, TViolationRequest tViolation) {

        return baseMapper.getListPage(page, tViolation);
    }

    public IPage appFindAll(Page<TViolation> page, TViolationRequest tViolation) {

        IPage<TViolation> tViolationIPage = baseMapper.appFindAll(page, tViolation);
        for (TViolation record : tViolationIPage.getRecords()) {
            record.setViolationTimes(record.getViolationTime());
        }
        return tViolationIPage;
    }

    public List<TViolation> selectForExport(TViolationRequest violationRequest) {
        //使用重载方法
        return baseMapper.getListPage(violationRequest);
    }

    public TViolationRequest getTVById(Long id) {
        TViolation tViolation = baseMapper.selectById(id);
        TViolationRequest target = new TViolationRequest();
        BeanUtils.copyProperties(tViolation, target);
        List<TViolationImage> images = imageMapper.selectByViolationId(id);
        target.setImgList(images);

        return target;
    }

    public TViolationRequest findOneForApp(Long id) {
        TViolation tViolation = baseMapper.selectById(id);
        TViolationRequest target = new TViolationRequest();
        BeanUtils.copyProperties(tViolation, target);
        List<TViolationImage> images = imageMapper.findOneForApp(id);
        target.setImgList(images);

        return target;
    }


    public Result add(TViolationRequest request) {

        //进行新增数据
        TViolation data = new TViolation();
        BeanUtils.copyProperties(request, data);
        data.setCode(generateRandomString());
        int newId = new Random().nextInt();
        if (newId<0){
            newId = -newId;
        }
        data.setId(Long.valueOf(newId));
        data.setCreator(SecurityFrameworkUtils.getLoginUserNickname());
        baseMapper.insert(data);
        //添加图片表
        if (request.getImgList() != null){
            List<TViolationImage> imgList = request.getImgList();
            int i = 1;
            for (TViolationImage image :imgList){
                image.setName(request.getTitle() + i++);
                image.setViolationId(Long.valueOf(newId));
            
                image.setCreator(SecurityFrameworkUtils.getLoginUserNickname());
                imageMapper.insert(image);
                noticeFolder(image,10963L,"1");
            }
        }

        return Result.success();

    }

    @Transactional(rollbackFor = Exception.class)
    public void updateByIdVo(TViolationRequest request){
        //进行新增数据
        TViolation data = new TViolation();
        BeanUtils.copyProperties(request, data);
        baseMapper.updateById(data);
        //添加图片表
        LambdaQueryWrapper<TViolationImage> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TViolationImage::getViolationId,request.getId());
        imageMapper.delete(wrapper);
        if (request.getImgList() != null){
            List<TViolationImage> imgList = request.getImgList();
            int i = 1;
            for (TViolationImage image :imgList){
                image.setName(request.getTitle() + i++);
                image.setViolationId(request.getId());
                image.setId(generateRandomString());
                image.setCreator(SecurityFrameworkUtils.getLoginUserNickname());
                imageMapper.insert(image);
                noticeFolder(image,10963L,"1");
            }
        }
    }
    public void push(Long id) {
        TViolation pushData = getById(id);

        Date date = pushData.getLastPushTime();
       //判断是否推送过
        if(date != null){
            Instant instant = date.toInstant();
            ZoneId zone = ZoneId.systemDefault();
            LocalDate localDate = instant.atZone(zone).toLocalDate();

            //判断最后推送时间是否是今天
            if (!LocalDate.now().isEqual(localDate)) {
                //todo 推送
                pushData.setLastPushTime(new Date());
                baseMapper.updateById(pushData);
            }
        }else {
            //todo 推送
            pushData.setLastPushTime(new Date());
            baseMapper.updateById(pushData);
        }

    }


    /**
     * 逻辑删除数据
     *
     * @param ids
     */
    public Result delete(List<Long> ids) {
        int flag = 0;
        for (Long id : ids) {
            baseMapper.deleteById(id);
            flag++;
        }
        return Result.success(flag);
    }


    public static String generateRandomString() {
        Random random = new Random();
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < 6; i++) {
            int randomNumber = random.nextInt(10);
            sb.append(randomNumber);
        }

        return sb.toString();
    }

    /**
     * 通信违章图片文件夹
     * @param target
     * @param folderNum
     * @param fileType
     * @return
     */
    private boolean noticeFolder(TViolationImage target,long folderNum,String fileType){
        TArchivesRequest tArchivesRequest =new TArchivesRequest();
        tArchivesRequest.setParentId(folderNum);
//        tArchivesRequest.setFileSize(Long.valueOf(target.getFileSize()));
        tArchivesRequest.setFileSize(Long.valueOf(target.getFileSize()));
        tArchivesRequest.setOriginalFilename(target.getName());
        tArchivesRequest.setFileUrl(target.getFileUrl());
        tArchivesRequest.setCurFilename(target.getName());
        tArchivesRequest.setType(fileType);
        tArchivesRequest.setArchiveType("0");
        try {
            tArchivesService.add(tArchivesRequest);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }

    public Result addForApp(TViolationRequest request) {

        //进行新增数据
        TViolation data = new TViolation();
        BeanUtils.copyProperties(request, data);
        data.setCode(generateRandomString());
        int newId = new Random().nextInt();
        if (newId<0){
            newId = -newId;
        }
        data.setId(Long.valueOf(newId));
        data.setCreator(SecurityFrameworkUtils.getLoginUserNickname());
        baseMapper.insert(data);
        //添加图片表
        if (request.getImgList() != null){
            List<TViolationImage> imgList = request.getImgList();
            int i = 1;
            for (TViolationImage image :imgList){
                image.setName(request.getTitle() + i++);
                image.setViolationId(Long.valueOf(newId));
                image.setCreator(SecurityFrameworkUtils.getLoginUserNickname());
                imageMapper.insert(image);
                noticeFolder(image,10963L,"1");
            }
        }

        return Result.success();

    }

    @Transactional(rollbackFor = Exception.class)
    public void updateByIdVoForApp(TViolationRequest request){
        //进行新增数据
        TViolation data = new TViolation();
        BeanUtils.copyProperties(request, data);
        baseMapper.updateById(data);
        //添加图片表
        LambdaQueryWrapper<TViolationImage> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TViolationImage::getViolationId,request.getId());
        imageMapper.delete(wrapper);
        if (request.getImgList() != null){
            List<TViolationImage> imgList = request.getImgList();
            int i = 1;
            for (TViolationImage image :imgList){
                image.setName(request.getTitle() + i++);
                image.setViolationId(request.getId());
                image.setId(generateRandomString());
                image.setCreator(SecurityFrameworkUtils.getLoginUserNickname());
                imageMapper.insert(image);
                noticeFolder(image,10963L,"1");
            }
        }
    }
    public void pushForApp(Long id) {
        TViolation pushData = getById(id);

        Date date = pushData.getLastPushTime();
        //判断是否推送过
        if(date != null){
            Instant instant = date.toInstant();
            ZoneId zone = ZoneId.systemDefault();
            LocalDate localDate = instant.atZone(zone).toLocalDate();

            //判断最后推送时间是否是今天
            if (!LocalDate.now().isEqual(localDate)) {
                //todo 推送
                pushData.setLastPushTime(new Date());
                baseMapper.updateById(pushData);
            }
        }else {
            //todo 推送
            pushData.setLastPushTime(new Date());
            baseMapper.updateById(pushData);
        }

    }


    /**
     * 逻辑删除数据
     *
     * @param ids
     */
    public Result deleteForApp(List<Long> ids) {
        int flag = 0;
        for (Long id : ids) {
            baseMapper.deleteById(id);
            flag++;
        }
        return Result.success(flag);
    }



}

