/*
 * 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.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.unis.auth.core.util.StpClientUtil;
import com.unis.auth.core.util.StpLoginUserUtil;
import com.unis.auth.modular.login.entity.UserCollectLogin;
import com.unis.basic.info.modular.grainPriceCollect.mapper.GrainPriceCollectMapper;
import com.unis.basic.info.modular.grainPriceCollectCitySum.entity.GrainPriceCollectCitySum;
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.service.impl.AssessmentLevelServiceImpl;
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.service.impl.AssessmentTargetServiceImpl;
import com.unis.sys.modular.user.entity.SysUser;
import com.unis.sys.modular.user.service.SysUserService;
import org.apache.commons.lang3.StringUtils;
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.Priority;
import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 粮食安全责任制考核-考核指标管理表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 AssessmentLevelServiceImpl assessmentLevelServiceImpl;

    @Resource
    private AssessmentTargetMapper assessmentTargetMapper;

    @Resource
    private AssessmentTargetServiceImpl assessmentTargetServiceImpl;

    @Override
    public Page<AssessmentManage> page(AssessmentManagePageParam assessmentManagePageParam) throws ParseException {
        QueryWrapper<AssessmentManage> queryWrapper = new QueryWrapper<>();
        if(ObjectUtil.isNotEmpty(assessmentManagePageParam.getAssessmentYear())) {
            queryWrapper.lambda().eq(AssessmentManage::getAssessmentYear,assessmentManagePageParam.getAssessmentYear());
        }
        if(ObjectUtil.isNotEmpty(assessmentManagePageParam.getAssessmentType())) {
            queryWrapper.lambda().eq(AssessmentManage::getAssessmentType,assessmentManagePageParam.getAssessmentType());
        }
        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().orderByAsc(AssessmentManage::getId);
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

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

        this.save(assessmentManage);
        for (int i = 0; i < levelList.size(); i++) {
            levelList.get(i).setAssessmentManageId(assessmentManage.getId());
            assessmentLevelServiceImpl.add(levelList.get(i));
        }
        for (int j = 0; j < targetList.size(); j++) {
            targetList.get(j).setAssessmentManageId(assessmentManage.getId());
            assessmentTargetServiceImpl.add(targetList.get(j));
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(AssessmentManageEditParam assessmentManageEditParam) {
        AssessmentManage assessmentManage = this.queryEntity(assessmentManageEditParam.getId());
        BeanUtil.copyProperties(assessmentManageEditParam, assessmentManage);
        this.updateById(assessmentManage);
        /**
         * 删除子表 在新增
         */

        for (int i = 0; i <assessmentManageEditParam.getLevelList().size() ; i++) {
            assessmentLevelMapper.deleteById(assessmentManageEditParam.getLevelList().get(i).getId());
        }

        for (int i = 0; i <assessmentManageEditParam.getTargetList().size() ; i++) {
            assessmentTargetMapper.deleteById(assessmentManageEditParam.getTargetList().get(i).getId());
        }

        for (int i = 0; i < assessmentManageEditParam.getLevelList().size(); i++) {
            AssessmentLevelAddParam assessmentLevelAddParam = new AssessmentLevelAddParam();
            assessmentLevelAddParam.setAssessmentManageId(assessmentManageEditParam.getId());
            assessmentLevelAddParam.setMaxValue(assessmentManageEditParam.getLevelList().get(i).getMaxValue());
            assessmentLevelAddParam.setMinValue(assessmentManageEditParam.getLevelList().get(i).getMinValue());
            assessmentLevelAddParam.setName(assessmentManageEditParam.getLevelList().get(i).getName());
            assessmentLevelServiceImpl.add(assessmentLevelAddParam);
        }
        for (int j = 0; j < assessmentManageEditParam.getTargetList().size(); j++) {
            AssessmentTargetAddParam assessmenttargetAddParam = new AssessmentTargetAddParam();
            assessmenttargetAddParam.setAssessmentManageId(assessmentManageEditParam.getId());
            assessmenttargetAddParam.setScore(assessmentManageEditParam.getTargetList().get(j).getScore());
            assessmenttargetAddParam.setTargetNo(assessmentManageEditParam.getTargetList().get(j).getTargetNo());
            assessmenttargetAddParam.setSysOrgId(assessmentManageEditParam.getTargetList().get(j).getSysOrgId());
            assessmenttargetAddParam.setStatus(0);//未下发
            assessmentTargetServiceImpl.add(assessmenttargetAddParam);
        }

        /*for (int i = 0; i < assessmentManageEditParam.getLevelList().size(); i++) {
            AssessmentLevel assessmentLevel = assessmentLevelServiceImpl.queryEntity(assessmentManageEditParam.getLevelList().get(i).getId());
            BeanUtil.copyProperties(assessmentManageEditParam.getLevelList().get(i), assessmentLevel);
            assessmentLevelServiceImpl.updateById(assessmentLevel);
        }

        for (int j = 0; j < assessmentManageEditParam.getTargetList().size(); j++) {
            AssessmentTarget assessmentTarget = assessmentTargetServiceImpl.queryEntity(assessmentManageEditParam.getTargetList().get(j).getId());
            BeanUtil.copyProperties(assessmentManageEditParam.getTargetList().get(j), assessmentTarget);
            assessmentTargetServiceImpl.updateById(assessmentTarget);
        }*/

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<AssessmentManageIdParam> assessmentManageIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(assessmentManageIdParamList, AssessmentManageIdParam::getId));
        /**\
         * 删除子表内容
         * 查询主键 根据主键删除
         */
        List<AssessmentLevel> levelList = assessmentLevelServiceImpl.queryList(assessmentManageIdParamList.get(0).getId());
        for (int i = 0; i <levelList.size() ; i++) {
            assessmentLevelMapper.deleteById(levelList.get(i).getId());
        }

        List<AssessmentTarget> targetList = assessmentTargetServiceImpl.queryList(assessmentManageIdParamList.get(0).getId());
        for (int i = 0; i <targetList.size() ; i++) {
            assessmentTargetMapper.deleteById(targetList.get(i).getId());
        }
    }

    @Override
    public AssessmentManage detail(AssessmentManageIdParam assessmentManageIdParam) {
        AssessmentManage assessmentManage = this.queryEntity(assessmentManageIdParam.getId());
        assessmentManage.setLevelList(assessmentLevelServiceImpl.queryList(assessmentManageIdParam.getId()));
        assessmentManage.setTargetList(assessmentTargetServiceImpl.queryList(assessmentManageIdParam.getId()));
        return assessmentManage;
    }

    @Override
    public AssessmentManage queryEntity(String id) {
        AssessmentManage assessmentManage = this.getById(id);
        assessmentManage.setLevelList(assessmentLevelServiceImpl.queryList(id));
        assessmentManage.setTargetList(assessmentTargetServiceImpl.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());
        }
            queryWrapper.eq("nam.AssessmentType",1);
            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;
    }


}
