package com.xjrsoft.module.textbook.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.xjrsoft.common.enums.ClaimTypeEnum;
import com.xjrsoft.common.enums.IssueModeEnum;
import com.xjrsoft.common.exception.MyException;
import com.xjrsoft.common.page.ConventPage;
import com.xjrsoft.module.organization.mapper.RoleMapper;
import com.xjrsoft.module.teacher.entity.XjrUser;
import com.xjrsoft.module.teacher.mapper.XjrUserMapper;
import com.xjrsoft.module.textbook.dto.ConfirmDistributeDto;
import com.xjrsoft.module.textbook.dto.WfTextbookClaimPageDto;
import com.xjrsoft.module.textbook.entity.*;
import com.xjrsoft.module.textbook.mapper.TextbookClaimUserMapper;
import com.xjrsoft.module.textbook.mapper.WfTextbookClaimItemMapper;
import com.xjrsoft.module.textbook.mapper.WfTextbookClaimMapper;
import com.xjrsoft.module.textbook.service.ITextbookIssueRecordService;
import com.xjrsoft.module.textbook.service.ITextbookService;
import com.xjrsoft.module.textbook.service.ITextbookStudentClaimService;
import com.xjrsoft.module.textbook.service.IWfTextbookClaimService;
import com.xjrsoft.module.textbook.vo.WfTextbookClaimItemVo;
import com.xjrsoft.module.textbook.vo.WfTextbookClaimPageVo;
import com.xjrsoft.module.textbook.vo.WfTextbookClaimVo;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @title: 教材申领
 * @Author szs
 * @Date: 2023-12-26
 * @Version 1.0
 */
@Service
@AllArgsConstructor
public class WfTextbookClaimServiceImpl extends MPJBaseServiceImpl<WfTextbookClaimMapper, WfTextbookClaim> implements IWfTextbookClaimService {
    private final WfTextbookClaimMapper wfTextbookClaimWfTextbookClaimMapper;

    private final WfTextbookClaimItemMapper wfTextbookClaimWfTextbookClaimItemMapper;

    private final XjrUserMapper xjrUserMapper;

    private final RoleMapper roleMapper;

    private final ITextbookService textbookService;

    private final ITextbookStudentClaimService textbookStudentClaimService;

    private final ITextbookIssueRecordService textbookIssueRecordService;

