package com.zksy.dispatch.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zksy.dispatch.domain.DisEventPlan;
import com.zksy.dispatch.domain.DisPlanApproval;
import com.zksy.dispatch.dto.DisPlanApprovalPageDTO;
import com.zksy.dispatch.mapper.DisEventPlanMapper;
import com.zksy.dispatch.mapper.DisPlanApprovalMapper;
import com.zksy.dispatch.service.DisPlanApprovalService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Slf4j
@Service
public class DisPlanApprovalServiceImpl extends ServiceImpl<DisPlanApprovalMapper, DisPlanApproval>
        implements DisPlanApprovalService {

    @Autowired
    private DisEventPlanMapper planMapper;

    /** 状态常量 */
    private static final String STATUS_EDITING = "编辑中";
    private static final String STATUS_APPROVING = "审批中";
    private static final String STATUS_FINAL_APPROVING = "终审中";
    private static final String STATUS_PUBLISHED = "已发布";
    private static final String STATUS_REVISE = "待修正";

    @Override
    public Page<DisPlanApproval> findByPage(DisPlanApprovalPageDTO dto) {
        Page<DisPlanApproval> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        LambdaQueryWrapper<DisPlanApproval> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(dto.getPlanName() != null && !dto.getPlanName().isEmpty(), DisPlanApproval::getPlanName, dto.getPlanName());
        wrapper.eq(dto.getPlanType() != null && !dto.getPlanType().isEmpty(), DisPlanApproval::getPlanType, dto.getPlanType());
        wrapper.eq(dto.getStatus() != null && !dto.getStatus().isEmpty(), DisPlanApproval::getStatus, dto.getStatus());
        wrapper.orderByDesc(DisPlanApproval::getCreateTime);
        return this.page(page, wrapper);
    }

    @Override
    public boolean submitForApproval(Long id) {
        DisPlanApproval approval = this.getById(id);
        if (approval == null) {
            log.warn("审批记录不存在, id={}", id);
            return false;
        }
        if (!STATUS_EDITING.equals(approval.getStatus()) && !STATUS_REVISE.equals(approval.getStatus())) {
            log.warn("当前状态不允许提交审批, id={}, status={}", id, approval.getStatus());
            return false;
        }
        approval.setStatus(STATUS_APPROVING);
        approval.setSubmitTime(LocalDateTime.now());
        return this.updateById(approval);
    }

    @Override
    public boolean approve(Long id, String opinion) {
        DisPlanApproval approval = this.getById(id);
        if (approval == null) {
            log.warn("审批记录不存在, id={}", id);
            return false;
        }
        if (!STATUS_APPROVING.equals(approval.getStatus())) {
            log.warn("当前状态不允许审批, id={}, status={}", id, approval.getStatus());
            return false;
        }
        approval.setStatus(STATUS_FINAL_APPROVING);
        String record = buildAuditRecord(approval.getAuditRecord(), "初审通过", opinion);
        approval.setAuditRecord(record);
        return this.updateById(approval);
    }

    @Override
    public boolean reject(Long id, String opinion) {
        DisPlanApproval approval = this.getById(id);
        if (approval == null) {
            log.warn("审批记录不存在, id={}", id);
            return false;
        }
        if (!STATUS_APPROVING.equals(approval.getStatus()) && !STATUS_FINAL_APPROVING.equals(approval.getStatus())) {
            log.warn("当前状态不允许驳回, id={}, status={}", id, approval.getStatus());
            return false;
        }
        approval.setStatus(STATUS_REVISE);
        String record = buildAuditRecord(approval.getAuditRecord(), "驳回", opinion);
        approval.setAuditRecord(record);
        return this.updateById(approval);
    }

    @Override
    public boolean publish(Long id, String opinion) {
        DisPlanApproval approval = this.getById(id);
        if (approval == null) {
            log.warn("审批记录不存在, id={}", id);
            return false;
        }
        if (!STATUS_FINAL_APPROVING.equals(approval.getStatus())) {
            log.warn("当前状态不允许发布, id={}, status={}", id, approval.getStatus());
            return false;
        }
        approval.setStatus(STATUS_PUBLISHED);
        approval.setApproveTime(LocalDateTime.now());
        String record = buildAuditRecord(approval.getAuditRecord(), "终审通过-已发布", opinion);
        approval.setAuditRecord(record);
        return this.updateById(approval);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean createFromPlan(Long planId) {
        DisEventPlan plan = planMapper.selectById(planId);
        if (plan == null) {
            log.warn("预案不存在, planId={}", planId);
            return false;
        }
        DisPlanApproval approval = new DisPlanApproval();
        approval.setPlanId(plan.getId());
        approval.setPlanName(plan.getPlanName());
        approval.setPlanType(plan.getPlanType());
        approval.setPlanLevel(plan.getPlanLevel());
        approval.setVersion(plan.getVersion());
        approval.setStatus(STATUS_APPROVING);
        approval.setSubmitTime(LocalDateTime.now());
        this.save(approval);

        // 更新预案状态为审批中
        plan.setStatus("审批中");
        plan.setUpdateTime(LocalDateTime.now());
        planMapper.updateById(plan);
        return true;
    }

    /**
     * 构建审批记录文本，每条记录用换行分隔
     */
    private String buildAuditRecord(String existingRecord, String action, String opinion) {
        String time = LocalDateTime.now().toString().replace("T", " ");
        String newRecord = "[" + time + "] " + action;
        if (opinion != null && !opinion.isEmpty()) {
            newRecord += "：" + opinion;
        }
        if (existingRecord == null || existingRecord.isEmpty()) {
            return newRecord;
        }
        return existingRecord + "\n" + newRecord;
    }
}
