package com.srs.diagnostic.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.srs.common.core.domain.AjaxResult;
import com.srs.common.utils.DateUtils;
import com.srs.diagnostic.domain.DiaReportItems;
import com.srs.diagnostic.domain.DiaReportRelease;
import com.srs.diagnostic.mapper.DiaReportReleaseMapper;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import com.srs.diagnostic.mapper.DiaReportStandardsMapper;
import com.srs.diagnostic.domain.DiaReportStandards;
import com.srs.diagnostic.service.IDiaReportStandardsService;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import static com.srs.common.utils.DateUtils.getNowDate;
import static com.srs.common.utils.SecurityUtils.getDeptId;
import static com.srs.common.utils.SecurityUtils.getUsername;

/**
 * 诊断报告标准Service业务层处理
 *
 * @author LSD
 * @date 2025-06-21
 */
@Service
public class DiaReportStandardsServiceImpl extends ServiceImpl<DiaReportStandardsMapper,DiaReportStandards> implements IDiaReportStandardsService {
    @Autowired
    private DiaReportStandardsMapper diaReportStandardsMapper;

    @Autowired
    private DiaReportReleaseMapper diaReportReleaseMapper;

    @Autowired
    public PlatformTransactionManager transactionManager;

    @Override
    public List<Map<String, Object>> countGradeItemFinishNumByRelId(DiaReportStandards params) {
        return diaReportStandardsMapper.countGradeItemFinishNumByRelId(params);
    }

    @Override
    public List<Map<String, Object>> countGradeFinishNumByRelId(DiaReportStandards params) {
        return diaReportStandardsMapper.countGradeFinishNumByRelId(params);
    }

    @Override
    public List<Map<String, Object>> countClassItemFinishNumByRelId(DiaReportStandards params) {
        return diaReportStandardsMapper.countClassItemFinishNumByRelId(params);
    }

    @Override
    public List<Map<String, Object>> countClassFinishNumByRelId(DiaReportStandards params) {
        return diaReportStandardsMapper.countClassFinishNumByRelId(params);
    }

    @Override
    public List<Map<String, Object>> countMajorItemFinishNumByRelId(DiaReportStandards params) {
        return diaReportStandardsMapper.countMajorItemFinishNumByRelId(params);
    }

    @Override
    public List<Map<String, Object>> countMajorFinishNumByRelId(DiaReportStandards params) {
        return diaReportStandardsMapper.countMajorFinishNumByRelId(params);
    }

    @Override
    public List<Map<String, Object>> countDeptFinishNumByRelId(DiaReportStandards params) {
        return diaReportStandardsMapper.countDeptFinishNumByRelId(params);
    }

    @Override
    public List<Map<String, Object>> countDeptItemFinishNumByRelId(DiaReportStandards params) {
        return diaReportStandardsMapper.countDeptItemFinishNumByRelId(params);
    }

    @Override
    public Map<String,Object> countItemFinishNumByRelId(DiaReportStandards param) {
        return diaReportStandardsMapper.countItemFinishNumByRelId(param);
    }

    @Override
    public Map<String, Object> countFinishNumByRelId(DiaReportStandards param){
        return diaReportStandardsMapper.countFinishNumByRelId(param);
    }


