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.toolkit.Wrappers;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.xjrsoft.common.enums.IssueModeEnum;
import com.xjrsoft.common.enums.RecedeTypeEnum;
import com.xjrsoft.common.enums.WarehouseModeEnum;
import com.xjrsoft.module.base.entity.BaseClass;
import com.xjrsoft.module.base.mapper.BaseClassMapper;
import com.xjrsoft.module.textbook.entity.*;
import com.xjrsoft.module.textbook.mapper.*;
import com.xjrsoft.module.textbook.service.IWfTextbookRecedeService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
* @title: 推书申请
* @Author szs
* @Date: 2024-01-03
* @Version 1.0
*/
@Service
@AllArgsConstructor
public class WfTextbookRecedeServiceImpl extends MPJBaseServiceImpl<WfTextbookRecedeMapper, WfTextbookRecede> implements IWfTextbookRecedeService {
    private final WfTextbookRecedeMapper wfTextbookRecedeWfTextbookRecedeMapper;

    private final WfTextbookRecedeItemMapper wfTextbookRecedeWfTextbookRecedeItemMapper;

    private final TextbookMapper textbookTextbookMapper;

    private final BaseClassMapper baseClassMapper;

    private final TextbookWarehouseRecordMapper textbookWarehouseRecordMapper;

