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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.jeeplus.core.query.QueryWrapperGenerator;
import com.jeeplus.sys.service.dto.UserDTO;
import com.jeeplus.sys.utils.StringUtils;
import com.jeeplus.sys.utils.UserUtils;
import com.jeeplus.test.cw.contractRegistration.service.ContractInfoService;
import com.jeeplus.test.materialManagement.purchase.domain.MaterialBasic;
import com.jeeplus.test.materialManagement.purchase.domain.MaterialDetailed;
import com.jeeplus.test.materialManagement.purchase.mapper.MaterialBasicMapper;
import com.jeeplus.test.materialManagement.purchase.mapper.MaterialDetailedMapper;
import com.jeeplus.test.materialManagement.wareHouse.domain.WareHouseBasic;
import com.jeeplus.test.materialManagement.wareHouse.domain.WareHouseDetailed;
import com.jeeplus.test.materialManagement.wareHouse.domain.WareHouseSummary;
import com.jeeplus.test.materialManagement.wareHouse.mapper.WareHouseBasicMapper;
import com.jeeplus.test.materialManagement.wareHouse.mapper.WareHouseDetailedMapper;
import com.jeeplus.test.materialManagement.wareHouse.mapper.WareHouseSummaryMapper;
import com.jeeplus.test.materialManagement.wareHouse.service.dto.WareHouseDto;
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.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * @author: 王强
 * @create: 2022-12-29 14:19
 **/
@Service
@Transactional
public class WareHouseBasicService {

    @Resource
    private MaterialBasicMapper materialBasicMapper;

    @Resource
    private WareHouseBasicMapper basicMapper;

    @Resource
    private WareHouseDetailedMapper detailedMapper;

    @Resource
    private WareHouseSummaryMapper summaryMapper;

    @Resource
    private MaterialDetailedMapper materialDetailedMapper;

    @Resource
    private OssServiceMapper ossServiceMapper;

    @Resource
    private SerialnumTplService serialnumTplService;

    @Resource
    private ContractInfoService infoService;

