package com.jeeplus.test.materialManagement.collect.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jeeplus.core.query.QueryWrapperGenerator;
import com.jeeplus.sys.service.dto.UserDTO;
import com.jeeplus.sys.utils.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.jeeplus.sys.utils.UserUtils;
import com.jeeplus.test.cw.contractRegistration.service.ContractInfoService;
import com.jeeplus.test.materialManagement.collect.domain.CollectBasic;
import com.jeeplus.test.materialManagement.collect.domain.CollectDetailed;
import com.jeeplus.test.materialManagement.collect.mapper.CollectBasicMapper;
import com.jeeplus.test.materialManagement.collect.mapper.CollectDetailedMapper;
import com.jeeplus.test.materialManagement.collect.service.dto.CollectDto;
import com.jeeplus.test.materialManagement.collect.service.dto.WareHouseSummaryDto;
import com.jeeplus.test.materialManagement.wareHouse.domain.WareHouseSummary;
import com.jeeplus.test.materialManagement.wareHouse.mapper.WareHouseSummaryMapper;
import com.jeeplus.test.mould.service.SerialnumTplService;
import com.jeeplus.test.oss.domain.WorkAttachment;
import com.jeeplus.test.oss.mapper.OssServiceMapper;
import com.jeeplus.test.workContract.service.dto.WorkAttachmentDto;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import org.springframework.beans.BeanUtils;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 领用表
 * @author: 王强
 * @create: 2023-01-03 16:24
 **/
@Service
@Transactional
public class CollectService {

    @Resource
    private CollectBasicMapper basicMapper;

    @Resource
    private CollectDetailedMapper detailedMapper;

    @Resource
    private WareHouseSummaryMapper summaryMapper;

    @Resource
    private SerialnumTplService serialnumTplService;

    @Resource
    private ContractInfoService infoService;

    @Resource
    private OssServiceMapper ossServiceMapper;

    public void updateStatusById(CollectDto dto) {
        basicMapper.updateStatusById(dto.getId(), dto.getStatus());
    }

