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

import cn.hutool.core.date.DateUtil;
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.framework.mybatis.core.dataobject.BaseDO;
import cn.iocoder.yudao.module.knowledge.constants.CodeEnum;
import cn.iocoder.yudao.module.knowledge.controller.requestdto.TArchivesRequest;
import cn.iocoder.yudao.module.knowledge.controller.requestdto.TLawsRequest;
import cn.iocoder.yudao.module.knowledge.mapper.TLawsMapper;
import cn.iocoder.yudao.module.knowledge.entity.TLaws;
import cn.iocoder.yudao.module.knowledge.entity.TLawsRecord;
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.*;

/**
 * 法律法规表(TLaws)表服务实现类
 *
 * @author makejava
 * @since 2024-04-12 10:31:34
 */
@Service
public class TLawsService extends ServiceImpl<TLawsMapper, TLaws> {
    @Autowired
    private TArchivesService tArchivesService;
    @Autowired
    private TLawsRecordService recordService;


    public IPage select(Page<TLaws> page, TLawsRequest tLaws) {
        tLaws.setCreateTimeStr(DateUtil.format(tLaws.getCreateTime(),"yyyy-MM-dd"));
        return baseMapper.getListPage(page,tLaws);
    }


    public List<TLaws> selectForExport( TLawsRequest tLaws) {
//        String tokenStr = "&Authorization=Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZGVudGl0eUlkIjoxLCJkZXB0SWQiOjEsIm5pY2tuYW1lIjoiR2xvYmFsIFVzZXIiLCJ0ZW5hbnQtaWQiOjEsInVzZXJuYW1lIjoiR2xvYmFsIFVzZXIiLCJleHAiOjE5NzU2NTcyNzZ9.VuFK-ubqp54VwSL3O8yprt7lMWkc77jfSboxUXtRqQ4";
        //使用重载方法
        List<TLaws> result = baseMapper.getListPage(tLaws);
//        result = result.stream()
//                .peek(obj -> obj.setFileUrl(obj.getFileUrl() + tokenStr))
//                .collect(Collectors.toList());
        return result;
    }


