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

import cn.hutool.core.date.DateUtil;
import cn.iocoder.yudao.framework.mybatis.core.dataobject.BaseDO;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.knowledge.constants.CodeEnum;
import cn.iocoder.yudao.module.knowledge.constants.Result;
import cn.iocoder.yudao.module.knowledge.controller.requestdto.TArchivesRequest;
import cn.iocoder.yudao.module.knowledge.controller.requestdto.TRegulatoryFrameworkRequest;
import cn.iocoder.yudao.module.knowledge.mapper.TRegulatoryFrameworkMapper;
import cn.iocoder.yudao.module.knowledge.entity.TRegulatoryFramework;
import cn.iocoder.yudao.module.knowledge.entity.TRegulatoryFrameworkRecord;
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 org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

;

/**
 * 规章制度表(TRegulatoryFramework)表服务实现类
 *
 * @author makejava
 * @since 2024-04-12 17:36:32
 */
@Service
public class TRegulatoryFrameworkService extends ServiceImpl<TRegulatoryFrameworkMapper, TRegulatoryFramework> {

    @Autowired
    private TArchivesService tArchivesService;
    @Autowired
    private TRegulatoryFrameworkRecordsService recordService;


    public IPage select(Page<TRegulatoryFramework> page, TRegulatoryFrameworkRequest regulatoryFrameworkRequest) {

        return baseMapper.getListPage(page,regulatoryFrameworkRequest);
    }

    public List<TRegulatoryFramework> selectForExport(TRegulatoryFrameworkRequest dto) {
        //使用重载方法
        return baseMapper.getListPage(dto);
    }


    public Result add(TRegulatoryFrameworkRequest regulatoryFrameworkRequest)throws Exception {
        LambdaQueryWrapper<TRegulatoryFramework> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(TRegulatoryFramework::getName,regulatoryFrameworkRequest.getName()).last("limit 1");
        TRegulatoryFramework old = this.getOne(queryWrapper);
        //判断之前是否有相同名字的规章制度

        if (old != null){
            //判断版本号是否重复
            if(old.getVersion().equals(regulatoryFrameworkRequest.getVersion()))
            {
                throw new  RuntimeException("存在历史版本号");
            }
            //更新相同名字的记录
            TRegulatoryFramework newRegulatoryFramework =new TRegulatoryFramework();
            BeanUtils.copyProperties(regulatoryFrameworkRequest,newRegulatoryFramework);
            newRegulatoryFramework.setId(old.getId());
            baseMapper.updateById(newRegulatoryFramework);
            if(old.getIsFiling()==0){
                //之前未归档过归档过
                //进行修改
                // 将现存数据移至历史
                TRegulatoryFrameworkRecord saveData =new TRegulatoryFrameworkRecord();
                BeanUtils.copyProperties(old,saveData);
                saveData.setLawsId(old.getId());
                saveData.setFilingTime(new Date());
                saveData.setId(null);
                saveData.setCreatorId(SecurityFrameworkUtils.getLoginUserId().toString());
                saveData.setCreator(SecurityFrameworkUtils.getLoginUserNickname());
                recordService.save(saveData);
                noticeFolder(old,193l,"1");
            }
        }else {
            //在历史库中查询版本号是否重复
            LambdaQueryWrapper<TRegulatoryFrameworkRecord> queryWrapperHis = new LambdaQueryWrapper<>();
            queryWrapperHis.eq(TRegulatoryFrameworkRecord::getName,regulatoryFrameworkRequest.getName()).eq(TRegulatoryFrameworkRecord::getVersion,regulatoryFrameworkRequest.getVersion());
            long count = this.count(queryWrapper);
            if (count>0){
                throw new  RuntimeException("存在历史版本号");
            }
            //进行新增数据
            TRegulatoryFramework data =new TRegulatoryFramework();
            BeanUtils.copyProperties(regulatoryFrameworkRequest,data);
            data.setCode(generateRandomString());
            data.setIsFiling(0);
            baseMapper.insert(data);
           // noticeFolder(data,193l,"0");
        }

        return Result.success();

    }


    public Result updateByTLId(TRegulatoryFrameworkRequest regulatoryFrameworkRequest) throws Exception {
        TRegulatoryFramework old = this.getById(regulatoryFrameworkRequest.getId());
        if (old != null){
            //判断是否修改了文件名称
            old.setFileName(regulatoryFrameworkRequest.getFileName());
            old.setFileSize(regulatoryFrameworkRequest.getFileSize());
            old.setFileUrl(regulatoryFrameworkRequest.getFileUrl());
            old.setDescribeInfo(regulatoryFrameworkRequest.getDescribeInfo());
            old.setType(regulatoryFrameworkRequest.getType());
            baseMapper.updateById(old);
            //noticeFolder(old,193l,"0");
            return Result.success();
        }else {
            return Result.error(CodeEnum.TARCHIVES_SELECT_FAILED.getCode(),CodeEnum.TARCHIVES_SELECT_FAILED.getMsg());
        }

    }