    public String remove(String id) {
        // 删除基础信息表
        basicMapper.deleteById(id);
        // 删除详情列表 及对应附件信息
        List<CollectDetailed> detailedList = detailedMapper.getByBasicId(id);
        if (null != detailedList){
            detailedList.forEach(de->{
                //附件
                List<WorkAttachmentDto> fileList = detailedMapper.getByAttachmentId(de.getId());
                if ( null != fileList ){
                    fileList.forEach(f->{
                        ossServiceMapper.deleteById(f.getId());
                    });
                }
                detailedMapper.deleteById(de.getId());
            });
        }
        // 删除附件信息
        LambdaQueryWrapper<WorkAttachment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WorkAttachment::getAttachmentId, id);
        ossServiceMapper.delete(wrapper);
        return "操作成功";
    }

    public String save(CollectDto dto) throws Exception{
        // 获取当前登录人信息
        UserDTO userDTO = UserUtils.getCurrentUserDTO();
        synchronized (this) {
            if (StringUtils.isNotEmpty(dto.getId()) && !dto.getId().equals("false")) {
                return update(dto, userDTO);
            } else {
                return add(dto, userDTO);
            }
        }

    }

    public String update(CollectDto dto, UserDTO userDTO) {
        // 修改基础信息
        CollectBasic info = new CollectBasic();
        BeanUtils.copyProperties(dto, info);
        info.setUpdateBy(userDTO.getId());
        info.setHandledBy(dto.getHandledById());
        info.setUpdateDate(new Date());
        basicMapper.updateById(info);
        // 修改报销详情列表信息
        // 删除原有数据
//        LambdaQueryWrapper<MaterialDetailed> detailWrapper = new LambdaQueryWrapper<>();
//        detailWrapper.eq(MaterialDetailed::getBasicId, dto.getId());
//        detailedMapper.delete(detailWrapper);
        if (CollectionUtils.isNotEmpty(dto.getDetailInfos())) {

            List<String> idList = detailedMapper.getIdByBasicId(info.getId());
            for (CollectDetailed detailInfo : dto.getDetailInfos()) {
                //删除多余的领用详情
                //根据基础表id获取所有的详情表id
                if (null != idList) {
                    if (idList.contains(detailInfo.getId())){
                        idList.remove(detailInfo.getId());
                    }
                }
            }
            if (null != idList & idList.size()>0) {
                idList.forEach(id->{
                    detailedMapper.deleteById(id);
                });
            }

            if (StringUtils.isNotEmpty(dto.getSign())) {

            } else {
                for (CollectDetailed detailInfo : dto.getDetailInfos()) {

                    CollectDetailed materialDetailed = detailedMapper.selectById(detailInfo.getId());
                    if (StringUtils.isEmpty(detailInfo.getCollectNumber())){
                        detailInfo.setCollectNumber("0");
                    }
                    if ( null == materialDetailed) {
                        // 生成id
                        String detailId = UUID.randomUUID().toString().replace("-", "");
                        detailInfo.setId(detailId);
                        detailInfo.setRecipientAgent(detailInfo.getRecipientAgentId());
                        detailInfo.setCollectType(detailInfo.getCollectTypeId());
                        detailInfo.setCreateBy(userDTO.getId());
                        detailInfo.setCreateDate(new Date());
                        detailInfo.setUpdateBy(userDTO.getId());
                        detailInfo.setUpdateDate(new Date());
                        detailInfo.setDelFlag(0);
                        // 保存基础表信息主键值
                        detailInfo.setBasicId(dto.getId());
                        detailedMapper.insert(detailInfo);
                        // 修改附件信息列表
                        if (CollectionUtils.isNotEmpty(detailInfo.getFileInfoLost())) {
                            infoService.saveFiles(detailInfo.getFileInfoLost(), userDTO, detailInfo.getId());
                        }
                    } else {
                        detailInfo.setRecipientAgent(detailInfo.getRecipientAgentId());
                        detailInfo.setCollectType(detailInfo.getCollectTypeId());
                        detailInfo.setUpdateBy(userDTO.getId());
                        detailInfo.setUpdateDate(new Date());
                        detailInfo.setBasicId(dto.getId());
                        detailedMapper.updateById(detailInfo);
                        if (CollectionUtils.isNotEmpty(detailInfo.getFileInfoLost())) {
                            infoService.updateFiles(detailInfo.getFileInfoLost(), userDTO, detailInfo.getId());
                        }
                    }

                    //当流程结束的时候 修改入库汇总表的数量
                    if ( StringUtils.isNotEmpty(info.getStatus()) && info.getStatus().equals("5")){
                        //根据商品名称 及 领用类型查询汇总表修改改商品库存数量
                        WareHouseSummary summaryInfo = summaryMapper.getInfoByTradeName(detailInfo.getGoodsName(), detailInfo.getCollectType());
                        if (null != summaryInfo) {
                            String num = Double.parseDouble(summaryInfo.getTradeNumber())
                                    - Double.parseDouble(detailInfo.getCollectNumber()) + "";
                            summaryInfo.setTradeNumber(num);
                            summaryMapper.updateById(summaryInfo);
                        }
                    }

                }
            }

        }
        // 修改附件信息列表
        if (CollectionUtils.isNotEmpty(dto.getFiles())) {
            infoService.updateFiles(dto.getFiles(), userDTO, dto.getId());
        }
        return dto.getId();
    }

    public String add(CollectDto dto, UserDTO userDTO) throws Exception{
        // 生成id
        String id = UUID.randomUUID().toString().replace("-", "");
        // 生成编号
        String no = serialnumTplService.genSerialNum(userDTO.getCompanyDTO().getId(), dto.BIZ_CODE);
        // 保存基础信息表信息
        CollectBasic info = new CollectBasic();
        BeanUtils.copyProperties(dto, info);
        info.setId(id);
        info.setCollectNo(no);
        info.setHandledBy(dto.getHandledById());
        info.setCreateBy(userDTO.getId());
        info.setCreateDate(new Date());
        info.setUpdateBy(userDTO.getId());
        info.setUpdateDate(new Date());
        info.setDelFlag(0);
        basicMapper.insert(info);
        // 保存详情列表信息
        if (CollectionUtils.isNotEmpty(dto.getDetailInfos())) {
            for (CollectDetailed detailed : dto.getDetailInfos()) {
                // 生成id
                String detailId = UUID.randomUUID().toString().replace("-", "");
                detailed.setId(detailId);
                detailed.setRecipientAgent(detailed.getRecipientAgentId());
                detailed.setCollectType(detailed.getCollectTypeId());
                detailed.setCreateBy(userDTO.getId());
                detailed.setCreateDate(new Date());
                detailed.setUpdateBy(userDTO.getId());
                detailed.setUpdateDate(new Date());
                detailed.setDelFlag(0);
                // 保存基础表信息主键值
                detailed.setBasicId(id);
                detailedMapper.insert(detailed);
                //保存详情列表附件信息
                if (CollectionUtils.isNotEmpty(detailed.getFileInfoLost())){
                    infoService.saveFiles(detailed.getFileInfoLost(), userDTO, detailId);
                }

            }
        }
        // 保存附件列表信息
        if (CollectionUtils.isNotEmpty(dto.getFiles())) {
            infoService.saveFiles(dto.getFiles(), userDTO, id);
        }
        return id;
    }

    public CollectDto findById(String id) {
        CollectDto dto = new CollectDto();
        // 查询基础信息表
        CollectBasic info = basicMapper.selectById(id);
        if (ObjectUtils.isNotEmpty(info)) {
            BeanUtils.copyProperties(info, dto);
            //将采购详情数据查出
            List<CollectDetailed> detailedList = detailedMapper.getByBasicId(id);
            if (CollectionUtils.isNotEmpty(detailedList)){
                detailedList.forEach(detailed->{
                    //附件信息
                    List<WorkAttachmentDto> acList = detailedMapper.getByAttachmentId(detailed.getId());
                    if (CollectionUtils.isNotEmpty(acList)) {
                        for (WorkAttachmentDto i : acList) {
                            i.setCreateBy(UserUtils.get(i.getBy()));
                        }
                    }
                    detailed.setFileInfoLost(acList);
                });
            }
            dto.setDetailInfos(detailedList);
            //附件信息
            List<WorkAttachmentDto> files = detailedMapper.getByAttachmentId(info.getId());
            if (CollectionUtils.isNotEmpty(files)) {
                for (WorkAttachmentDto i : files) {
                    i.setCreateBy(UserUtils.get(i.getBy()));
                }
            }
            //根据经办人id查出经办人的名称
            String name = basicMapper.getUserNameByUserId(info.getHandledBy());
            dto.setHandledBy(name);
            dto.setHandledById(info.getHandledBy());
            dto.setFiles(files);
        }
        return dto;
    }

    /**
     * 列表查询
     */
    public IPage<CollectDto> list(Page<CollectDto> page , CollectDto dto) throws Exception{
        QueryWrapper<CollectDto> queryWrapper = QueryWrapperGenerator.buildQueryCondition(dto, CollectDto.class);

        queryWrapper.eq("a.del_flag", "0");
        if (StringUtils.isNotEmpty(dto.getCollectNo())) {
            queryWrapper.like("a.collect_no", dto.getCollectNo());
        }
        if (StringUtils.isNotEmpty(dto.getGoodsName())) {
            queryWrapper.like("b.goods_name", dto.getGoodsName());
        }
        if (StringUtils.isNotEmpty(dto.getHandledBy())) {
            queryWrapper.eq("su.name", dto.getHandledBy());
        }
        if (StringUtils.isNotEmpty(dto.getHandledByOffice())) {
            //先根据id查出是否是父节点，是父节点则查出所有的子节点信息
            List<String> childIds = basicMapper.findChildIds(dto.getHandledByOffice());
            if ( null != childIds & childIds.size()>0){
                childIds.add(dto.getHandledByOffice());
                queryWrapper.in("a.handled_by_office",childIds);
            }else {
                queryWrapper.eq("a.handled_by_office", dto.getHandledByOffice());
            }
        }
        String[] contractDates = dto.getCollectDates();
        if (contractDates != null) {

            queryWrapper.between("a.collect_date", contractDates[0], contractDates[1]);
        }

        return basicMapper.findList(page, queryWrapper);
    }

    /**
     * 列表查询
     */
    public IPage<WareHouseSummaryDto> wareHouseList(Page<WareHouseSummaryDto> page , WareHouseSummaryDto dto) throws Exception{
        QueryWrapper<WareHouseSummaryDto> queryWrapper = QueryWrapperGenerator.buildQueryCondition(dto, WareHouseSummaryDto.class);

        queryWrapper.eq("a.del_flag", "0");
        queryWrapper.eq("a.ware_house_type", dto.getWareHouseType());
        queryWrapper.gt("a.trade_number", 0);
        if (StringUtils.isNotEmpty(dto.getTradeName())) {
            queryWrapper.like("a.trade_name", dto.getTradeName());
        }

        return basicMapper.findWareHouseList(page, queryWrapper);
    }
}
