package com.chinaweal.aiccs.aiccs.forcedCancellation.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.chinaweal.aiccs.aiccs.abnormal.entity.TSAttachment;
import com.chinaweal.aiccs.aiccs.abnormal.entity.TSWrit;
import com.chinaweal.aiccs.aiccs.abnormal.service.IGzaiccodeService;
import com.chinaweal.aiccs.aiccs.abnormal.service.TSAttachmentService;
import com.chinaweal.aiccs.aiccs.abnormal.service.TSWritService;
import com.chinaweal.aiccs.aiccs.forcedCancellation.entity.ForceLogoutNotice;
import com.chinaweal.aiccs.aiccs.forcedCancellation.entity.ForceLogoutNoticeDetail;
import com.chinaweal.aiccs.aiccs.forcedCancellation.mapper.ForceLogoutNoticeMapper;
import com.chinaweal.aiccs.aiccs.forcedCancellation.service.ForceLogoutNoticeDetailService;
import com.chinaweal.aiccs.aiccs.forcedCancellation.service.ForceLogoutNoticeService;
import com.chinaweal.aiccs.aiccs.revoke.entity.Tsbizrevlist;
import com.chinaweal.aiccs.aiccs.revoke.entity.Tsrevtasklist;
import com.chinaweal.aiccs.aiccs.revoke.service.CreateFileService;
import com.chinaweal.aiccs.aiccs.writs.entity.Tswrittemplate;
import com.chinaweal.aiccs.aiccs.writs.service.TswrittemplateService;
import com.chinaweal.aiccs.common.util.ConstantsUtil;
import com.chinaweal.aiccs.common.util.StringUtils;
import com.chinaweal.aiccs.common.util.WorkNoUtil;
import com.chinaweal.aiccs.org.service.AicorgService;
import com.chinaweal.aicorg.model.AICUser;
import com.chinaweal.youfool.framework.springboot.mybatis.plus.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;

import javax.annotation.Resource;
import java.io.File;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 拟强制注销公告信息表 服务实现类
 * </p>
 *
 * @author lwd
 * @since 2025-10-22
 */
@Service
public class ForceLogoutNoticeServiceImpl extends BaseServiceImpl<ForceLogoutNoticeMapper, ForceLogoutNotice> implements ForceLogoutNoticeService {

    @Autowired
    private ForceLogoutNoticeDetailService forceLogoutNoticeDetailService;
    @Resource
    private IGzaiccodeService gzaiccodeService;
    @Resource
    private TswrittemplateService tswrittemplateService;
    @Resource
    private AicorgService aicorgService;
    @Resource
    private CreateFileService createFileService;
    @Resource
    private TSWritService tsWritService;
    @Resource
    private TSAttachmentService attachmentService;
    @Override
    public IPage<ForceLogoutNotice> page(IPage<ForceLogoutNotice> page, ForceLogoutNotice entity) {
        LambdaQueryWrapper<ForceLogoutNotice> wrapper = Wrappers.lambdaQuery();

        // 构建查询条件
        if (StringUtils.isNotBlank(entity.getBizseqId())) {
            wrapper.eq(ForceLogoutNotice::getBizseqId, entity.getBizseqId());
        }
        if (StringUtils.isNotBlank(entity.getNoticeTitle())) {
            wrapper.like(ForceLogoutNotice::getNoticeTitle, entity.getNoticeTitle());
        }
        if (StringUtils.isNotBlank(entity.getJudAuth())) {
            wrapper.eq(ForceLogoutNotice::getJudAuth, entity.getJudAuth());
        }
        if (entity.getNoticeFrom() != null) {
            wrapper.ge(ForceLogoutNotice::getNoticeFrom, entity.getNoticeFrom());
        }
        if (entity.getNoticeTo() != null) {
            wrapper.le(ForceLogoutNotice::getNoticeTo, entity.getNoticeTo());
        }
        if (StringUtils.isNotBlank(entity.getSExtFromnode())) {
            wrapper.eq(ForceLogoutNotice::getSExtFromnode, entity.getSExtFromnode());
        }

        // 按时间降序排序
        wrapper.orderByDesc(ForceLogoutNotice::getSExtDatetime);

        return page(page, wrapper);
    }

    @Override
    public ForceLogoutNotice getByBizSeqId(String bizseqId) {
        LambdaQueryWrapper<ForceLogoutNotice> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(ForceLogoutNotice::getBizseqId, bizseqId);
        wrapper.orderByDesc(ForceLogoutNotice::getSExtDatetime);
        wrapper.last("limit 1");
        return getOne(wrapper);
    }