    @Override
    public AjaxResult stuEditStandard(List<DiaReportStandards> diaReportStandards){
        TransactionDefinition def = new DefaultTransactionDefinition();
        TransactionStatus status = transactionManager.getTransaction(def);
        try{
            List<DiaReportStandards> needInsertList = new ArrayList<>();
            List<DiaReportStandards> needUpdateList = new ArrayList<>();

            for(DiaReportStandards standard : diaReportStandards){
                standard.setUserName(getUsername());
                standard.setLevel(3);
                QueryWrapper<DiaReportStandards> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("relId",standard.getRelId());
                queryWrapper.eq("itemId",standard.getItemId());
                queryWrapper.eq("level","3");
                queryWrapper.eq("user_name",getUsername());
                DiaReportStandards oldStandard = this.getOne(queryWrapper);
                if(oldStandard == null){
                    standard.setCreateTime(getNowDate());
                    standard.setCreateBy(getUsername());
                    needInsertList.add(standard);
                }else{
                    oldStandard.setUpdateTime(getNowDate());
                    oldStandard.setUpdateBy(getUsername());
                    oldStandard.setUserName(getUsername());
                    oldStandard.setStandardValue(standard.getStandardValue());
                    needUpdateList.add(oldStandard);
                }
            }

            if(!needInsertList.isEmpty()){
                boolean res = this.saveBatch(needInsertList);
                if(!res){
                    throw new Exception("新增失败");
                }
            }

            if(!needUpdateList.isEmpty()){
                boolean res = this.updateBatchById(needUpdateList);
                if(!res){
                    throw new Exception("更新失败");
                }
            }

            transactionManager.commit(status);
            return AjaxResult.success();
        } catch (Exception ex) {
            transactionManager.rollback(status);
            return AjaxResult.error(ex.getMessage());
        }
    }


    @Override
    public AjaxResult xwEditStandard(List<DiaReportStandards> diaReportStandards){
        TransactionDefinition def = new DefaultTransactionDefinition();
        TransactionStatus status = transactionManager.getTransaction(def);
        try{
            List<DiaReportStandards> needInsertList = new ArrayList<>();
            List<DiaReportStandards> needUpdateList = new ArrayList<>();

            for(DiaReportStandards standard : diaReportStandards){
                standard.setUserName(getUsername());
                standard.setLevel(2);
                DiaReportStandards searchQuery = new DiaReportStandards();
                searchQuery.setRelId(standard.getRelId());
                searchQuery.setItemId(standard.getItemId());
                searchQuery.setLevel(2);
                searchQuery.deptId = getDeptId();

                DiaReportStandards oldStandard = diaReportStandardsMapper.selectStandardDept(searchQuery);
                if(oldStandard == null){
                    standard.setCreateTime(getNowDate());
                    standard.setCreateBy(getUsername());
                    needInsertList.add(standard);
                }else{
                    oldStandard.setUpdateTime(getNowDate());
                    oldStandard.setUpdateBy(getUsername());
                    oldStandard.setUserName(getUsername());
                    oldStandard.setStandardValue(standard.getStandardValue());
                    needUpdateList.add(oldStandard);
                }
            }

            if(!needInsertList.isEmpty()){
                boolean res = this.saveBatch(needInsertList);
                if(!res){
                    throw new Exception("新增失败");
                }
            }

            if(!needUpdateList.isEmpty()){
                boolean res = this.updateBatchById(needUpdateList);
                if(!res){
                    throw new Exception("更新失败");
                }
            }

            transactionManager.commit(status);
            return AjaxResult.success();
        } catch (Exception ex) {
            transactionManager.rollback(status);
            return AjaxResult.error(ex.getMessage());
        }
    }