    public List<TRegulatoryFramework> history(TRegulatoryFrameworkRequest regulatoryFrameworkRequest) {
        LambdaQueryWrapper<TRegulatoryFramework> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TRegulatoryFramework::getName,regulatoryFrameworkRequest.getName());
        queryWrapper.eq(TRegulatoryFramework::getDeleted,"1");
        queryWrapper.orderByDesc(TRegulatoryFramework::getCreateTime);

        return baseMapper.selectList(queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    public void filing(long id) throws Exception {
        // 归档操作
        baseMapper.filling(id);
        TRegulatoryFramework old = getById(id);
        // 将现存数据移至历史
        TRegulatoryFrameworkRecord saveData =new TRegulatoryFrameworkRecord();
        BeanUtils.copyProperties(old,saveData);
        saveData.setId(null);
        saveData.setLawsId(old.getId());
        saveData.setFilingTime(new Date());
        saveData.setCreatorId(SecurityFrameworkUtils.getLoginUserId().toString());
        saveData.setCreator(SecurityFrameworkUtils.getLoginUserNickname());
        recordService.save(saveData);
        noticeFolder(old,193l,"1");

    }

    public boolean isFilling(long id){
        if (baseMapper.judgeIsFilling(id) == 1){
            //已经归档，不可预览
            return true;
        }else {
            //未归档，可以预览
            return false;
        }


    }


    public void archiveFolder() {

        //todo 将所有的归档规章制度根据年限进行分组形成时间文件夹


    }

    public List<TRegulatoryFrameworkRecord> recordsQuery(TRegulatoryFrameworkRequest tLawsRequest) {
        LambdaQueryWrapper<TRegulatoryFrameworkRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TRegulatoryFrameworkRecord::getLawsId,tLawsRequest.getId()).orderByDesc(BaseDO::getCreateTime);
        //记录查询
        List<TRegulatoryFrameworkRecord> targetList = recordService.list(queryWrapper);
        return targetList;
    }