    public Result add(TLawsRequest tLaws) throws Exception {
        LambdaQueryWrapper<TLaws> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(TLaws::getName,tLaws.getName()).last("limit 1");
        TLaws old = this.getOne(queryWrapper);
        //判断之前是否有相同名字的法律法规

        if (old != null){
            //判断版本号是否重复
            if(old.getVersion().equals(tLaws.getVersion()))
            {
                throw new  RuntimeException("存在历史版本号");
            }
            //更新相同名字的记录
            TLaws newLaws =new TLaws();
            BeanUtils.copyProperties(tLaws,newLaws);
            newLaws.setId(old.getId());
            newLaws.setIsFiling(0);
            baseMapper.updateById(newLaws);
            if(old.getIsFiling()==0){
                //之前未归档过归档过
                //进行修改
                // 将现存数据移至历史
                TLawsRecord saveData =new TLawsRecord();
                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);
                // 通信法律法规文件夹
                TArchivesRequest tArchivesRequest =new TArchivesRequest();
                tArchivesRequest.setParentId(106L);
                tArchivesRequest.setFileSize(old.getFileSize());
                tArchivesRequest.setOriginalFilename(old.getFileName());
                tArchivesRequest.setFileUrl(old.getFileUrl());
                tArchivesRequest.setCurFilename(old.getName()+"_"+old.getVersion());
                tArchivesRequest.setType("3");
                tArchivesRequest.setArchiveType("1");
                tArchivesService.add(tArchivesRequest);
            }
        }else {
            //在历史库中查询版本号是否重复
            LambdaQueryWrapper<TLawsRecord> queryWrapperHis = new LambdaQueryWrapper<>();
            queryWrapperHis.eq(TLawsRecord::getName,tLaws.getName()).eq(TLawsRecord::getVersion,tLaws.getVersion());
            long count = this.count(queryWrapper);
            if (count>0){
                throw new  RuntimeException("存在历史版本号");
            }
            //进行新增数据
            TLaws data =new TLaws();
            BeanUtils.copyProperties(tLaws,data);
            data.setCode(generateRandomString());
            data.setCreator(SecurityFrameworkUtils.getLoginUserNickname());
            baseMapper.insert(data);
        }
//        // 通信法律法规文件夹
//        TArchivesRequest tArchivesRequest =new TArchivesRequest();
//        tArchivesRequest.setParentId(106L);
//        tArchivesRequest.setFileSize(tLaws.getFileSize());
//        tArchivesRequest.setOriginalFilename(tLaws.getFileName());
//        tArchivesRequest.setFileUrl(tLaws.getFileUrl());
//        tArchivesRequest.setCurFilename(tLaws.getName());
//        tArchivesRequest.setType("3");
//        tArchivesRequest.setArchiveType("0");
//        tArchivesService.add(tArchivesRequest);
        return Result.success();

    }


    public Result updateByTLId(TLawsRequest tLaws) throws Exception {
        TLaws old = this.getById(tLaws.getId());
        if (old != null){
            //判断是否修改了文件名称
            old.setFileName(tLaws.getFileName());
            old.setFileSize(tLaws.getFileSize());
            old.setFileUrl(tLaws.getFileUrl());
            old.setDescribeInfo(tLaws.getDescribeInfo());
            old.setType(tLaws.getType());
            baseMapper.updateById(old);
//            // 通信法律法规文件夹
//            TArchivesRequest tArchivesRequest =new TArchivesRequest();
//            tArchivesRequest.setParentId(106L);
//            tArchivesRequest.setFileSize(old.getFileSize());
//            tArchivesRequest.setOriginalFilename(old.getFileName());
//            tArchivesRequest.setFileUrl(old.getFileUrl());
//            tArchivesRequest.setCurFilename(old.getName());
//            tArchivesRequest.setType("3");
//            tArchivesRequest.setArchiveType("0");
//            tArchivesService.add(tArchivesRequest);
            return Result.success();
        }else {
            return Result.error(CodeEnum.TARCHIVES_SELECT_FAILED.getCode(),CodeEnum.TARCHIVES_SELECT_FAILED.getMsg());
        }

    }

    public List<TLaws> history(TLawsRequest tLaws) {
        LambdaQueryWrapper<TLaws> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TLaws::getName,tLaws.getName());
        queryWrapper.eq(TLaws::getDeleted,"1");
        queryWrapper.orderByDesc(TLaws::getCreateTime);

        return baseMapper.selectList(queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    public void filing(long id) throws Exception {
        // 归档操作
        baseMapper.filling(id);
        TLaws old = getById(id);
        // 将现存数据移至历史
        TLawsRecord saveData =new TLawsRecord();
        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);
        // 通信法律法规文件夹
        TArchivesRequest tArchivesRequest =new TArchivesRequest();
        tArchivesRequest.setParentId(106L);
        tArchivesRequest.setFileSize(old.getFileSize());
        tArchivesRequest.setOriginalFilename(old.getFileName());
        tArchivesRequest.setFileUrl(old.getFileUrl());
        tArchivesRequest.setCurFilename(old.getName()+"_"+old.getVersion());
        tArchivesRequest.setType("3");
        tArchivesRequest.setArchiveType("1");
        tArchivesService.add(tArchivesRequest);
    }


    public void archiveFolder() {

    }

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

    /**
     * 逻辑删除数据
     * @param ids
     */
    @Transactional(rollbackFor = Exception.class)
    public Result delete(List<Long> ids) {
        int flag = 0;
        for (Long id : ids) {
            LambdaQueryWrapper<TLawsRecord> queryWrapper =new LambdaQueryWrapper<>();
            queryWrapper.eq(TLawsRecord::getLawsId,id);
            //同步删除归档记录
            List<TLawsRecord> records = recordService.list(queryWrapper);
            for (TLawsRecord record : records) {
                //同步删除档案管理中的文件
                TArchivesRequest tArchivesRequest =new TArchivesRequest();
                tArchivesRequest.setParentId(106L);
                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 boolean isFilling(long id){
        if (baseMapper.judgeIsFilling(id) == 1){
            //已经归档，不可预览
            return true;
        }else {
            //未归档，可以预览
            return false;
        }


    }


    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();
    }

    //===========app
    public IPage selectForApp(Page<TLaws> page, TLawsRequest tLaws) throws ParseException {
        tLaws.setCreateTimeStr(DateUtil.format(tLaws.getCreateTime(),"yyyy-MM-dd"));
        IPage<TLaws> tLawsIPage = baseMapper.selectForApp(page, tLaws);
        List<TLaws> records = tLawsIPage.getRecords();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        for (TLaws record : records) {
            String format = simpleDateFormat.format(record.getCreateTime());
            Date date = simpleDateFormat.parse(format);
        }
        return tLawsIPage;
    }

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

    public Result addForApp(TLawsRequest tLaws) throws Exception {
        LambdaQueryWrapper<TLaws> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(TLaws::getName,tLaws.getName()).last("limit 1");
        TLaws old = this.getOne(queryWrapper);
        //判断之前是否有相同名字的法律法规

        if (old != null){
            //判断版本号是否重复
            if(old.getVersion().equals(tLaws.getVersion()))
            {
                throw new  RuntimeException("存在历史版本号");
            }
            //更新相同名字的记录
            TLaws newLaws =new TLaws();
            BeanUtils.copyProperties(tLaws,newLaws);
            newLaws.setId(old.getId());
            newLaws.setIsFiling(0);
            baseMapper.updateById(newLaws);
            if(old.getIsFiling()==0){
                //之前未归档过归档过
                //进行修改
                // 将现存数据移至历史
                TLawsRecord saveData =new TLawsRecord();
                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);
                // 通信法律法规文件夹
                TArchivesRequest tArchivesRequest =new TArchivesRequest();
                tArchivesRequest.setParentId(106L);
                tArchivesRequest.setFileSize(old.getFileSize());
                tArchivesRequest.setOriginalFilename(old.getFileName());
                tArchivesRequest.setFileUrl(old.getFileUrl());
                tArchivesRequest.setCurFilename(old.getName()+"_"+old.getVersion());
                tArchivesRequest.setType("3");
                tArchivesRequest.setArchiveType("1");
                tArchivesService.add(tArchivesRequest);
            }
        }else {
            //在历史库中查询版本号是否重复
            LambdaQueryWrapper<TLawsRecord> queryWrapperHis = new LambdaQueryWrapper<>();
            queryWrapperHis.eq(TLawsRecord::getName,tLaws.getName()).eq(TLawsRecord::getVersion,tLaws.getVersion());
            long count = this.count(queryWrapper);
            if (count>0){
                throw new  RuntimeException("存在历史版本号");
            }
            //进行新增数据
            TLaws data =new TLaws();
            BeanUtils.copyProperties(tLaws,data);
            data.setCode(generateRandomString());
            data.setCreator(SecurityFrameworkUtils.getLoginUserNickname());
            baseMapper.insert(data);
        }
        // 通信法律法规文件夹
        TArchivesRequest tArchivesRequest =new TArchivesRequest();
        tArchivesRequest.setParentId(106L);
        tArchivesRequest.setFileSize(tLaws.getFileSize());
        tArchivesRequest.setOriginalFilename(tLaws.getFileName());
        tArchivesRequest.setFileUrl(tLaws.getFileUrl());
        tArchivesRequest.setCurFilename(tLaws.getName());
        tArchivesRequest.setType("3");
        tArchivesRequest.setArchiveType("0");
        tArchivesService.add(tArchivesRequest);
        return Result.success();

    }


    public Result updateByTLIdForApp(TLawsRequest tLaws) throws Exception {
        TLaws old = this.getById(tLaws.getId());
        if (old != null){
            //判断是否修改了文件名称
            old.setFileName(tLaws.getFileName());
            old.setFileSize(tLaws.getFileSize());
            old.setFileUrl(tLaws.getFileUrl());
            old.setDescribeInfo(tLaws.getDescribeInfo());
            baseMapper.updateById(old);
            // 通信法律法规文件夹
            TArchivesRequest tArchivesRequest =new TArchivesRequest();
            tArchivesRequest.setParentId(106L);
            tArchivesRequest.setFileSize(old.getFileSize());
            tArchivesRequest.setOriginalFilename(old.getFileName());
            tArchivesRequest.setFileUrl(old.getFileUrl());
            tArchivesRequest.setCurFilename(old.getName());
            tArchivesRequest.setType("3");
            tArchivesRequest.setArchiveType("0");
            tArchivesService.add(tArchivesRequest);
            return Result.success();
        }else {
            return Result.error(CodeEnum.TARCHIVES_SELECT_FAILED.getCode(),CodeEnum.TARCHIVES_SELECT_FAILED.getMsg());
        }

    }

    public List<TLaws> historyForApp(TLawsRequest tLaws) {
        LambdaQueryWrapper<TLaws> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TLaws::getName,tLaws.getName());
        queryWrapper.eq(TLaws::getDeleted,"1");
        queryWrapper.orderByDesc(TLaws::getCreateTime);

        return baseMapper.selectList(queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    public void filingForApp(long id) throws Exception {
        // 归档操作
        baseMapper.filling(id);
        TLaws old = getById(id);
        // 将现存数据移至历史
        TLawsRecord saveData =new TLawsRecord();
        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);
        // 通信法律法规文件夹
        TArchivesRequest tArchivesRequest =new TArchivesRequest();
        tArchivesRequest.setParentId(106L);
        tArchivesRequest.setFileSize(old.getFileSize());
        tArchivesRequest.setOriginalFilename(old.getFileName());
        tArchivesRequest.setFileUrl(old.getFileUrl());
        tArchivesRequest.setCurFilename(old.getName()+"_"+old.getVersion());
        tArchivesRequest.setType("3");
        tArchivesRequest.setArchiveType("1");
        tArchivesService.add(tArchivesRequest);
    }


    public void archiveFolderForApp() {

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


    }

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


    public IPage findAllDocuments(Page<TLaws> page, TLawsRequest tLaws) {
        IPage<TLaws> allDocuments = baseMapper.findAllDocuments(page, tLaws);
        return allDocuments;
    }
}