    @Override
    public AjaxResult xgEditStandard(List<DiaReportStandards> diaReportStandards){
        TransactionDefinition def = new DefaultTransactionDefinition();
        TransactionStatus status = transactionManager.getTransaction(def);
        try{
            List<DiaReportStandards> needInsertList = new ArrayList<>();
            List<DiaReportStandards> needUpdateList = new ArrayList<>();

            for(DiaReportStandards standard : diaReportStandards){
                standard.setUserName(getUsername());
                standard.setLevel(1);
                QueryWrapper<DiaReportStandards> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("relId",standard.getRelId());
                queryWrapper.eq("itemId",standard.getItemId());
                queryWrapper.eq("level","1");
                DiaReportStandards oldStandard = this.getOne(queryWrapper);
                if(oldStandard == null){
                    standard.setCreateTime(getNowDate());
                    standard.setCreateBy(getUsername());
                    needInsertList.add(standard);
                }else{
                    oldStandard.setUpdateTime(getNowDate());
                    oldStandard.setUpdateBy(getUsername());
                    oldStandard.setUserName(getUsername());
                    oldStandard.setStandardValue(standard.getStandardValue());
                    needUpdateList.add(oldStandard);
                }
            }

            if(!needInsertList.isEmpty()){
                boolean res = this.saveBatch(needInsertList);
                if(!res){
                    throw new Exception("新增失败");
                }
            }

            if(!needUpdateList.isEmpty()){
                boolean res = this.updateBatchById(needUpdateList);
                if(!res){
                    throw new Exception("更新失败");
                }
            }

            transactionManager.commit(status);
            return AjaxResult.success();
        } catch (Exception ex) {
            transactionManager.rollback(status);
            return AjaxResult.error(ex.getMessage());
        }
    }

    @Override
    public List<DiaReportItems> getItemByReportId(Long reportId) {
        return diaReportStandardsMapper.getItemByReportId(reportId);
    }
    @Override
    public List<DiaReportItems> getXgItemByReportId(Long relId, Long reportId){
        List<DiaReportItems> diaReportItems = diaReportStandardsMapper.getItemByReportId(reportId);
        diaReportItems.forEach(item->{
            QueryWrapper<DiaReportStandards> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("relId",relId);
            queryWrapper.eq("itemId",item.getItemId());
            queryWrapper.eq("level","1");
            DiaReportStandards diaReportStandards = this.getOne(queryWrapper);
            if(diaReportStandards!= null){
                item.xgStandard = diaReportStandards.getStandardValue();
            }
        });
        return diaReportItems;
    }

    @Override
    public List<DiaReportItems> countItemFinishByRelId(Long relId) {
        DiaReportRelease release = diaReportReleaseMapper.selectById(relId);
        if(release == null){
            return new ArrayList<>();
        }
        Long reportId = release.getReportId();
        List<DiaReportItems> diaReportItems = diaReportStandardsMapper.getItemByReportId(reportId);
        diaReportItems.forEach(item->{
            QueryWrapper<DiaReportStandards> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("relId",relId);
            queryWrapper.eq("itemId",item.getItemId());
            queryWrapper.eq("level","1");
            DiaReportStandards diaReportStandards = this.getOne(queryWrapper);
            if(diaReportStandards!= null){
                item.xgStandard = diaReportStandards.getStandardValue();
            }

            DiaReportStandards searchQuery = new DiaReportStandards();
            searchQuery.setRelId(relId);
            searchQuery.setItemId(item.getItemId());
            searchQuery.setLevel(2);
            searchQuery.deptId = getDeptId();
            DiaReportStandards diaReportStandards1 = diaReportStandardsMapper.selectStandardDept(searchQuery);
            if(diaReportStandards1!= null){
                item.xwStandard = diaReportStandards1.getStandardValue();
            }
        });
        return diaReportItems;
    }

    @Override
    public List<DiaReportItems> getXwItemByReportId(Long relId , Long reportId){
        List<DiaReportItems> diaReportItems = diaReportStandardsMapper.getItemByReportId(reportId);
        diaReportItems.forEach(item->{

            QueryWrapper<DiaReportStandards> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("relId",relId);
            queryWrapper.eq("itemId",item.getItemId());
            queryWrapper.eq("level","1");
            DiaReportStandards diaReportStandards = this.getOne(queryWrapper);
            if(diaReportStandards!= null){
                item.xgStandard = diaReportStandards.getStandardValue();
            }

            DiaReportStandards searchQuery = new DiaReportStandards();
            searchQuery.setRelId(relId);
            searchQuery.setItemId(item.getItemId());
            searchQuery.setLevel(2);
            searchQuery.deptId = getDeptId();
            DiaReportStandards diaReportStandards1 = diaReportStandardsMapper.selectStandardDept(searchQuery);
            if(diaReportStandards1!= null){
                item.xwStandard = diaReportStandards1.getStandardValue();
            }
        });
        return diaReportItems;
    }

