/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package com.unis.examine.modular.assessmentManage.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.unis.common.util.CommonTimeFormatUtil;
import com.unis.examine.modular.assessmentlevel.entity.AssessmentLevel;
import com.unis.examine.modular.assessmentlevel.mapper.AssessmentLevelMapper;
import com.unis.examine.modular.assessmentlevel.param.AssessmentLevelAddParam;
import com.unis.examine.modular.assessmentlevel.param.AssessmentLevelEditParam;
import com.unis.examine.modular.assessmentlevel.service.AssessmentLevelService;
import com.unis.examine.modular.assessmenttarget.entity.AssessmentTarget;
import com.unis.examine.modular.assessmenttarget.mapper.AssessmentTargetMapper;
import com.unis.examine.modular.assessmenttarget.param.AssessmentTargetAddParam;
import com.unis.examine.modular.assessmenttarget.param.AssessmentTargetEditParam;
import com.unis.examine.modular.assessmenttarget.service.AssessmentTargetService;
import com.unis.sys.modular.user.entity.SysUser;
import com.unis.sys.modular.user.service.SysUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.unis.common.enums.CommonSortOrderEnum;
import com.unis.common.exception.CommonException;
import com.unis.common.page.CommonPageRequest;
import com.unis.examine.modular.assessmentManage.entity.AssessmentManage;
import com.unis.examine.modular.assessmentManage.mapper.AssessmentManageMapper;
import com.unis.examine.modular.assessmentManage.param.AssessmentManageAddParam;
import com.unis.examine.modular.assessmentManage.param.AssessmentManageEditParam;
import com.unis.examine.modular.assessmentManage.param.AssessmentManageIdParam;
import com.unis.examine.modular.assessmentManage.param.AssessmentManagePageParam;
import com.unis.examine.modular.assessmentManage.service.AssessmentManageService;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.unis.examine.modular.assessmentManage.enums.AssessmentManageEnum.GK;
import static com.unis.examine.modular.assessmentManage.enums.AssessmentManageEnum.SK;

/**
 * 粮食安全责任制考核-考核指标管理表Service接口实现类
 *
 * @author shine
 * @date 2024/04/22 11:44
 **/
@Service
public class AssessmentManageServiceImpl extends ServiceImpl<AssessmentManageMapper, AssessmentManage> implements AssessmentManageService {

    @Resource
    private SysUserService sysUserService;

    @Resource
    private AssessmentManageMapper assessmentManageMapper;

    @Resource
    private AssessmentLevelMapper assessmentLevelMapper;

    @Resource
    private AssessmentLevelService assessmentLevelService;

    @Resource
    private AssessmentTargetMapper assessmentTargetMapper;

    @Resource
    private AssessmentTargetService assessmentTargetService;

