/*
 * 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.policy.info.modular.mlpAdviceCollect.service.impl;

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.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
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.policy.info.modular.mlpAdviceCollect.entity.MlpAdviceCollectOrg;
import com.unis.policy.info.modular.mlpAdviceCollect.mapper.MlpAdviceCollectOrgMapper;
import com.unis.policy.info.modular.mlpAdviceCollect.vo.MlpAdviceCollectVO;
import com.unis.policy.info.modular.mlpAdviceCollectFeedback.entity.MlpAdviceCollectOrgFeedback;
import com.unis.policy.info.modular.mlpAdviceCollectFeedback.mapper.MlpAdviceCollectOrgFeedbackMapper;
import com.unis.policy.info.modular.mlpAdviceCollectFeedback.param.MlpAdviceCollectOrgFeedbackAddParam;
import com.unis.sys.modular.org.entity.SysOrg;
import com.unis.sys.modular.org.mapper.SysOrgMapper;
import com.unis.sys.modular.user.entity.SysUser;
import com.unis.sys.modular.user.mapper.SysUserMapper;
import io.minio.MinioClient;
import io.minio.ObjectWriteResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.jcajce.provider.symmetric.SEED;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
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.policy.info.modular.mlpAdviceCollect.entity.MlpAdviceCollect;
import com.unis.policy.info.modular.mlpAdviceCollect.mapper.MlpAdviceCollectMapper;
import com.unis.policy.info.modular.mlpAdviceCollect.param.MlpAdviceCollectAddParam;
import com.unis.policy.info.modular.mlpAdviceCollect.param.MlpAdviceCollectEditParam;
import com.unis.policy.info.modular.mlpAdviceCollect.param.MlpAdviceCollectIdParam;
import com.unis.policy.info.modular.mlpAdviceCollect.param.MlpAdviceCollectPageParam;
import com.unis.policy.info.modular.mlpAdviceCollect.service.MlpAdviceCollectService;

import java.util.Date;
import java.util.List;

/**
 * 中长期规划管理-规划编制（意见收集）Service接口实现类
 *
 * @author hujinachun
 * @date 2024/04/18 18:02
 **/
@Slf4j
@Service
public class MlpAdviceCollectServiceImpl extends ServiceImpl<MlpAdviceCollectMapper, MlpAdviceCollect> implements MlpAdviceCollectService {

    @Autowired
    private SysOrgMapper sysOrgMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private MlpAdviceCollectMapper mlpAdviceCollectMapper;

    @Autowired
    private MlpAdviceCollectOrgMapper mlpAdviceCollectOrgMapper;

    @Autowired
    private MlpAdviceCollectOrgFeedbackMapper mlpAdviceCollectOrgFeedbackMapper;