    @Override
    public List<DiaReportItems> getStuItemByReportId(Long deptId,Long relId , Long reportId){
        List<DiaReportItems> diaReportItems = diaReportStandardsMapper.getItemByReportId(reportId);
        diaReportItems.forEach(item->{

            QueryWrapper<DiaReportStandards> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("relId",relId);
            queryWrapper.eq("itemId",item.getItemId());
            queryWrapper.eq("level","1");
            DiaReportStandards diaReportStandards = this.getOne(queryWrapper);
            if(diaReportStandards!= null){
                item.xgStandard = diaReportStandards.getStandardValue();
            }

            DiaReportStandards searchQuery = new DiaReportStandards();
            searchQuery.setRelId(relId);
            searchQuery.setItemId(item.getItemId());
            searchQuery.setLevel(2);
            searchQuery.deptId = deptId;
            DiaReportStandards diaReportStandards1 = diaReportStandardsMapper.selectStandardDept(searchQuery);
            if(diaReportStandards1!= null){
                item.xwStandard = diaReportStandards1.getStandardValue();
            }

            QueryWrapper<DiaReportStandards> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("relId",relId);
            queryWrapper1.eq("itemId",item.getItemId());
            queryWrapper1.eq("level","3");
            queryWrapper1.eq("user_name",getUsername());
            DiaReportStandards diaReportStandards2 = this.getOne(queryWrapper1);
            if(diaReportStandards2!= null){
                item.stuStandard = diaReportStandards2.getStandardValue();
            }
        });
        return diaReportItems;
    }

    /**
     * 查询诊断报告标准
     *
     * @param standardId 诊断报告标准主键
     * @return 诊断报告标准
     */
    @Override
    public DiaReportStandards selectDiaReportStandardsByStandardId(Long standardId) {
        return diaReportStandardsMapper.selectDiaReportStandardsByStandardId(standardId);
    }

    /**
     * 查询诊断报告标准列表
     *
     * @param diaReportStandards 诊断报告标准
     * @return 诊断报告标准
     */
    @Override
    public List<DiaReportStandards> selectDiaReportStandardsList(DiaReportStandards diaReportStandards) {
        return diaReportStandardsMapper.selectDiaReportStandardsList(diaReportStandards);
    }

    /**
     * 新增诊断报告标准
     *
     * @param diaReportStandards 诊断报告标准
     * @return 结果
     */
    @Override
    public int insertDiaReportStandards(DiaReportStandards diaReportStandards) {
                diaReportStandards.setCreateTime(getNowDate());
            return diaReportStandardsMapper.insertDiaReportStandards(diaReportStandards);
    }

    /**
     * 修改诊断报告标准
     *
     * @param diaReportStandards 诊断报告标准
     * @return 结果
     */
    @Override
    public int updateDiaReportStandards(DiaReportStandards diaReportStandards) {
                diaReportStandards.setUpdateTime(getNowDate());
        return diaReportStandardsMapper.updateDiaReportStandards(diaReportStandards);
    }

    /**
     * 批量删除诊断报告标准
     *
     * @param standardIds 需要删除的诊断报告标准主键
     * @return 结果
     */
    @Override
    public int deleteDiaReportStandardsByStandardIds(Long[] standardIds) {
        return diaReportStandardsMapper.deleteDiaReportStandardsByStandardIds(standardIds);
    }

    /**
     * 删除诊断报告标准信息
     *
     * @param standardId 诊断报告标准主键
     * @return 结果
     */
    @Override
    public int deleteDiaReportStandardsByStandardId(Long standardId) {
        return diaReportStandardsMapper.deleteDiaReportStandardsByStandardId(standardId);
    }
}
