package com.jeeplus.psimanage.supplier.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
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.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.core.query.QueryWrapperGenerator;
import com.jeeplus.psimanage.supplier.domain.PsiMaterialSupplier;
import com.jeeplus.psimanage.supplier.domain.PsiMaterialSupplierLink;
import com.jeeplus.psimanage.supplier.mapper.PsiMaterialSupplierLinkMapper;
import com.jeeplus.psimanage.supplier.mapper.PsiMaterialSupplierMapper;
import com.jeeplus.psimanage.supplier.service.dto.PsiMaterialSupplierDTO;
import com.jeeplus.psimanage.supplier.service.dto.PsiMaterialSupplierLinkDTO;
import com.jeeplus.psimanage.supplier.service.mapstruct.PsiMaterialSupplierLinkWrapper;
import com.jeeplus.psimanage.supplier.service.mapstruct.PsiMaterialSupplierWrapper;
import com.jeeplus.psimanage.oss.service.PsiOssService;
import com.jeeplus.sys.feign.IWorkAttachmentApi;
import com.jeeplus.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional(rollbackFor = Exception.class)
public class PsiMaterialSupplierService extends ServiceImpl<PsiMaterialSupplierMapper, PsiMaterialSupplier> {

    @Autowired
    private PsiMaterialSupplierMapper psiMaterialSupplierMapper;

    @Autowired
    private PsiMaterialSupplierLinkMapper materialSupplierLinkMapper;

    @Autowired
    private PsiOssService psiOssService;

    public IPage<PsiMaterialSupplierDTO> findList(Page<PsiMaterialSupplierDTO> page, PsiMaterialSupplierDTO materialSupplierDTO) throws Exception{
        QueryWrapper<PsiMaterialSupplier> queryWrapper = QueryWrapperGenerator.buildQueryCondition ( PsiMaterialSupplierWrapper.INSTANCE.toEntity(materialSupplierDTO), PsiMaterialSupplier.class );
        queryWrapper.eq("ms.del_flag","0");
        if (ObjectUtil.isNotEmpty(materialSupplierDTO)) {
            // 根据联系人名称查询
            if (StringUtils.isNotBlank(materialSupplierDTO.getLinkName())) {
                List<String> supplierIdList = new ArrayList<>();
                List<PsiMaterialSupplierLink> materialSupplierLinks = materialSupplierLinkMapper.selectList(new LambdaQueryWrapper<PsiMaterialSupplierLink>().like(PsiMaterialSupplierLink::getName, materialSupplierDTO.getLinkName()));
                if (CollectionUtil.isNotEmpty(materialSupplierLinks)) {
                    supplierIdList.addAll(materialSupplierLinks.stream().map(PsiMaterialSupplierLink::getSupplierId).collect(Collectors.toList()));
                }
                if (CollectionUtil.isNotEmpty(supplierIdList)) {
                    queryWrapper.in("ms.id", supplierIdList);
                } else {
                    return new Page<>();
                }
            }
        }
        return psiMaterialSupplierMapper.findList(page,queryWrapper);
    }

    public PsiMaterialSupplierDTO queryById(String id) {

        PsiMaterialSupplierDTO materialSupplierDTO = psiMaterialSupplierMapper.queryById(id);

        return materialSupplierDTO;
    }

    public PsiMaterialSupplier saveSupplier(PsiMaterialSupplierDTO materialSupplierDTO) throws Exception{
        PsiMaterialSupplier materialSupplier = PsiMaterialSupplierWrapper.INSTANCE.toEntity(materialSupplierDTO);
        this.saveOrUpdate(materialSupplier);

        if (ObjectUtil.isNotEmpty(materialSupplierDTO)) {
            // 附件
            Map<String,String> map = new HashMap<>();
            String fileList = JSON.toJSONString((materialSupplierDTO.getWorkAttachmentDtoList()));
            String attachmentId = materialSupplier.getId();
            String attachmentFlag = "material_supplier";
            map.put("fileList",fileList);
            map.put("attachmentId",attachmentId);
            map.put("attachmentFlag",attachmentFlag);
            map.put("currentToken", TokenProvider.getCurrentToken ( ));
            SpringUtil.getBean ( IWorkAttachmentApi.class ).saveOrUpdateFileList(map);
//            ossService.saveOrUpdateFileList(materialSupplierDTO.getWorkAttachmentDtoList(), materialSupplier.getId(),"material_supplier");
            // 联系人信息
            if(CollectionUtil.isNotEmpty(materialSupplierDTO.getPsiMaterialSupplierLinkDTOList())){
                List<String> delIds = materialSupplierDTO.getPsiMaterialSupplierLinkDTOList().stream().distinct().filter(item -> {
                    if (StringUtils.isNotBlank(item.getId())) {
                        return true;
                    }
                    return false;
                }).map(PsiMaterialSupplierLinkDTO::getId).collect(Collectors.toList());
                if(CollectionUtil.isNotEmpty(delIds)){
                    materialSupplierLinkMapper.delete(new QueryWrapper<PsiMaterialSupplierLink>().lambda()
                            .eq(PsiMaterialSupplierLink::getSupplierId, materialSupplier.getId())
                            .notIn(PsiMaterialSupplierLink::getId,delIds));
                }else{
                    materialSupplierLinkMapper.delete(new QueryWrapper<PsiMaterialSupplierLink>().lambda().eq(PsiMaterialSupplierLink::getSupplierId, materialSupplier.getId()));
                }
                materialSupplierDTO.getPsiMaterialSupplierLinkDTOList().stream().forEach(item->{
                    PsiMaterialSupplierLink materialSupplierLink = PsiMaterialSupplierLinkWrapper.INSTANCE.toEntity(item);
                    if(StringUtils.isNotBlank(materialSupplierLink.getId())){
                        materialSupplierLinkMapper.updateById(materialSupplierLink);
                    }else{
                        materialSupplierLink.setSupplierId(materialSupplier.getId());
                        materialSupplierLinkMapper.insert(materialSupplierLink);
                    }
                });
            }else{
                materialSupplierLinkMapper.delete(new QueryWrapper<PsiMaterialSupplierLink>().lambda().eq(PsiMaterialSupplierLink::getSupplierId, materialSupplier.getId()));
            }
        }
        return materialSupplier;
    }

    public ResponseEntity deleteByIds(String ids) {
        String idArray[] =ids.split(",");
        if (idArray.length > 0) {
            List<String> supplierIds = Arrays.asList(idArray);
            if (CollectionUtil.isNotEmpty(supplierIds)) {
                // 删除联系人信息
                materialSupplierLinkMapper.delete(new LambdaQueryWrapper<PsiMaterialSupplierLink>().in(PsiMaterialSupplierLink::getSupplierId, supplierIds));
                // 删除附件
                SpringUtil.getBean ( IWorkAttachmentApi.class ).deleteByIds(JSON.toJSONString(supplierIds));
//                ossService.remove(new LambdaQueryWrapper<WorkAttachment>().in(WorkAttachment::getAttachmentId,supplierIds));
                // 删除供应商信息
                this.removeByIds (Lists.newArrayList (idArray));
            }
        }
        return ResponseEntity.ok ("删除成功");
    }

    public PsiMaterialSupplier findByName(String name) {
        PsiMaterialSupplier materialSupplier = this.getOne(new LambdaQueryWrapper<PsiMaterialSupplier>().eq(PsiMaterialSupplier::getName, name));
        return materialSupplier;
    }

}
