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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.metadata.IPage;
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.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.purchase.service.dto.MaterialInfoDto;
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.beans.BeanUtils;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author: 王强
 * @create: 2022-12-02 16:26
 **/
@Service
public class MaterialService {

    @Resource
    private MaterialBasicMapper basicMapper;

    @Resource
    private ContractInfoService infoService;

    @Resource
    private SerialnumTplService serialnumTplService;

    @Resource
    private MaterialDetailedMapper detailedMapper;

    @Resource
    private OssServiceMapper ossServiceMapper;

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

        queryWrapper.eq("a.del_flag", "0");
        if (StringUtils.isNotEmpty(dto.getPurchaseSketch())) {
            queryWrapper.like("a.purchase_sketch", dto.getPurchaseSketch());
        }
        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());
            }
        }
        if (StringUtils.isNotEmpty(dto.getStatus())) {
            queryWrapper.like("a.status", dto.getStatus());
        }
        //采购类别
        if (StringUtils.isNotEmpty(dto.getProcurementType())) {
            queryWrapper.like("b.procurement_type", dto.getProcurementType());
        }
        //经办人
        if (StringUtils.isNotEmpty(dto.getHandledBy())) {
            //根据经办人id查出经办人名称
//            String name = basicMapper.getHandledName(dto.getHandledBy());
//            dto.setHandledBy(name);
            queryWrapper.eq("su.name", dto.getHandledBy());
        }
        //合同金额
        //3、合同金额（区间）
        String[] contractAmounts = dto.getContractAmounts();
        if (contractAmounts != null) {
            if (StringUtils.isNotEmpty(contractAmounts[0])) {
                queryWrapper.ge("b.trade_total_price",contractAmounts[0]);
            }
            if (StringUtils.isNotEmpty(contractAmounts[1])) {
                queryWrapper.le("b.trade_total_price", contractAmounts[1]);
            }
        }
        String[] contractDates = dto.getContractDates();
        if (contractDates != null) {

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

        return basicMapper.findList(page, queryWrapper);
    }

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

    public String add(MaterialInfoDto dto, UserDTO userDTO) throws Exception{
        // 生成id
        String id = UUID.randomUUID().toString().replace("-", "");
        // 生成编号
        String no = serialnumTplService.genSerialNum(userDTO.getCompanyDTO().getId(), dto.BIZ_CODE);
        // 保存基础信息表信息
        MaterialBasic info = new MaterialBasic();
        BeanUtils.copyProperties(dto, info);
        info.setId(id);
//        info.setNo(no);
        info.setPurchaseNo(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 (MaterialDetailed detailed : dto.getDetailInfos()) {
                // 生成id
                String detailId = UUID.randomUUID().toString().replace("-", "");
                detailed.setId(detailId);
                detailed.setPurchaserAgent(detailed.getPurchaserAgentId());
                detailed.setProcurementType(detailed.getProcurementTypeId());
                detailed.setCreateBy(userDTO.getId());
                detailed.setCreateDate(new Date());
                detailed.setUpdateBy(userDTO.getId());
                detailed.setUpdateDate(new Date());
                detailed.setDelFlag(0);
                // 保存基础表信息主键值
                detailed.setBasicId(id);
                detailed.setTradeTotalPrice(dto.getTradeTotalPrice());
                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 String update(MaterialInfoDto dto, UserDTO userDTO) {
        // 修改基础信息
        MaterialBasic info = new MaterialBasic();
        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 (MaterialDetailed 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);
                });
            }

            for (MaterialDetailed detailInfo : dto.getDetailInfos()) {
                MaterialDetailed materialDetailed = detailedMapper.selectById(detailInfo.getId());
                if ( null == materialDetailed) {
                    // 生成id
                    String detailId = UUID.randomUUID().toString().replace("-", "");
                    detailInfo.setId(detailId);
                    detailInfo.setPurchaserAgent(detailInfo.getPurchaserAgentId());
                    detailInfo.setProcurementType(detailInfo.getProcurementTypeId());
                    detailInfo.setCreateBy(userDTO.getId());
                    detailInfo.setCreateDate(new Date());
                    detailInfo.setUpdateBy(userDTO.getId());
                    detailInfo.setUpdateDate(new Date());
                    detailInfo.setDelFlag(0);
                    // 保存基础表信息主键值
                    detailInfo.setBasicId(dto.getId());
                    detailInfo.setTradeTotalPrice(dto.getTradeTotalPrice());
                    detailedMapper.insert(detailInfo);
                    // 修改附件信息列表
                    if (CollectionUtils.isNotEmpty(detailInfo.getFileInfoLost())) {
                        infoService.saveFiles(detailInfo.getFileInfoLost(), userDTO, detailInfo.getId());
                    }
                } else {
                    detailInfo.setPurchaserAgent(detailInfo.getPurchaserAgentId());
                    detailInfo.setProcurementType(detailInfo.getProcurementTypeId());
                    detailInfo.setUpdateBy(userDTO.getId());
                    detailInfo.setUpdateDate(new Date());
                    detailInfo.setBasicId(dto.getId());
                    detailInfo.setTradeTotalPrice(dto.getTradeTotalPrice());
                    detailedMapper.updateById(detailInfo);
                    if (CollectionUtils.isNotEmpty(detailInfo.getFileInfoLost())) {
                        infoService.updateFiles(detailInfo.getFileInfoLost(), userDTO, detailInfo.getId());
                    }
                }

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

    public MaterialInfoDto findById(String id) {
        MaterialInfoDto dto = new MaterialInfoDto();
        // 查询基础信息表
        MaterialBasic info = basicMapper.selectById(id);
        if (ObjectUtils.isNotEmpty(info)) {
            BeanUtils.copyProperties(info, dto);
            //将采购详情数据查出
            List<MaterialDetailed> 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 String remove(String id) {
        // 删除基础信息表
        basicMapper.deleteById(id);
        // 删除详情列表 及对应附件信息
        List<MaterialDetailed> 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 void updateStatusById(MaterialInfoDto dto) {
        basicMapper.updateStatusById(dto.getId(), dto.getStatus());
    }
}