    @Override
    public Page<AssessmentManage> page(AssessmentManagePageParam assessmentManagePageParam) {
        QueryWrapper<AssessmentManage> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(AssessmentManage::getDeleteFlag, "NOT_DELETE");
        // 考核年度
        if (ObjectUtil.isNotEmpty(assessmentManagePageParam.getAssessmentYear())) {
            queryWrapper.lambda().eq(AssessmentManage::getAssessmentYear, assessmentManagePageParam.getAssessmentYear());
        }
        // 考核类型:1:国考,2:省考
        if (ObjectUtil.isNotEmpty(assessmentManagePageParam.getAssessmentType())) {
            queryWrapper.lambda().eq(AssessmentManage::getAssessmentType, assessmentManagePageParam.getAssessmentType());
        }
        // 考核指标管理-所有
        // 状态
        if (ObjectUtil.isNotEmpty(assessmentManagePageParam.getStatus())) {
            // 考核任务下发-列表
            queryWrapper.lambda().ne(AssessmentManage::getStatus, 0);
        }

        if (ObjectUtil.isAllNotEmpty(assessmentManagePageParam.getSortField(), assessmentManagePageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(assessmentManagePageParam.getSortOrder());
            queryWrapper.orderBy(true, assessmentManagePageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(assessmentManagePageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByDesc(AssessmentManage::getId);
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(AssessmentManageAddParam assessmentManageAddParam, List<AssessmentLevelAddParam> levelList, List<AssessmentTargetAddParam> targetList) {
        AssessmentManage assessmentManage = BeanUtil.toBean(assessmentManageAddParam, AssessmentManage.class);

        // 保存考核指标管理
        this.save(assessmentManage);
        // 保存子表考核指标管理-考核等级
        levelList.forEach(level -> {
            level.setAssessmentManageId(assessmentManage.getId());
            assessmentLevelService.add(level);
        });
        // 保存子表考核指标管理-考核指标
        targetList.forEach(target -> {
            target.setAssessmentManageId(assessmentManage.getId());
            target.setStatus(assessmentManage.getStatus());
            assessmentTargetService.add(target);
        });
    }

    @SuppressWarnings("all")
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(AssessmentManageEditParam assessmentManageEditParam) {
        AssessmentManage assessmentManage = this.queryEntity(assessmentManageEditParam.getId());
        BeanUtil.copyProperties(assessmentManageEditParam, assessmentManage);
        this.updateById(assessmentManage);
        /*
         * 先删除子表 在新增
         */
        Integer titleStatus = assessmentManageEditParam.getTitleStatus();
        if (null != titleStatus && 9 == titleStatus) { // 列表下发
            QueryWrapper<AssessmentTarget> wrapper = new QueryWrapper<>();
            wrapper.eq("assessment_manage_id", assessmentManageEditParam.getId());
            AssessmentTarget target = new AssessmentTarget();
            target.setStatus(assessmentManageEditParam.getStatus());
            assessmentTargetMapper.update(target, wrapper);
        } else {
            if (1 == assessmentManageEditParam.getStatus()) { // 考核任务管理保存编辑
                this.editTargetList(assessmentManageEditParam.getTargetList(), assessmentManageEditParam);
            } else {
                if (CollectionUtils.isNotEmpty(assessmentManageEditParam.getLevelList())) {
//                    assessmentManageEditParam.getLevelList().forEach(levelList -> assessmentLevelMapper.deleteById(levelList.getId()));
                    this.editLeveltList(assessmentManage.getLevelList(), assessmentManageEditParam.getId());
                }
                this.editTargetList(assessmentManageEditParam.getTargetList(), assessmentManageEditParam);
            }
            // 任务下发
            if (2 == assessmentManageEditParam.getStatus()) {
                QueryWrapper<AssessmentTarget> wrapper = new QueryWrapper<>();
                wrapper.eq("assessment_manage_id", assessmentManageEditParam.getId());
                AssessmentTarget target = new AssessmentTarget();
                target.setStatus(assessmentManageEditParam.getStatus());
                assessmentTargetMapper.update(target, wrapper);
            }
        }
    }

    private void editTargetList(List<AssessmentTargetEditParam> targetList, AssessmentManageEditParam assessmentManageEditParam) {
        // 先删除
        QueryWrapper<AssessmentTarget> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(AssessmentTarget::getAssessmentManageId, assessmentManageEditParam.getId());
        assessmentTargetMapper.delete(wrapper);
        // 考核指标
        targetList.forEach(target -> {
            AssessmentTargetAddParam assessmentTarget = new AssessmentTargetAddParam();
            assessmentTarget.setAssessmentManageId(assessmentManageEditParam.getId());
            assessmentTarget.setScore(target.getScore());
            assessmentTarget.setTargetNo(target.getTargetNo());
            assessmentTarget.setSysOrgId(target.getSysOrgId());
            assessmentTarget.setStatus(assessmentManageEditParam.getStatus()); // 状态 0:未下发任务;1:保存;2:已下发任务
            assessmentTargetService.add(assessmentTarget);
        });
    }

    private void editLeveltList(List<AssessmentLevel> levelList, String manageId) {
        // 考核等级
        levelList.forEach(level -> assessmentLevelService.updateById(level));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<AssessmentManageIdParam> assessmentManageIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(assessmentManageIdParamList, AssessmentManageIdParam::getId));
        /*
         * 删除子表内容
         * 查询主键 根据主键删除
         */
        assessmentManageIdParamList.forEach(ids -> {
            // 删除考核指标设置-子表管理数据
            QueryWrapper<AssessmentTarget> targetQueryWrapper = new QueryWrapper<>();
            targetQueryWrapper.lambda().eq(AssessmentTarget::getAssessmentManageId, ids.getId());
            assessmentTargetMapper.delete(targetQueryWrapper);
            // 删除考核等级设置-子表管理数据
            QueryWrapper<AssessmentLevel> levelQueryWrapper = new QueryWrapper<>();
            levelQueryWrapper.lambda().eq(AssessmentLevel::getAssessmentManageId, ids.getId());
            assessmentLevelMapper.delete(levelQueryWrapper);
        });
    }

    @Override
    public AssessmentManage detail(AssessmentManageIdParam assessmentManageIdParam) {
        AssessmentManage assessmentManage = this.queryEntity(assessmentManageIdParam.getId());
        assessmentManage.setLevelList(assessmentLevelService.queryList(assessmentManageIdParam.getId()));
        List<AssessmentTarget> assessmentTargets = assessmentTargetService.queryList(assessmentManageIdParam.getId());
        if (CollectionUtils.isNotEmpty(assessmentTargets)) {
            if (0 == assessmentManageIdParam.getStatus()) {
                assessmentTargets = assessmentTargets.stream().filter(target -> target.getStatus() == 0).collect(Collectors.toList());
            } else if (1 == assessmentManageIdParam.getStatus()) {
                assessmentTargets = assessmentTargets.stream().filter(target -> target.getStatus() == 1).collect(Collectors.toList());
            } else if (2 == assessmentManageIdParam.getStatus()) {
                assessmentTargets = assessmentTargets.stream().filter(target -> target.getStatus() == 2).collect(Collectors.toList());
            } else {
                assessmentManage.setTargetList(assessmentTargets);
            }
            assessmentManage.setTargetList(assessmentTargets);
        }
        return assessmentManage;
    }

    @Override
    public AssessmentManage queryEntity(String id) {
        AssessmentManage assessmentManage = this.getById(id);
        assessmentManage.setLevelList(assessmentLevelService.queryList(id));
        assessmentManage.setTargetList(assessmentTargetService.queryList(id));
        if (ObjectUtil.isEmpty(assessmentManage)) {
            throw new CommonException("粮食安全责任制考核-考核指标管理表不存在，id值为：{}", id);
        }
        return assessmentManage;
    }

    @Override
    public IPage<Map<String, Object>> findByOrgIdPage(AssessmentManagePageParam assessmentManagePageParam) throws ParseException {
        //条形查询器
        QueryWrapper<AssessmentManage> queryWrapper = new QueryWrapper<>();

        SysUser user = sysUserService.queryEntity(StpUtil.getLoginIdAsString());
        if (user == null) {
            throw new CommonException("获取不到当前用户，请登陆后再试");
        }
       queryWrapper.eq("nat.sys_org_id", user.getOrgId());

        if (assessmentManagePageParam.getAssessmentYear() != null) {
            queryWrapper.like("nam.assessmentYear", assessmentManagePageParam.getAssessmentYear());
        }
        if (assessmentManagePageParam.getAssessmentType() == 1) {
            queryWrapper.eq("nam.assessment_type", 1);
        } else {
            queryWrapper.eq("nam.assessment_type", 2);
        }
        queryWrapper.eq("nam.status", 2);
        Page<AssessmentManage> p = new Page<>(assessmentManagePageParam.getCurrent(), assessmentManagePageParam.getSize());
        IPage<Map<String, Object>> page = assessmentManageMapper.selectMyMapsPage(p, queryWrapper);
        return page;
    }

    @Override
    public IPage<Map<String, Object>> findByPage(AssessmentManagePageParam assessmentManagePageParam) throws ParseException {
        //条形查询器
        QueryWrapper<AssessmentManage> queryWrapper = new QueryWrapper<>();


        if (assessmentManagePageParam.getAssessmentYear() != null) {
            queryWrapper.like("nam.assessmentYear", assessmentManagePageParam.getAssessmentYear());
        }
        if (assessmentManagePageParam.getAssessmentType() == 1) {
            queryWrapper.eq("nam.assessment_type", GK.getValue());
        } else {
            queryWrapper.eq("nam.assessment_type", SK.getValue());
        }
        queryWrapper.eq("nam.status", 2);
        queryWrapper.eq("bas.status", 1);
        queryWrapper.eq("nat.status", 2);

        Page<AssessmentManage> p = new Page<>(assessmentManagePageParam.getCurrent(), assessmentManagePageParam.getSize());



        IPage<Map<String, Object>> page = assessmentManageMapper.selectMyPage(p, queryWrapper);
        // 检查 page 是否有数据
        if (page != null && page.getRecords() != null && !page.getRecords().isEmpty()) {
            // 遍历分页数据
            for (Map<String, Object> record : page.getRecords()) {
                // 在这里处理每一个 map 对象，map 中的 key 是数据库列名，value 是对应的值
                // 例如，获取名为 "id" 的列的值
                Integer pcType = Integer.parseInt(record.get("pcType").toString());

            // 假设 pcType 已经被定义并且有合法的值
            String pcTypeName;
                switch (pcType) {
                    case 2:
                        pcTypeName = "西宁市";
                        break;
                    case 3:
                        pcTypeName = "海东市";
                        break;
                    case 4:
                        pcTypeName = "海北州";
                        break;
                    case 5:
                        pcTypeName = "海西州";
                        break;
                    case 6:
                        pcTypeName = "海南州";
                        break;
                    case 7:
                        pcTypeName = "黄南州";
                        break;
                    case 8:
                        pcTypeName = "果洛州";
                        break;
                    case 9:
                        pcTypeName = "玉树州";
                        break;
                    default:
                        // 如果 pcType 不在上述范围内，你可以设定一个默认值或者抛出异常
                        pcTypeName = "未知类型";
                        // 或者 throw new IllegalArgumentException("Invalid pcType: " + pcType);
                }
                // 将 pcTypeName 放入 record
                record.put("pcTypeName", pcTypeName);
            }
        }

        return page;
    }

    @Override
    public List<Map<String, Object>> getAssessmentName() {
        return assessmentManageMapper.getAssessmentName(CommonTimeFormatUtil.getDateTime());
    }

    @Override
    public List<Map<String, Object>> getOnlyOrgInfo(String parentId) {
        return assessmentManageMapper.getOnlyOrgInfo(parentId);
    }

    @Override
    public IPage<Map<String, Object>> ScorePage(AssessmentManagePageParam assessmentManagePageParam) {
        //条形查询器
        QueryWrapper<AssessmentManage> queryWrapper = new QueryWrapper<>();

        if (assessmentManagePageParam.getAssessmentYear() != null) {
            queryWrapper.like("nam.assessmentYear", assessmentManagePageParam.getAssessmentYear());
        }
        if (assessmentManagePageParam.getAssessmentType() == 1) {
            queryWrapper.eq("nam.assessment_type", 1);
        } else {
            queryWrapper.eq("nam.assessment_type", 2);
        }
        queryWrapper.eq("nam.status", 2);
        Page<AssessmentManage> p = new Page<>(assessmentManagePageParam.getCurrent(), assessmentManagePageParam.getSize());
        IPage<Map<String, Object>> page = assessmentManageMapper.selectMyMapsPage(p, queryWrapper);
        return page;
    }

}