    /**
     * 逻辑删除数据
     * @param ids
     */
    public Result delete(List<Long> ids) {
        int flag = 0;
        for (Long id : ids) {
            LambdaQueryWrapper<TRegulatoryFrameworkRecord> queryWrapper =new LambdaQueryWrapper<>();
            queryWrapper.eq(TRegulatoryFrameworkRecord::getLawsId,id);
            //同步删除归档记录
            List<TRegulatoryFrameworkRecord> records = recordService.list(queryWrapper);
            for (TRegulatoryFrameworkRecord record : records) {
                //同步删除档案管理中的文件
                TArchivesRequest tArchivesRequest =new TArchivesRequest();
                tArchivesRequest.setParentId(193l);
                tArchivesRequest.setCurFilename(record.getName()+"_"+record.getVersion());
                tArchivesRequest.setYear(DateUtil.format(record.getFilingTime(),"yyyy"));
                tArchivesService.delByFileIdAndYear(tArchivesRequest);
                recordService.removeById(record.getId());
            }
            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(TRegulatoryFramework target, long folderNum, String fileType) {
        // 通信规章制度文件夹
        TArchivesRequest tArchivesRequest = new TArchivesRequest();
        tArchivesRequest.setParentId(folderNum);
        tArchivesRequest.setFileSize(target.getFileSize());
        tArchivesRequest.setOriginalFilename(target.getFileName());
        tArchivesRequest.setFileUrl(target.getFileUrl());
        tArchivesRequest.setCurFilename(target.getName() + "_" + target.getVersion());
        tArchivesRequest.setType("3");
        tArchivesRequest.setArchiveType(fileType);
        try {
            tArchivesService.add(tArchivesRequest);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    //=====app
    public IPage selectForApp(Page<TRegulatoryFramework> page, TRegulatoryFrameworkRequest regulatoryFrameworkRequest) throws ParseException {

        IPage<TRegulatoryFramework> tRegulatoryFrameworkIPage = baseMapper.selectForApp(page, regulatoryFrameworkRequest);
        List<TRegulatoryFramework> records = tRegulatoryFrameworkIPage.getRecords();

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        for (TRegulatoryFramework record : records) {
            String format = simpleDateFormat.format(record.getCreateTime());
            Date date = simpleDateFormat.parse(format);

        }
        return tRegulatoryFrameworkIPage;
    }

    public List<TRegulatoryFramework> selectForExportForApp(TRegulatoryFrameworkRequest dto) {
        //使用重载方法
        return baseMapper.getListPage(dto);
    }


    public Result addForApp(TRegulatoryFrameworkRequest regulatoryFrameworkRequest)throws Exception {
        LambdaQueryWrapper<TRegulatoryFramework> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(TRegulatoryFramework::getName,regulatoryFrameworkRequest.getName()).last("limit 1");
        TRegulatoryFramework old = this.getOne(queryWrapper);
        //判断之前是否有相同名字的规章制度

        if (old != null){
            //判断版本号是否重复
            if(old.getVersion().equals(regulatoryFrameworkRequest.getVersion()))
            {
                throw new  RuntimeException("存在历史版本号");
            }
            //更新相同名字的记录
            TRegulatoryFramework newRegulatoryFramework =new TRegulatoryFramework();
            BeanUtils.copyProperties(regulatoryFrameworkRequest,newRegulatoryFramework);
            newRegulatoryFramework.setId(old.getId());
            baseMapper.updateById(newRegulatoryFramework);
            if(old.getIsFiling()==0){
                //之前未归档过归档过
                //进行修改
                // 将现存数据移至历史
                TRegulatoryFrameworkRecord saveData = new TRegulatoryFrameworkRecord();
                BeanUtils.copyProperties(old,saveData);
                saveData.setLawsId(old.getId());
                saveData.setFilingTime(new Date());
                saveData.setId(null);
                saveData.setCreatorId(SecurityFrameworkUtils.getLoginUserId().toString());
                saveData.setCreator(SecurityFrameworkUtils.getLoginUserNickname());
                recordService.save(saveData);
                noticeFolder(old,193l,"1");
            }
        }else {
            //在历史库中查询版本号是否重复
            LambdaQueryWrapper<TRegulatoryFrameworkRecord> queryWrapperHis = new LambdaQueryWrapper<>();
            queryWrapperHis.eq(TRegulatoryFrameworkRecord::getName,regulatoryFrameworkRequest.getName()).eq(TRegulatoryFrameworkRecord::getVersion,regulatoryFrameworkRequest.getVersion());
            long count = this.count(queryWrapper);
            if (count>0){
                throw new  RuntimeException("存在历史版本号");
            }
            //进行新增数据
            TRegulatoryFramework data =new TRegulatoryFramework();
            BeanUtils.copyProperties(regulatoryFrameworkRequest,data);
            data.setCode(generateRandomString());
            data.setIsFiling(0);
            baseMapper.insert(data);
           // noticeFolder(data,193l,"0");
        }

        return Result.success();

    }


    public Result updateByTLIdForApp(TRegulatoryFrameworkRequest regulatoryFrameworkRequest) throws Exception {
        TRegulatoryFramework old = this.getById(regulatoryFrameworkRequest.getId());
        if (old != null){
            //判断是否修改了文件名称
            old.setFileName(regulatoryFrameworkRequest.getFileName());
            old.setFileSize(regulatoryFrameworkRequest.getFileSize());
            old.setFileUrl(regulatoryFrameworkRequest.getFileUrl());
            old.setDescribeInfo(regulatoryFrameworkRequest.getDescribeInfo());
            baseMapper.updateById(old);
           // noticeFolder(old,193l,"0");
            return Result.success();
        }else {
            return Result.error(CodeEnum.TARCHIVES_SELECT_FAILED.getCode(),CodeEnum.TARCHIVES_SELECT_FAILED.getMsg());
        }

    }

    public List<TRegulatoryFramework> historyForApp(TRegulatoryFrameworkRequest regulatoryFrameworkRequest) {
        LambdaQueryWrapper<TRegulatoryFramework> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TRegulatoryFramework::getName,regulatoryFrameworkRequest.getName());
        queryWrapper.eq(TRegulatoryFramework::getDeleted,"1");
        queryWrapper.orderByDesc(TRegulatoryFramework::getCreateTime);

        return baseMapper.selectList(queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    public void filingForApp(long id) throws Exception {
        // 归档操作
        baseMapper.filling(id);
        TRegulatoryFramework old = getById(id);
        // 将现存数据移至历史
        TRegulatoryFrameworkRecord saveData = new TRegulatoryFrameworkRecord();
        BeanUtils.copyProperties(old,saveData);
        saveData.setId(null);
        saveData.setLawsId(old.getId());
        saveData.setFilingTime(new Date());
        saveData.setCreatorId(SecurityFrameworkUtils.getLoginUserId().toString());
        saveData.setCreator(SecurityFrameworkUtils.getLoginUserNickname());
        recordService.save(saveData);
        noticeFolder(old,193l,"1");

    }

    public boolean isFillingForApp(long id){
        if (baseMapper.judgeIsFilling(id) == 1){
            //已经归档，不可预览
            return true;
        }else {
            //未归档，可以预览
            return false;
        }


    }


    public void archiveFolderForApp() {

        //todo 将所有的归档规章制度根据年限进行分组形成时间文件夹


    }

    public List<TRegulatoryFrameworkRecord> recordsQueryForApp(TRegulatoryFrameworkRequest tLawsRequest) {
        LambdaQueryWrapper<TRegulatoryFrameworkRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TRegulatoryFrameworkRecord::getLawsId,tLawsRequest.getId()).orderByDesc(BaseDO::getCreateTime);
        //记录查询
        List<TRegulatoryFrameworkRecord> targetList = recordService.list(queryWrapper);
        return targetList;
    }

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

}