    private final TextbookClaimUserMapper textbookClaimUserMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean add(WfTextbookClaim wfTextbookClaim) {
        wfTextbookClaimWfTextbookClaimMapper.insert(wfTextbookClaim);
        for (WfTextbookClaimItem wfTextbookClaimItem : wfTextbookClaim.getWfTextbookClaimItemList()) {
            wfTextbookClaimItem.setWfTextbookClaimId(wfTextbookClaim.getId());
            wfTextbookClaimWfTextbookClaimItemMapper.insert(wfTextbookClaimItem);
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean update(WfTextbookClaim wfTextbookClaim) {
        wfTextbookClaimWfTextbookClaimMapper.updateById(wfTextbookClaim);
        //********************************* WfTextbookClaimItem  增删改  开始 *******************************************/
        {
            // 查出所有子级的id
            List<WfTextbookClaimItem> wfTextbookClaimItemList = wfTextbookClaimWfTextbookClaimItemMapper.selectList(Wrappers.lambdaQuery(WfTextbookClaimItem.class).eq(WfTextbookClaimItem::getWfTextbookClaimId, wfTextbookClaim.getId()).select(WfTextbookClaimItem::getId));
            List<Long> wfTextbookClaimItemIds = wfTextbookClaimItemList.stream().map(WfTextbookClaimItem::getId).collect(Collectors.toList());
            //原有子表单 没有被删除的主键
            List<Long> wfTextbookClaimItemOldIds = wfTextbookClaim.getWfTextbookClaimItemList().stream().map(WfTextbookClaimItem::getId).filter(Objects::nonNull).collect(Collectors.toList());
            //找到需要删除的id
            List<Long> wfTextbookClaimItemRemoveIds = wfTextbookClaimItemIds.stream().filter(item -> !wfTextbookClaimItemOldIds.contains(item)).collect(Collectors.toList());

            for (WfTextbookClaimItem wfTextbookClaimItem : wfTextbookClaim.getWfTextbookClaimItemList()) {
                //如果不等于空则修改
                if (wfTextbookClaimItem.getId() != null) {
                    wfTextbookClaimWfTextbookClaimItemMapper.updateById(wfTextbookClaimItem);
                }
                //如果等于空 则新增
                else {
                    //已经不存在的id 删除
                    wfTextbookClaimItem.setWfTextbookClaimId(wfTextbookClaim.getId());
                    wfTextbookClaimWfTextbookClaimItemMapper.insert(wfTextbookClaimItem);
                }
            }
            //已经不存在的id 删除
            if (wfTextbookClaimItemRemoveIds.size() > 0) {
                wfTextbookClaimWfTextbookClaimItemMapper.deleteBatchIds(wfTextbookClaimItemRemoveIds);
            }
        }
        //********************************* WfTextbookClaimItem  增删改  结束 *******************************************/

        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean delete(List<Long> ids) {
        wfTextbookClaimWfTextbookClaimMapper.deleteBatchIds(ids);
        wfTextbookClaimWfTextbookClaimItemMapper.delete(Wrappers.lambdaQuery(WfTextbookClaimItem.class).in(WfTextbookClaimItem::getWfTextbookClaimId, ids));

        return true;
    }

    @Override
    public IPage<WfTextbookClaimPageVo> getPage(WfTextbookClaimPageDto dto) {

        dto.setUserId(StpUtil.getLoginIdAsLong());
        IPage<WfTextbookClaimPageVo> page = wfTextbookClaimWfTextbookClaimMapper.getPage(ConventPage.getPage(dto), dto);

        for (WfTextbookClaimPageVo wfTextbookClaimPageVo : page.getRecords()) {
            //拆分代领取人
            String receiveUserIdStr = wfTextbookClaimPageVo.getReceiveUserId();
            if (ObjectUtil.isNotNull(receiveUserIdStr) && !receiveUserIdStr.equals("")) {
                String[] receiveUserIdStrs = receiveUserIdStr.split(",");
                List<Long> receiveUserIdList = new ArrayList<>();
                for (String str : receiveUserIdStrs) {
                    receiveUserIdList.add(Long.parseLong(str));
                }
                LambdaQueryWrapper<XjrUser> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper
                        .in(XjrUser::getId, receiveUserIdList);
                List<XjrUser> xjrUserList = xjrUserMapper.selectList(queryWrapper);
                if (ObjectUtil.isNotNull(xjrUserList) && xjrUserList.size() > 0) {
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < xjrUserList.size(); i++) {
                        if(i == 0){
                            sb.append(xjrUserList.get(i).getName());
                        }else{
                            sb.append("," + xjrUserList.get(i).getName());
                        }
                    }
                    wfTextbookClaimPageVo.setReceiveUserIdCN(sb.toString());
                }
            }
            //加上申领项
            List<WfTextbookClaimItemVo> wfTextbookClaimItemVoList = wfTextbookClaimWfTextbookClaimItemMapper.getListByWfTextbookClaimId(Long.parseLong(wfTextbookClaimPageVo.getId()));

            if (ObjectUtil.isNotNull(wfTextbookClaimItemVoList) && wfTextbookClaimItemVoList.size() > 0) {
                wfTextbookClaimPageVo.setWfTextbookClaimItemList(wfTextbookClaimItemVoList);
            }
        }
        return page;
    }

    @Override
    public WfTextbookClaimVo infoDistribute(Long id) {
        WfTextbookClaimVo wfTextbookClaimVo = wfTextbookClaimWfTextbookClaimMapper.infoDistribute(id);
        if (ObjectUtil.isNotNull(wfTextbookClaimVo)) {
            //拆分代领人
            String receiveUserIdStr = wfTextbookClaimVo.getReceiveUserId();
            if (ObjectUtil.isNotNull(receiveUserIdStr) && !receiveUserIdStr.equals("")) {
                String[] receiveUserIdStrs = receiveUserIdStr.split(",");
                List<Long> receiveUserIdList = new ArrayList<>();
                for (String str : receiveUserIdStrs) {
                    receiveUserIdList.add(Long.parseLong(str));
                }
                LambdaQueryWrapper<XjrUser> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper
                        .in(XjrUser::getId, receiveUserIdList);
                List<XjrUser> xjrUserList = xjrUserMapper.selectList(queryWrapper);
                if (ObjectUtil.isNotNull(xjrUserList) && xjrUserList.size() > 0) {
                    StringBuilder sb = new StringBuilder();
                    for (XjrUser xjrUser : xjrUserList) {
                        sb.append("," + xjrUser.getName());
                    }
                    wfTextbookClaimVo.setReceiveUserIdCN(sb.toString());
                }
            }
            //加上申领项
            List<WfTextbookClaimItemVo> wfTextbookClaimItemVoList = wfTextbookClaimWfTextbookClaimItemMapper.getListByWfTextbookClaimId(Long.parseLong(wfTextbookClaimVo.getId()));

            if (ObjectUtil.isNotNull(wfTextbookClaimItemVoList) && wfTextbookClaimItemVoList.size() > 0) {
                wfTextbookClaimVo.setWfTextbookClaimItemList(wfTextbookClaimItemVoList);
            }
        }
        return wfTextbookClaimVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean confirmDistribute(ConfirmDistributeDto dto) {
        WfTextbookClaim wfTextbookClaim = this.getById(dto.getTextbookClaimId());

        if (ObjectUtil.isNull(wfTextbookClaim) || ObjectUtil.isNull(dto.getTextbookClaimItemList()) || dto.getTextbookClaimItemList().size() == 0) {
            throw new MyException("未找到申领数据");
        }

        //操作每一个申领项
        for (ConfirmDistributeDto.TextbookClaimItem textbookClaimItem : dto.getTextbookClaimItemList()) {

            WfTextbookClaimItem wfTextbookClaimItem = wfTextbookClaimWfTextbookClaimItemMapper.selectById(textbookClaimItem.getTextbookClaimItemId());

            if (ObjectUtil.isNull(wfTextbookClaimItem)) {
                throw new MyException("未找到申领数据");
            }

            Textbook textbook = textbookService.getById(wfTextbookClaimItem.getTextbookId());

            if (ObjectUtil.isNull(textbook)) {
                throw new MyException("未找到相关教材数据");
            }

            //判断总发放数量是否超出该申请项的申请数量
            Integer issueNumber = ObjectUtil.isNull(wfTextbookClaimItem.getIssueNumber()) ? 0 : wfTextbookClaimItem.getIssueNumber();//已发放
            Integer confirmNumber = ObjectUtil.isNull(textbookClaimItem.getConfirmNumber()) ? 0 : textbookClaimItem.getConfirmNumber();//本次发放
            Integer applicantNumber = ObjectUtil.isNull(wfTextbookClaimItem.getApplicantNumber()) ? 0 : wfTextbookClaimItem.getApplicantNumber();//申领总数量
            if (issueNumber + confirmNumber > applicantNumber) {
                throw new MyException(textbook.getBookName() + "发放总数量超出申领数量");
            }

            //判断发放量是否多于库存量
            Integer stock = ObjectUtil.isNull(textbook.getStock()) ? 0 : textbook.getStock();
            if (stock < confirmNumber) {
                throw new MyException(textbook.getBookName() + "库存不足");
            }

            //增加出库记录
            textbookIssueRecordService.save(new TextbookIssueRecord() {{
                setCreateDate(new Date());
                setTextbookId(wfTextbookClaimItem.getTextbookId());
                setDataId(wfTextbookClaim.getId());
                setDataItemId(wfTextbookClaimItem.getId());
                setIssueNumber(confirmNumber);
                setRemainingNumber(applicantNumber - issueNumber - confirmNumber);
                setReceiveUserId(dto.getReceiveUserId());
                setIssueUserId(StpUtil.getLoginIdAsLong());
                if (ObjectUtil.isNotNull(wfTextbookClaim.getClaimType()) && wfTextbookClaim.getClaimType().equals(ClaimTypeEnum.ClaimStudent.getCode())) {
                    setIssueMode(IssueModeEnum.Imtudent.getCode());
                }
                if (ObjectUtil.isNotNull(wfTextbookClaim.getClaimType()) && wfTextbookClaim.getClaimType().equals(ClaimTypeEnum.ClaimTeacher.getCode())) {
                    setIssueMode(IssueModeEnum.ImTeacher.getCode());
                }
                setRemark(dto.getRemark());
                QueryWrapper<TextbookIssueRecord> queryWrapperSortcode = new QueryWrapper<>();
                queryWrapperSortcode.select("IFNULL(MAX(sort_code),0) as sortCode");
                TextbookIssueRecord t = textbookIssueRecordService.getOne(queryWrapperSortcode);
                setSortCode(t.getSortCode()+1);

            }});

            //更新教材管理中的库存数量
            textbookService.updateById(new Textbook() {{
                setModifyUserId(StpUtil.getLoginIdAsLong());
                setModifyDate(new Date());
                setId(textbook.getId());
                setStock(stock - confirmNumber);
            }});

            //更新申领项中的已经发放数量
            wfTextbookClaimWfTextbookClaimItemMapper.updateById(new WfTextbookClaimItem() {{
                setModifyUserId(StpUtil.getLoginIdAsLong());
                setModifyDate(new Date());
                setId(wfTextbookClaimItem.getId());
                setIssueNumber(issueNumber + confirmNumber);
            }});


            //当申领类型为学生的时候,为班级每个学生生成领取（确认信息）认领记录
            if (ObjectUtil.isNotNull(wfTextbookClaim.getClaimType()) && wfTextbookClaim.getClaimType().equals(ClaimTypeEnum.ClaimStudent.getCode())) {
                //查出班上的所有学生id
                List<Long> userIdList = xjrUserMapper.getUserIdByClassId(wfTextbookClaim.getClassId());

                if (ObjectUtil.isNull(userIdList) && userIdList.size() == 0) {
                    throw new MyException("申领班级有误，请核实");
                }
                //验证当前领取教材是否已经生成领取记录
                LambdaQueryWrapper<TextbookStudentClaim> queryWrapperRecord = new LambdaQueryWrapper<>();
                queryWrapperRecord
                        .eq(TextbookStudentClaim::getTextbookId, wfTextbookClaimItem.getTextbookId())
                        .eq(TextbookStudentClaim::getClassId, wfTextbookClaim.getClassId());
                Long count = textbookStudentClaimService.count(queryWrapperRecord);
                //为0的时候表示该班级该书没有生成领取记录
                if(count <= 0){
                    for (Long userId : userIdList) {
                        textbookStudentClaimService.save(new TextbookStudentClaim() {{
                            setCreateUserId(StpUtil.getLoginIdAsLong());
                            setCreateDate(new Date());
                            setStudentUserId(userId);
                            setBaseSemesterId(wfTextbookClaim.getBaseSemesterId());
                            setClassId(wfTextbookClaim.getClassId());
                            setTextbookId(wfTextbookClaimItem.getTextbookId());
                        }});
                    }
                }
            }
        }
        return true;
    }

    @Override
    @Transactional
    public Boolean dataHandleAddClaimUserNode(Long id) {
        WfTextbookClaim wfTextbookClaim = this.getById(id);
        if (ObjectUtil.isNotNull(wfTextbookClaim)
                && ObjectUtil.isNotNull(wfTextbookClaim.getClaimType())) {
            //所有需要添加的可领取人ID
            List<TextbookClaimUser> textbookClaimUserList = new ArrayList<>();
            //申领人自己可以领取
            textbookClaimUserList.add(new TextbookClaimUser() {{
                setCreateDate(new Date());
                setWfTextbookClaimId(wfTextbookClaim.getId());
                setUserId(wfTextbookClaim.getApplicantUserId());
                setUserType(2);
            }});
            //申领类型是学生申领,学生代表可领取
            if (wfTextbookClaim.getClaimType().equals(ClaimTypeEnum.ClaimStudent.getCode())) {
                textbookClaimUserList.add(new TextbookClaimUser() {{
                    setCreateDate(new Date());
                    setWfTextbookClaimId(wfTextbookClaim.getId());
                    setUserId(wfTextbookClaim.getStudentUserId());
                    setUserType(1);
                }});
            }
            //申领类型是教师申领，领取人可领取
            if (wfTextbookClaim.getClaimType().equals(ClaimTypeEnum.ClaimTeacher.getCode())
                    && ObjectUtil.isNotNull(wfTextbookClaim.getApplicantUserId())
                    && ObjectUtil.isNotNull(wfTextbookClaim.getClaimUserId())
                    && !wfTextbookClaim.getApplicantUserId().equals(wfTextbookClaim.getClaimUserId())) {
                textbookClaimUserList.add(new TextbookClaimUser() {{
                    setCreateDate(new Date());
                    setWfTextbookClaimId(wfTextbookClaim.getId());
                    setUserId(wfTextbookClaim.getClaimUserId());
                    setUserType(2);
                }});
            }

            for (TextbookClaimUser textbookClaimUser : textbookClaimUserList) {
                textbookClaimUserMapper.insert(textbookClaimUser);
            }
        }
        return true;
    }

}
