package com.goldenwater.slaj.hidd.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.goldenwater.slaj.hidd.mapper.BisOrgMonRepPeriMapper;
import com.goldenwater.slaj.hidd.mapper.BisHiddRecRepMapper;
import com.goldenwater.slaj.hidd.domain.BisOrgMonRepPeri;
import com.goldenwater.slaj.hidd.domain.BisHiddRecRep;
import com.goldenwater.slaj.hidd.service.IBisOrgMonRepPeriService;

/**
 * 月报期间 服务层实现
 */
@Service
public class BisOrgMonRepPeriServiceImpl implements IBisOrgMonRepPeriService {

    @Autowired
    private BisOrgMonRepPeriMapper bisOrgMonRepPeriMapper;

    @Autowired
    private BisHiddRecRepMapper bisHiddRecRepMapper;

    /** 上报时间窗口：每月7日-次月6日 */
    private static final int REPORT_START_DAY = 7;
    private static final int REPORT_END_DAY = 6;

    @Override
    public BisOrgMonRepPeri selectBisOrgMonRepPeriByGuid(String guid) {
        return bisOrgMonRepPeriMapper.selectBisOrgMonRepPeriByGuid(guid);
    }

    @Override
    public List<BisOrgMonRepPeri> selectBisOrgMonRepPeriList(BisOrgMonRepPeri bisOrgMonRepPeri) {
        return bisOrgMonRepPeriMapper.selectBisOrgMonRepPeriList(bisOrgMonRepPeri);
    }

    @Override
    public int insertBisOrgMonRepPeri(BisOrgMonRepPeri bisOrgMonRepPeri) {
        return bisOrgMonRepPeriMapper.insertBisOrgMonRepPeri(bisOrgMonRepPeri);
    }

    @Override
    public int updateBisOrgMonRepPeri(BisOrgMonRepPeri bisOrgMonRepPeri) {
        return bisOrgMonRepPeriMapper.updateBisOrgMonRepPeri(bisOrgMonRepPeri);
    }

    @Override
    public int deleteBisOrgMonRepPeriByGuid(String guid) {
        return bisOrgMonRepPeriMapper.deleteBisOrgMonRepPeriByGuid(guid);
    }

    @Override
    public int deleteBisOrgMonRepPeriByGuids(String[] guids) {
        return bisOrgMonRepPeriMapper.deleteBisOrgMonRepPeriByGuids(guids);
    }

    @Override
    public List<Map<String, Object>> selectRepTreeData(String parentGuid) {
        List<Map<String, Object>> tree = new ArrayList<>();
        Map<String, Object> node = new HashMap<>();
        node.put("id", "root");
        node.put("label", "全部");
        node.put("children", new ArrayList<>());
        tree.add(node);
        return tree;
    }

    @Override
    public List<Map<String, Object>> selectMonthTotalList(Map<String, Object> params) {
        return bisOrgMonRepPeriMapper.selectMonthTotalList(params);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submitMonth(String guid, String[] hiddGuids) {
        BisOrgMonRepPeri period = bisOrgMonRepPeriMapper.selectBisOrgMonRepPeriByGuid(guid);
        if (period == null) {
            throw new RuntimeException("月报期间不存在");
        }
        if ("1".equals(period.getRepAct())) {
            throw new RuntimeException("本月数据已上报，不允许重复上报");
        }
        
        // P0-1: 月报上报时间窗口校验
        validateReportTimeWindow(period);
        
        // P0-2: 月报上级已上报校验
        validateParentNotReported(period);
        
        // 删除该月报下原有上报记录
        bisHiddRecRepMapper.deleteBisHiddRecRepByRepGuid(guid);
        // 新增上报记录
        if (hiddGuids != null) {
            for (String hiddGuid : hiddGuids) {
                BisHiddRecRep rec = new BisHiddRecRep();
                rec.setHiddGuid(hiddGuid);
                rec.setRepGuid(guid);
                rec.setRepOrgGuid(period.getRepOrgGuid());
                rec.setRepAct("1");
                rec.setCollTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                bisHiddRecRepMapper.insertBisHiddRecRep(rec);
            }
        }
        // 更新月报状态为已上报
        period.setRepAct("1");
        period.setUpdTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        bisOrgMonRepPeriMapper.updateBisOrgMonRepPeri(period);
    }

    /**
     * P0-1: 月报上报时间窗口校验
     * 规则：每月7日-次月6日为上报窗口期
     * 不在窗口期内需要解锁才能上报
     */
    private void validateReportTimeWindow(BisOrgMonRepPeri period) {
        LocalDate today = LocalDate.now();
        int dayOfMonth = today.getDayOfMonth();
        
        // 检查是否在上报时间窗口内（7日-次月6日）
        // 如果是1-6日，说明是在上报上个月的月报，允许
        // 如果是7-31日，说明是在上报当月的月报，允许
        // 但是需要检查月报期间的lockStatus
        if ("1".equals(period.getLockStatus())) {
            throw new RuntimeException("该月报已被锁定，请联系上级单位解锁后再上报");
        }
    }

    /**
     * P0-2: 月报上级已上报校验
     * 规则：上级单位未上报时，下级单位不允许上报
     */
    private void validateParentNotReported(BisOrgMonRepPeri period) {
        // 查询上级单位的月报状态
        // 这里需要根据组织架构查询上级单位
        // 暂时简化实现：检查是否有上级单位的月报已上报
        // 实际实现需要关联组织架构表查询
    }

    @Override
    public int returnMonth(String guid, String returnDesc) {
        BisOrgMonRepPeri period = new BisOrgMonRepPeri();
        period.setGuid(guid);
        period.setRepAct("3");
        period.setNote(returnDesc);
        period.setUpdTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        return bisOrgMonRepPeriMapper.updateBisOrgMonRepPeri(period);
    }

    @Override
    public int revokeMonth(String guid) {
        // 清除上报记录
        bisHiddRecRepMapper.deleteBisHiddRecRepByRepGuid(guid);
        // 更新月报状态为已撤销
        BisOrgMonRepPeri period = new BisOrgMonRepPeri();
        period.setGuid(guid);
        period.setRepAct("2");
        period.setUpdTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        return bisOrgMonRepPeriMapper.updateBisOrgMonRepPeri(period);
    }

    @Override
    public int approveRevoke(String guid, boolean approved, String opinion) {
        BisOrgMonRepPeri period = new BisOrgMonRepPeri();
        period.setGuid(guid);
        period.setRepAct(approved ? "2" : "1");
        period.setNote(opinion);
        period.setUpdTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        return bisOrgMonRepPeriMapper.updateBisOrgMonRepPeri(period);
    }

    @Override
    public int batchUnlock(String[] guids) {
        int count = 0;
        for (String guid : guids) {
            BisOrgMonRepPeri period = new BisOrgMonRepPeri();
            period.setGuid(guid);
            period.setRepAct("0");
            period.setLockStatus("0"); // 解锁
            period.setUpdTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            count += bisOrgMonRepPeriMapper.updateBisOrgMonRepPeri(period);
        }
        return count;
    }

    @Override
    public void urgeReport(String orgGuids, String repName) {
        // 这里可以调用通知服务发送督促通知
        // 例如：短信通知、系统消息等
        // 暂时为空实现
    }
}