    public String remove(String id) {
        // 删除基础信息表
        basicMapper.deleteById(id);
        // 删除详情列表 及对应附件信息
        List<WareHouseDetailed> 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);
        //删除入库汇总表信息
        List<WareHouseSummary> summaryList = summaryMapper.getInfoByBasicId(id);
        summaryList.forEach(sum->{
            summaryMapper.deleteById(sum.getId());
        });
        return "操作成功";
    }

    public WareHouseDto findById(String id) {
        WareHouseDto dto = new WareHouseDto();
        // 查询基础信息表
        WareHouseBasic info = basicMapper.selectById(id);
        BeanUtils.copyProperties(info, dto);
        //将入库详情数据查出
        List<WareHouseDetailed> wareHouseList = detailedMapper.getByBasicId(id);
        if (CollectionUtils.isNotEmpty(wareHouseList)){
            wareHouseList.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);
            });
        }
        //将采购详情数据查出
        List<MaterialDetailed> detailedList = new ArrayList<>();
        if (StringUtils.isNotEmpty(info.getPurchaseNo())) {
            MaterialBasic basic = materialBasicMapper.getInfoByPurchaseNo(info.getPurchaseNo());
            if (null != basic) {
                detailedList = materialDetailedMapper.getByBasicId(basic.getId());
            }
        }

        if (CollectionUtils.isNotEmpty(detailedList)){
            detailedList.forEach(detailed->{
                //附件信息
                List<WorkAttachmentDto> acList = materialDetailedMapper.getByAttachmentId(detailed.getId());
                if (CollectionUtils.isNotEmpty(acList)) {
                    for (WorkAttachmentDto i : acList) {
                        i.setCreateBy(UserUtils.get(i.getBy()));
                    }
                }
                detailed.setFileInfoLost(acList);
            });
        }
        dto.setDetailInfos(detailedList);
        dto.setWareHouse(wareHouseList);
        //附件信息
        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 String save(WareHouseDto dto) throws Exception{
        // 获取当前登录人信息
        UserDTO userDTO = UserUtils.getCurrentUserDTO();
        if (StringUtils.isNotEmpty(dto.getId())) {
            return update(dto, userDTO);
        } else {
            return add(dto, userDTO);
        }
    }

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

            List<String> idList = detailedMapper.getIdByBasicId(info.getId());
            for (WareHouseDetailed detailInfo : dto.getWareHouse()) {
                //删除多余的领用详情
                //根据基础表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);
                    //汇总表中的数据也删除掉
                    summaryMapper.deleteByDetailedId(id);
                });
            }

            for (WareHouseDetailed detailInfo : dto.getWareHouse()) {
                // 生成id
                WareHouseDetailed wareHouseDetailed = detailedMapper.selectById(detailInfo.getId());
                if (null == wareHouseDetailed) {
                    String detailId = UUID.randomUUID().toString().replace("-", "");
                    detailInfo.setId(detailId);
                    detailInfo.setWareHouseMan(detailInfo.getWareHouseManId());
                    detailInfo.setCreateBy(userDTO.getId());
                    detailInfo.setCreateDate(new Date());
                    detailInfo.setWareHouseMan(detailInfo.getWareHouseManId());
                    detailInfo.setUpdateBy(userDTO.getId());
                    detailInfo.setUpdateDate(new Date());
                    detailInfo.setWareHouseType(detailInfo.getWareHouseTypeId());
                    detailInfo.setDelFlag(0);
                    // 保存基础表信息主键值
                    detailInfo.setBasicId(dto.getId());
                    detailInfo.setTradeTotalPrice(dto.getWareHouseTotalPrice());
                    detailedMapper.insert(detailInfo);
                    //保存详情列表附件信息
                    if (CollectionUtils.isNotEmpty(detailInfo.getFileInfoLost())){
                        infoService.saveFiles(detailInfo.getFileInfoLost(), userDTO, detailId);
                    }
                    //将入库详情商品信息汇总处理
                    //根据商品名称及入库类型查是否有相关数据
                    WareHouseSummary summary = summaryMapper.getInfoByTradeName(detailInfo.getTradeName(),detailInfo.getWareHouseType());;
                    if (null != summary) {
                        if (summary.getTradeName().equals(detailInfo.getTradeName()) &&
                                summary.getWareHouseType().equals(detailInfo.getWareHouseType())) {
                            String num = Double.valueOf(detailInfo.getTradeNumber())
                                    + Double.valueOf(summary.getTradeNumber()) + "";
                            summary.setTradeNumber(num);
                            summary.setWareHouseType(detailInfo.getWareHouseType());
                            summary.setUpdateBy(userDTO.getId());
                            summary.setUpdateDate(new Date());
                            summary.setDetailedId(detailInfo.getId());
                            summaryMapper.updateById(summary);
                        }
                    } else {
                        summary = new WareHouseSummary();
                        // 生成id
                        String summaryId = UUID.randomUUID().toString().replace("-", "");
                        summary.setDetailedId(detailInfo.getId());
                        summary.setId(summaryId);
                        summary.setCreateBy(userDTO.getId());
                        summary.setCreateDate(new Date());
                        summary.setUpdateBy(userDTO.getId());
                        summary.setUpdateDate(new Date());
                        summary.setDelFlag(0);
                        summary.setWareHouseType(detailInfo.getWareHouseType());
                        summary.setTradeName(detailInfo.getTradeName());
                        summary.setTradeNumber(detailInfo.getTradeNumber());
                        summaryMapper.insert(summary);
                    }
                } else {
                    detailInfo.setWareHouseMan(detailInfo.getWareHouseManId());
                    detailInfo.setUpdateBy(userDTO.getId());
                    detailInfo.setUpdateDate(new Date());
                    detailInfo.setDelFlag(0);
                    detailInfo.setWareHouseType(detailInfo.getWareHouseTypeId());
                    // 保存基础表信息主键值
                    detailInfo.setBasicId(dto.getId());
                    detailInfo.setTradeTotalPrice(dto.getWareHouseTotalPrice());
                    detailedMapper.updateById(detailInfo);
                    // 修改附件信息列表
                    if (CollectionUtils.isNotEmpty(detailInfo.getFileInfoLost())) {
                        infoService.updateFiles(detailInfo.getFileInfoLost(), userDTO, detailInfo.getId());
                    }
                    //将入库详情商品信息汇总处理
                    //根据商品名称及入库类型查是否有相关数据
                    WareHouseSummary summary = summaryMapper.getInfoByTradeName(detailInfo.getTradeName(),detailInfo.getWareHouseType());;
                    if (null != summary) {
                        if (wareHouseDetailed.getTradeNumber().equals(detailInfo.getTradeNumber()) &&
                                !wareHouseDetailed.getTradeName().equals(detailInfo.getTradeName())) {
                            String num = Double.valueOf(detailInfo.getTradeNumber())
                                    + Double.valueOf(summary.getTradeNumber()) + "";
                            summary.setTradeNumber(num);
                            summary.setUpdateBy(userDTO.getId());
                            summary.setWareHouseType(detailInfo.getWareHouseType());
                            summary.setUpdateDate(new Date());
                            summary.setDetailedId(detailInfo.getId());
                            summaryMapper.updateById(summary);
                        }
                    } else {
                        summary = new WareHouseSummary();
                        // 生成id
                        String summaryId = UUID.randomUUID().toString().replace("-", "");
                        summary.setDetailedId(detailInfo.getId());
                        summary.setId(summaryId);
                        summary.setCreateBy(userDTO.getId());
                        summary.setCreateDate(new Date());
                        summary.setUpdateBy(userDTO.getId());
                        summary.setUpdateDate(new Date());
                        summary.setDelFlag(0);
                        summary.setWareHouseType(detailInfo.getWareHouseType());
                        summary.setTradeName(detailInfo.getTradeName());
                        summary.setTradeNumber(detailInfo.getTradeNumber());
                        summaryMapper.insert(summary);
                    }
                }
            }
        }
        // 修改附件信息列表
        if (CollectionUtils.isNotEmpty(dto.getFiles())) {
            infoService.updateFiles(dto.getFiles(), userDTO, dto.getId());
        }
        return dto.getId();
    }

    public String add(WareHouseDto dto, UserDTO userDTO) throws Exception{
        // 生成id
        String id = UUID.randomUUID().toString().replace("-", "");
        // 生成编号
        String no = serialnumTplService.genSerialNum(userDTO.getCompanyDTO().getId(), dto.BIZ_CODE);
        // 保存基础信息表信息
        WareHouseBasic info = new WareHouseBasic();
        BeanUtils.copyProperties(dto, info);
        info.setId(id);
//        info.setNo(no);
        info.setWareHouseNumber(no);
        info.setHandledBy(dto.getHandledById());
        info.setPurchaseNo(dto.getPurchaseNo());
        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.getWareHouse())) {
            for (WareHouseDetailed detailed : dto.getWareHouse()) {
                // 生成id
                String detailId = UUID.randomUUID().toString().replace("-", "");
                detailed.setWareHouseMan(detailed.getWareHouseManId());
                detailed.setId(detailId);
                detailed.setCreateBy(userDTO.getId());
                detailed.setCreateDate(new Date());
                detailed.setUpdateBy(userDTO.getId());
                detailed.setUpdateDate(new Date());
                detailed.setDelFlag(0);
                detailed.setWareHouseType(detailed.getWareHouseTypeId());
                // 保存基础表信息主键值
                detailed.setBasicId(id);
                detailed.setTradeTotalPrice(dto.getWareHouseTotalPrice());
                detailedMapper.insert(detailed);
                //保存详情列表附件信息
                if (CollectionUtils.isNotEmpty(detailed.getFileInfoLost())){
                    infoService.saveFiles(detailed.getFileInfoLost(), userDTO, detailId);
                }
                //将入库详情商品信息汇总处理
                //根据商品名称及入库类型查是否有相关数据
                WareHouseSummary summary = summaryMapper.getInfoByTradeName(detailed.getTradeName(),detailed.getWareHouseType());;
                if (null != summary) {
                    String num = Double.valueOf(detailed.getTradeNumber())
                            + Double.valueOf(summary.getTradeNumber()) + "";
                    summary.setTradeNumber(num);
                    summaryMapper.updateById(summary);
                } else {
                    summary = new WareHouseSummary();
                    // 生成id
                    String summaryId = UUID.randomUUID().toString().replace("-", "");
                    summary.setDetailedId(detailed.getId());
                    summary.setId(summaryId);
                    summary.setCreateBy(userDTO.getId());
                    summary.setCreateDate(new Date());
                    summary.setUpdateBy(userDTO.getId());
                    summary.setUpdateDate(new Date());
                    summary.setDelFlag(0);
                    summary.setWareHouseType(detailed.getWareHouseType());
                    summary.setTradeName(detailed.getTradeName());
                    summary.setTradeNumber(detailed.getTradeNumber());
                    summaryMapper.insert(summary);
                }
            }
        }
        // 保存附件列表信息
        if (CollectionUtils.isNotEmpty(dto.getFiles())) {
            infoService.saveFiles(dto.getFiles(), userDTO, id);
        }
        return id;
    }

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

        queryWrapper.eq("a.del_flag", "0");
        if (StringUtils.isNotEmpty(dto.getWareHouseNumber())) {
            queryWrapper.like("a.ware_house_number", dto.getWareHouseNumber());
        }
        if (StringUtils.isNotEmpty(dto.getWareHouseName())) {
            queryWrapper.like("a.ware_house_name", dto.getWareHouseName());
        }
        if (StringUtils.isNotEmpty(dto.getHandledBy())) {
            queryWrapper.like("a.handled_by", dto.getHandledBy());
        }
        if (StringUtils.isNotEmpty(dto.getHandledByOffice())) {
            queryWrapper.like("a.handled_by_office", dto.getHandledByOffice());
        }
        if (StringUtils.isNotEmpty(dto.getStatus())) {
            queryWrapper.like("a.status", dto.getStatus());
        }
        // 入库时间
        String[] contractDates = dto.getWareHouseDates();
        if (contractDates != null) {

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

        return basicMapper.findList(page, queryWrapper);
    }

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

        queryWrapper.eq("a.del_flag", "0");
        queryWrapper.gt("a.trade_number", "0");

        if (StringUtils.isNotEmpty(dto.getWareHouseNumber())) {
            queryWrapper.like("c.ware_house_number", dto.getWareHouseNumber());
        }
        if (StringUtils.isNotEmpty(dto.getTradeName())) {
            queryWrapper.like("b.trade_name", dto.getTradeName());
        }
        if (StringUtils.isNotEmpty(dto.getWareHouseMan())) {
            queryWrapper.like("b.ware_house_man", dto.getWareHouseMan());
        }
        if (StringUtils.isNotEmpty(dto.getWareHouseManOffice())) {
            queryWrapper.like("so.id", dto.getWareHouseManOffice());
        }

        //入库类型
        if (StringUtils.isNotEmpty(dto.getWareHouseType())) {
            queryWrapper.eq("d.name", dto.getWareHouseType());
        }

        // 入库时间
        String[] contractDates = dto.getWareHouseDates();
        if (contractDates != null) {

            queryWrapper.between("c.ware_house_date", contractDates[0], contractDates[1]);
        }

        return basicMapper.summaryList(page, queryWrapper);
    }

    public String findRequestId(String purchaseNo) {
        return basicMapper.findRequestId(purchaseNo);
    }

    public String updateStatusById(WareHouseDto dto) {
        WareHouseBasic wareHouseBasic = new WareHouseBasic();
        BeanUtils.copyProperties(dto,wareHouseBasic);
        basicMapper.update(wareHouseBasic, new QueryWrapper<WareHouseBasic>().lambda().eq(WareHouseBasic::getId, wareHouseBasic.getId()));
        return "操作成功";
    }

}