    @Override
    public List<ForceLogoutNotice> getByNoticeTitle(String noticeTitle) {
        LambdaQueryWrapper<ForceLogoutNotice> wrapper = Wrappers.lambdaQuery();
        wrapper.like(ForceLogoutNotice::getNoticeTitle, noticeTitle);
        wrapper.orderByDesc(ForceLogoutNotice::getSExtDatetime);
        return list(wrapper);
    }

    @Override
    public List<ForceLogoutNotice> getByJudAuth(String judAuth) {
        LambdaQueryWrapper<ForceLogoutNotice> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(ForceLogoutNotice::getJudAuth, judAuth);
        wrapper.orderByDesc(ForceLogoutNotice::getSExtDatetime);
        return list(wrapper);
    }

    @Override
    public List<ForceLogoutNotice> getByNoticeDateRange(LocalDate noticeFrom, LocalDate noticeTo) {
        LambdaQueryWrapper<ForceLogoutNotice> wrapper = Wrappers.lambdaQuery();
        wrapper.ge(ForceLogoutNotice::getNoticeFrom, noticeFrom);
        wrapper.le(ForceLogoutNotice::getNoticeTo, noticeTo);
        wrapper.orderByDesc(ForceLogoutNotice::getSExtDatetime);
        return list(wrapper);
    }

    @Override
    public List<ForceLogoutNotice> getBySExtFromnode(String sExtFromnode) {
        LambdaQueryWrapper<ForceLogoutNotice> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(ForceLogoutNotice::getSExtFromnode, sExtFromnode);
        wrapper.orderByDesc(ForceLogoutNotice::getSExtDatetime);
        return list(wrapper);
    }

    @Override
    @Transactional
    public boolean updateNoticePeriod(String forceId, LocalDate noticeFrom, LocalDate noticeTo) {
        ForceLogoutNotice entity = new ForceLogoutNotice();
        entity.setForceId(forceId);
        entity.setNoticeFrom(noticeFrom);
        entity.setNoticeTo(noticeTo);
        return updateById(entity);
    }

    @Override
    public List<ForceLogoutNotice> getValidNotices(LocalDate currentDate) {
        LambdaQueryWrapper<ForceLogoutNotice> wrapper = Wrappers.lambdaQuery();
        wrapper.le(ForceLogoutNotice::getNoticeFrom, currentDate);
        wrapper.ge(ForceLogoutNotice::getNoticeTo, currentDate);
        wrapper.orderByDesc(ForceLogoutNotice::getSExtDatetime);
        return list(wrapper);
    }

    @Override
    public List<ForceLogoutNotice> getByJudAuthAndDateRange(String judAuth, LocalDate startDate, LocalDate endDate) {
        LambdaQueryWrapper<ForceLogoutNotice> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(ForceLogoutNotice::getJudAuth, judAuth);
        wrapper.ge(ForceLogoutNotice::getNoticeFrom, startDate);
        wrapper.le(ForceLogoutNotice::getNoticeTo, endDate);
        wrapper.orderByDesc(ForceLogoutNotice::getSExtDatetime);
        return list(wrapper);
    }

    @Override
    @Transactional
    public boolean batchUpdateNoticeContent(List<String> forceIds, String noticeTitle, String noticeContent) {
        if (forceIds == null || forceIds.isEmpty()) {
            return false;
        }

        for (String forceId : forceIds) {
            ForceLogoutNotice entity = new ForceLogoutNotice();
            entity.setForceId(forceId);
            entity.setNoticeTitle(noticeTitle);
            entity.setNoticeContent(noticeContent);
            if (!updateById(entity)) {
                return false;
            }
        }
        return true;
    }