    @Override
    public Page<MlpAdviceCollect> page(MlpAdviceCollectPageParam mlpAdviceCollectPageParam) {
        QueryWrapper<MlpAdviceCollect> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(mlpAdviceCollectPageParam.getPlanName())) {
            queryWrapper.like("plan_name", mlpAdviceCollectPageParam.getPlanName());
        }
        if (mlpAdviceCollectPageParam.getCollectionDeadline() != null) {
            queryWrapper.eq("collection_deadline", mlpAdviceCollectPageParam.getCollectionDeadline());
        }
        if (ObjectUtil.isAllNotEmpty(mlpAdviceCollectPageParam.getSortField(), mlpAdviceCollectPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(mlpAdviceCollectPageParam.getSortOrder());
            queryWrapper.orderBy(true, mlpAdviceCollectPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(mlpAdviceCollectPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(MlpAdviceCollect::getId);
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(MlpAdviceCollectAddParam addParam) {

        //1. 通过登录人id查找到对应的上级机构
        //从token中获取到用户信息
        //数据范围
   /*     SysUser user = (SysUser) StpClientUtil.getTokenSession().get("loginUser");
        if (ObjectUtil.isEmpty(user)) {
            throw new CommonException("无法获取到用户信息");
        }
        SysUser sysUser = sysUserMapper.selectOne(Wrappers.lambdaQuery(SysUser.class)
                .eq(SysUser::getId, user.getId()));
        if (ObjectUtil.isEmpty(sysUser)) {
            throw new CommonException("暂无此用户信息");
        }
        List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
        if (ObjectUtil.isEmpty(loginUserDataScope)) {
            throw new CommonException("您没有权限操作意见收集");
        }
        if (!loginUserDataScope.contains(user.getOrgId())) {
            throw new CommonException("您没有权限进行操作意见收集，机构id：", user.getOrgId());
        }
*/
        //走到这说明有权限
        //收集科室需要可以存储多个id以逗号分隔  让前端传来以逗号分隔的字符串

        MlpAdviceCollect mlpAdviceCollect = new MlpAdviceCollect();
        BeanUtils.copyProperties(addParam, mlpAdviceCollect);
        mlpAdviceCollect.setAttachment(addParam.getAttachment());
        mlpAdviceCollect.setCreateTime(new Date());

        Integer status = addParam.getStatus();
        if (status == 1) {
            //状态为1，保存信息
            mlpAdviceCollectMapper.insert(mlpAdviceCollect);
        } else if (status == 2) {
            //状态为2，表示发布
            try {
                mlpAdviceCollectMapper.insert(mlpAdviceCollect);
            } catch (Exception e) {
                log.info("意见收集新增失败,异常信息:[{}]", e.getMessage());
                throw new CommonException("意见收集新增失败");
            }
            String[] orgIdList = addParam.getSysOrgId().split(",");
            for (String orgId : orgIdList) {
                mlpAdviceCollect.setSysOrgId(orgId);
                //插入中间表数据
                MlpAdviceCollectOrg mlpAdviceCollectOrg = new MlpAdviceCollectOrg();
                mlpAdviceCollectOrg.setAdviceCollectId(mlpAdviceCollect.getId());
                mlpAdviceCollectOrg.setSysOrgId(orgId);
                mlpAdviceCollectOrg.setCreateTime(new Date());
                mlpAdviceCollectOrg.setPlanName(addParam.getPlanName());
                try {
                    mlpAdviceCollectOrgMapper.insert(mlpAdviceCollectOrg);
                } catch (Exception e) {
                    log.info("意见收集中间表新增失败,异常信息:[{}]", e.getMessage());
                    throw new CommonException("意见收集新增失败");
                }
            }


        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(MlpAdviceCollectEditParam editParam) {
       /* MlpAdviceCollect mlpAdviceCollect = this.queryEntity(mlpAdviceCollectEditParam.getId());
        BeanUtil.copyProperties(mlpAdviceCollectEditParam, mlpAdviceCollect);
        this.updateById(mlpAdviceCollect);*/

        MlpAdviceCollect mlpAdviceCollect = new MlpAdviceCollect();
        BeanUtils.copyProperties(editParam, mlpAdviceCollect);
        mlpAdviceCollect.setUpdateTime(new Date());

        Integer status = editParam.getStatus();
        if (status == 1) {
            //状态为1，保存信息
            mlpAdviceCollectMapper.updateById(mlpAdviceCollect);

        } else if (status == 2) {
            //状态为2，表示发布
            try {
                mlpAdviceCollectMapper.updateById(mlpAdviceCollect);
            } catch (Exception e) {
                log.info("意见收集修改失败,异常信息:[{}]", e.getMessage());
                throw new CommonException("意见收集修改失败");
            }
            String[] orgIdList = editParam.getSysOrgId().split(",");
            for (String orgId : orgIdList) {
                mlpAdviceCollect.setSysOrgId(orgId);

                //修改中间表数据
                MlpAdviceCollectOrg mlpAdviceCollectOrg = new MlpAdviceCollectOrg();
                mlpAdviceCollectOrg.setAdviceCollectId(mlpAdviceCollect.getId());
                mlpAdviceCollectOrg.setSysOrgId(orgId);
                mlpAdviceCollectOrg.setUpdateTime(new Date());
                mlpAdviceCollectOrg.setPlanName(editParam.getPlanName());
                try {
                    mlpAdviceCollectOrgMapper.insert(mlpAdviceCollectOrg);
                } catch (Exception e) {
                    log.info("意见收集中间表修改失败,异常信息:[{}]", e.getMessage());
                    throw new CommonException("意见收集修改失败");
                }
            }
        }


    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<MlpAdviceCollectIdParam> mlpAdviceCollectIdParamList) {
        if (CollectionUtils.isEmpty(mlpAdviceCollectIdParamList)) {
            throw new CommonException("id不能为空");
        }
        MlpAdviceCollectIdParam deleteParam = mlpAdviceCollectIdParamList.get(0);
        List<MlpAdviceCollectOrgFeedback> mlpAdviceCollectOrgFeedbacks = mlpAdviceCollectOrgFeedbackMapper.selectList(Wrappers.lambdaQuery(MlpAdviceCollectOrgFeedback.class)
                .in(MlpAdviceCollectOrgFeedback::getAdviceCollectId, deleteParam.getId()));
        if (CollectionUtils.isNotEmpty(mlpAdviceCollectOrgFeedbacks)) {
            throw new CommonException("此数据关联了意见反馈信息，不能删除");
        }

        // 执行删除
        this.removeByIds(CollStreamUtil.toList(mlpAdviceCollectIdParamList, MlpAdviceCollectIdParam::getId));
    }

    @Override
    public MlpAdviceCollect detail(MlpAdviceCollectIdParam mlpAdviceCollectIdParam) {
        return this.queryEntity(mlpAdviceCollectIdParam.getId());


    }

    @Override
    public MlpAdviceCollect queryEntity(String id) {
        MlpAdviceCollect mlpAdviceCollect = this.getById(id);
        if (ObjectUtil.isEmpty(mlpAdviceCollect)) {
            throw new CommonException("中长期规划管理-规划编制（意见收集）不存在，id值为：{}", id);
        }
        return mlpAdviceCollect;
    }

    /**
     * @author: hujianchun
     * @Description:
     * @param:
     * @return: 查看意见
     */
    @Override
    public List<MlpAdviceCollectVO> selectAdvice(String id) {

        return mlpAdviceCollectMapper.selectAdvice(id);

    }
}