    private final TextbookIssueRecordMapper textbookIssueRecordMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean add(WfTextbookRecede wfTextbookRecede) {
        wfTextbookRecedeWfTextbookRecedeMapper.insert(wfTextbookRecede);
        for (WfTextbookRecedeItem wfTextbookRecedeItem : wfTextbookRecede.getWfTextbookRecedeItemList()) {
            wfTextbookRecedeItem.setWfTextbookRecedeId(wfTextbookRecede.getId());
            wfTextbookRecedeWfTextbookRecedeItemMapper.insert(wfTextbookRecedeItem);
        }

        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean update(WfTextbookRecede wfTextbookRecede) {
        wfTextbookRecedeWfTextbookRecedeMapper.updateById(wfTextbookRecede);
        //********************************* WfTextbookRecedeItem  增删改  开始 *******************************************/
        {
            // 查出所有子级的id
            List<WfTextbookRecedeItem> wfTextbookRecedeItemList = wfTextbookRecedeWfTextbookRecedeItemMapper.selectList(Wrappers.lambdaQuery(WfTextbookRecedeItem.class).eq(WfTextbookRecedeItem::getWfTextbookRecedeId, wfTextbookRecede.getId()).select(WfTextbookRecedeItem::getId));
            List<Long> wfTextbookRecedeItemIds = wfTextbookRecedeItemList.stream().map(WfTextbookRecedeItem::getId).collect(Collectors.toList());
            //原有子表单 没有被删除的主键
            List<Long> wfTextbookRecedeItemOldIds = wfTextbookRecede.getWfTextbookRecedeItemList().stream().map(WfTextbookRecedeItem::getId).filter(Objects::nonNull).collect(Collectors.toList());
            //找到需要删除的id
            List<Long> wfTextbookRecedeItemRemoveIds = wfTextbookRecedeItemIds.stream().filter(item -> !wfTextbookRecedeItemOldIds.contains(item)).collect(Collectors.toList());

            for (WfTextbookRecedeItem wfTextbookRecedeItem : wfTextbookRecede.getWfTextbookRecedeItemList()) {
                //如果不等于空则修改
                if (wfTextbookRecedeItem.getId() != null) {
                    wfTextbookRecedeWfTextbookRecedeItemMapper.updateById(wfTextbookRecedeItem);
                }
                //如果等于空 则新增
                else {
                    //已经不存在的id 删除
                    wfTextbookRecedeItem.setWfTextbookRecedeId(wfTextbookRecede.getId());
                    wfTextbookRecedeWfTextbookRecedeItemMapper.insert(wfTextbookRecedeItem);
                }
            }
            //已经不存在的id 删除
            if(wfTextbookRecedeItemRemoveIds.size() > 0){
                wfTextbookRecedeWfTextbookRecedeItemMapper.deleteBatchIds(wfTextbookRecedeItemRemoveIds);
            }
        }
        //********************************* WfTextbookRecedeItem  增删改  结束 *******************************************/

        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean delete(List<Long> ids) {
        wfTextbookRecedeWfTextbookRecedeMapper.deleteBatchIds(ids);
        wfTextbookRecedeWfTextbookRecedeItemMapper.delete(Wrappers.lambdaQuery(WfTextbookRecedeItem.class).in(WfTextbookRecedeItem::getWfTextbookRecedeId, ids));

        return true;
    }

    @Override
    @Transactional
    public Boolean dataHandle(Long formId) {
        WfTextbookRecede wfTextbookRecede = this.getById(formId);
        if(ObjectUtil.isNotNull(wfTextbookRecede)){
            LambdaQueryWrapper<WfTextbookRecedeItem> queryWrapperItem = new LambdaQueryWrapper<>();
            queryWrapperItem
                    .eq(WfTextbookRecedeItem::getWfTextbookRecedeId, wfTextbookRecede.getId());
            List<WfTextbookRecedeItem> wfTextbookRecedeItemList = wfTextbookRecedeWfTextbookRecedeItemMapper.selectList(queryWrapperItem);
            if(ObjectUtil.isNotNull(wfTextbookRecedeItemList)){
                //遍历每一个退书申请项
                for (WfTextbookRecedeItem wfTextbookRecedeItem : wfTextbookRecedeItemList) {
                    //获取所退书籍的信息
                    Textbook textbook = textbookTextbookMapper.selectById(wfTextbookRecedeItem.getTextbookId());
                    //退书类型是到教务处
                    if(ObjectUtil.isNotNull(textbook) && wfTextbookRecede.getRecedeType().equals(RecedeTypeEnum.RecedeDeansOffice.getCode())){
                        //修改库存
                        textbookTextbookMapper.updateById(new Textbook(){{
                            setModifyUserId(StpUtil.getLoginIdAsLong());
                            setModifyDate(new Date());
                            setId(wfTextbookRecedeItem.getTextbookId());
                            setStock((ObjectUtil.isNull(textbook.getStock())?0:textbook.getStock()) + (ObjectUtil.isNull(wfTextbookRecedeItem.getNumber())?0:wfTextbookRecedeItem.getNumber()));
                        }});
                        //增加入库记录
                        textbookWarehouseRecordMapper.insert(new TextbookWarehouseRecord(){{
                            setCreateUserId(StpUtil.getLoginIdAsLong());
                            setCreateDate(new Date());
                            setTextbookId(wfTextbookRecedeItem.getTextbookId());
                            setDataId(wfTextbookRecede.getId());
                            setDataItemId(wfTextbookRecedeItem.getId());
                            setWarehouseMode(WarehouseModeEnum.WmRecede.getCode());
                            setWarehouseNumber(ObjectUtil.isNull(wfTextbookRecedeItem.getNumber())?0:wfTextbookRecedeItem.getNumber());
                            if(wfTextbookRecede.getClassId() != null && wfTextbookRecede.getClassId() > 0){
                                BaseClass c = baseClassMapper.selectById(wfTextbookRecede.getClassId());
                                setSource(c.getName());
                            }
                            QueryWrapper<TextbookWarehouseRecord> queryWrapperSortcode = new QueryWrapper<>();
                            queryWrapperSortcode.select("IFNULL(MAX(sort_code),0) as sortCode");
                            TextbookWarehouseRecord t = textbookWarehouseRecordMapper.selectOne(queryWrapperSortcode);
                            setSortCode(t.getSortCode()+1);
                        }});
                    }

                    //退书类型是到书店
                    if(ObjectUtil.isNotNull(textbook) && wfTextbookRecede.getRecedeType().equals(RecedeTypeEnum.RecedeBookstore.getCode())){
                        //修改库存
                        textbookTextbookMapper.updateById(new Textbook(){{
                            setModifyUserId(StpUtil.getLoginIdAsLong());
                            setModifyDate(new Date());
                            setId(wfTextbookRecedeItem.getTextbookId());
                            setStock((ObjectUtil.isNull(textbook.getStock())?0:textbook.getStock()) - (ObjectUtil.isNull(wfTextbookRecedeItem.getNumber())?0:wfTextbookRecedeItem.getNumber()) );
                        }});
                        //增加出库记录
                        textbookIssueRecordMapper.insert(new TextbookIssueRecord(){{
                            setCreateUserId(StpUtil.getLoginIdAsLong());
                            setCreateDate(new Date());
                            setTextbookId(wfTextbookRecedeItem.getTextbookId());
                            setDataId(wfTextbookRecede.getId());
                            setDataItemId(wfTextbookRecedeItem.getId());
                            setIssueMode(IssueModeEnum.ImRecede.getCode());
                            setIssueNumber(ObjectUtil.isNull(wfTextbookRecedeItem.getNumber())?0:wfTextbookRecedeItem.getNumber());
                            QueryWrapper<TextbookIssueRecord> queryWrapperSortcode = new QueryWrapper<>();
                            queryWrapperSortcode.select("IFNULL(MAX(sort_code),0) as sortCode");
                            TextbookIssueRecord t = textbookIssueRecordMapper.selectOne(queryWrapperSortcode);
                            setSortCode(t.getSortCode()+1);
                        }});
                    }
                }
            }
        }

        return true;
    }
}
