package com.storlead.trade.service.impl;

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 com.storlead.trade.dto.SopDetailCreateDTO;
import com.storlead.trade.dto.SopDetailResponseDTO;
import com.storlead.trade.dto.SopDetailUpdateDTO;
import com.storlead.trade.dto.SopResponseDTO;
import com.storlead.trade.entity.SopDetailEntity;
import com.storlead.trade.entity.SopEntity;
import com.storlead.trade.mapper.SopMapper;
import com.storlead.trade.service.SopDetailService;
import com.storlead.trade.service.SopService;
import com.storlead.framework.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * SOP Service实现类
 */
@Slf4j
@Service
public class SopServiceImpl extends ServiceImpl<SopMapper, SopEntity> implements SopService {

    @Resource
    private SopDetailService sopDetailService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Object> createSop(String name, List<SopDetailCreateDTO> details) {
        boolean isOk = false;
        // 1. 创建SOP主表
        SopEntity sop = new SopEntity();
        sop.setName(name);
        isOk = save(sop);

        // 2. 批量创建SOP明细
        if (details != null && !details.isEmpty()) {
            List<SopDetailEntity> detailEntities = details.stream().map(dto -> {
                SopDetailEntity detail = new SopDetailEntity();
                BeanUtils.copyProperties(dto, detail);
                detail.setSopId(sop.getId());
                return detail;
            }).collect(Collectors.toList());

            isOk = sopDetailService.saveBatch(detailEntities);
        }

        if(!isOk){
            return Result.error("创建失败");
        }
        return Result.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSop(Long id, String name, List<SopDetailUpdateDTO> details) {
        // 1. 更新SOP主表
        SopEntity sop = getById(id);
        if (sop == null) {
            throw new RuntimeException("SOP不存在，ID: " + id);
        }
        sop.setName(name);
        updateById(sop);

        // 2. 删除旧的明细，重新插入新的明细
        LambdaQueryWrapper<SopDetailEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SopDetailEntity::getSopId, id);
        sopDetailService.remove(wrapper);

        // 3. 批量创建新的明细
        if (details != null && !details.isEmpty()) {
            List<SopDetailEntity> detailEntities = details.stream().map(dto -> {
                SopDetailEntity detail = new SopDetailEntity();
                BeanUtils.copyProperties(dto, detail);
                detail.setSopId(id);
                return detail;
            }).collect(Collectors.toList());

            sopDetailService.saveBatch(detailEntities);
        }

        log.info("更新SOP成功，ID: {}", id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteSop(Long id) {
        // 1. 删除SOP明细
        LambdaQueryWrapper<SopDetailEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SopDetailEntity::getSopId, id);
        sopDetailService.remove(wrapper);

        // 2. 删除SOP主表
        removeById(id);

        log.info("删除SOP成功，ID: {}", id);
    }

    @Override
    public SopResponseDTO getSopDetail(Long id) {
        SopResponseDTO response = new SopResponseDTO();

        // 1. 查询SOP主表
        SopEntity sop = getById(id);
        if (sop == null) {
            throw new RuntimeException("SOP不存在，ID: " + id);
        }
        BeanUtils.copyProperties(sop, response);

        // 2. 查询SOP明细
        LambdaQueryWrapper<SopDetailEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SopDetailEntity::getSopId, id);
        wrapper.orderByAsc(SopDetailEntity::getStep);
        List<SopDetailEntity> details = sopDetailService.list(wrapper);

        // 3. 转换明细
        List<SopDetailResponseDTO> detailResponses = details.stream().map(detail -> {
            SopDetailResponseDTO dto = new SopDetailResponseDTO();
            BeanUtils.copyProperties(detail, dto);
            return dto;
        }).collect(Collectors.toList());

        response.setDetails(detailResponses);

        return response;
    }

    @Override
    public IPage<SopResponseDTO> listSopPage(SopResponseDTO dto) {
        Integer pageIndex = dto.getPageIndex();
        Integer pageSize = dto.getPageSize();
        String name = dto.getName();
        // 1. 分页查询SOP主表
        Page<SopEntity> page = new Page<>(pageIndex, pageSize);
        LambdaQueryWrapper<SopEntity> wrapper = new LambdaQueryWrapper<>();
        if (name != null && !name.trim().isEmpty()) {
            wrapper.like(SopEntity::getName, name);
        }
        wrapper.orderByDesc(SopEntity::getCreateTime);
        IPage<SopEntity> sopPage = page(page, wrapper);

        // 2. 转换为响应DTO
        IPage<SopResponseDTO> responsePage = new Page<>(pageIndex, pageSize, sopPage.getTotal());
        List<SopResponseDTO> records = sopPage.getRecords().stream().map(sop -> {
            SopResponseDTO sopResponseDTO = new SopResponseDTO();
            BeanUtils.copyProperties(sop, sopResponseDTO);
            return sopResponseDTO;
        }).collect(Collectors.toList());
        responsePage.setRecords(records);

        return responsePage;
    }
}