    @Override
    public void deactivationNotice(String bizseq, AICUser loginUser, Tsbizrevlist tsbizrevlist, Tsrevtasklist taskList) {
        //生成注销公告书
        LocalDateTime now = LocalDateTime.now();
        LocalDate currentDate = LocalDate.now();
        // 获取90天后的日期（LocalDate类型）
        LocalDate futureDate = currentDate.plusDays(90);
        // 获取年份
        int yeara = futureDate.getYear();
        // 获取月份 (1-12)
        int montha = futureDate.getMonthValue();
        // 获取日期 (1-31)
        int daya = futureDate.getDayOfMonth();
        Map<String, Object> map = new HashMap<>();
        map.put("year", now.getYear());
        map.put("month", now.getMonthValue());
        map.put("day", now.getDayOfMonth());
        map.put("yeara", yeara);
        map.put("montha", montha);
        map.put("daya", daya);
        // 文书内容
        LambdaQueryWrapper<Tswrittemplate> wrapperws = new LambdaQueryWrapper<>();
        wrapperws.eq(Tswrittemplate::getBizseq, bizseq)
                .eq(Tswrittemplate::getIsTemplate, "0")
                .eq(Tswrittemplate::getWritsType, WorkNoUtil.WORKNOTYPE_64);
        Tswrittemplate tswrittemplatews = tswrittemplateService.getOne(wrapperws);
        String content = tswrittemplatews.getContent();
        String userOrgCode = aicorgService.getRegionCodeByUser(loginUser);
        String areaName = ConstantsUtil.getAreaName(userOrgCode);
        String decOrgName = gzaiccodeService.getNameByCode(userOrgCode);

        map.put("noAttach", "noAttach");

        map.put("htmlContent", content);

        // 生成文书号
        TSWrit tsWritModel = new TSWrit();
        tsWritModel.setWritsid(UUID.randomUUID().toString());
        String workNoType = WorkNoUtil.WORKNOTYPE_64;
        tsWritModel.setBizseq(bizseq);
        tsWritModel.setAreaCode(userOrgCode);
        tsWritModel.setWritsno("");
        tsWritModel.setWritstype(workNoType);
        tsWritModel.setPripid("");
        tsWritModel.setWritsname(WorkNoUtil.getWorkNoTypeName(workNoType));
        tsWritModel.setCreatetime(now);
        tsWritModel.setContent(tswrittemplateService.contentFormatter(content));

        int startIndex = 2; // "关于"的长度
        int endIndex = taskList.getBusname().length() - 5; // "的批量注销"的长度
        map.put("areaName", tsbizrevlist.getHandleOrgCn());
        map.put("userName", loginUser.getName());
        map.put("tel", loginUser.getEname());
        map.put("entname", taskList.getBusname().substring(startIndex, endIndex).trim());


        String fileName = taskList.getBusname().substring(startIndex, endIndex).trim() + "-拟强制注销公司登记公告";
        String path;
        if (!userOrgCode.equals("440115") && !userOrgCode.equals("440110")) {
            path = "static" + File.separator + "template" + File.separator + "forceLogoutNotice.docx";
        } else {
            path = "static" + File.separator + "template" + File.separator + "forceLogoutNotice.docx";
        }
        String pdfPath = createFileService.createPdfZx(bizseq, fileName, "64", path, map);

        // 验证PDF文件是否成功生成
        if (pdfPath == null || pdfPath.trim().isEmpty()) {
            throw new RuntimeException("PDF文件生成失败，返回路径为空");
        }

        // 更新文书、企业、附件信息 isCancelNotice
        LambdaUpdateWrapper<ForceLogoutNoticeDetail> updateWrapper = new LambdaUpdateWrapper<>();

        updateWrapper.eq(ForceLogoutNoticeDetail::getBizseqId, bizseq);

        ForceLogoutNoticeDetail updateEntity = new ForceLogoutNoticeDetail();
        updateEntity.setIsCancelNotice("1");
        updateEntity.setStatus("2");
        updateEntity.setIntosponsor(loginUser.getName());
        updateEntity.setIntosponsorId(loginUser.getPrimaryKey());
        updateEntity.setRemHandler(loginUser.getName());
        updateEntity.setIsDecisionPublish("0");
        updateEntity.setHandleOrg(tsbizrevlist.getHandleOrg());
        updateEntity.setHandleOrgCn(tsbizrevlist.getHandleOrgCn());
        updateEntity.setAnnDate(LocalDate.now());
        updateEntity.setNoticeFrom(currentDate);
        updateEntity.setNoticeTo(futureDate);

        boolean affectedRows = forceLogoutNoticeDetailService.update(updateEntity, updateWrapper);
        tsWritModel.setPath(pdfPath);

        TSAttachment attachmentModel = new TSAttachment();
        attachmentModel.setAttachmentid(bizseq);
        attachmentModel.setTemppath(pdfPath);

        tsWritService.save(tsWritModel);
        attachmentService.updateById(attachmentModel);
    }
}
