package com.jeeplus.pubmodules.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.pubmodules.oss.domain.WorkAttachment;
import com.jeeplus.pubmodules.oss.service.OssService;
import com.jeeplus.pubmodules.supplier.domain.MaterialSupplier;
import com.jeeplus.pubmodules.supplier.domain.MaterialSupplierLink;
import com.jeeplus.pubmodules.supplier.mapper.MaterialSupplierLinkMapper;
import com.jeeplus.pubmodules.supplier.mapper.MaterialSupplierMapper;
import com.jeeplus.pubmodules.supplier.service.dto.MaterialSupplierDTO;
import com.jeeplus.pubmodules.supplier.service.dto.MaterialSupplierLinkDTO;
import com.jeeplus.pubmodules.supplier.service.mapstruct.MaterialSupplierLinkWrapper;
import com.jeeplus.pubmodules.supplier.service.mapstruct.MaterialSupplierWrapper;
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 javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional(rollbackFor = Exception.class)
public class MaterialSupplierService extends ServiceImpl<MaterialSupplierMapper, MaterialSupplier> {

    @Autowired
    private MaterialSupplierMapper materialSupplierMapper;

    @Autowired
    private MaterialSupplierLinkMapper materialSupplierLinkMapper;

    @Autowired
    private OssService ossService;

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

    public MaterialSupplierDTO queryById(String id) {

        MaterialSupplierDTO materialSupplierDTO = materialSupplierMapper.queryById(id);

        return materialSupplierDTO;
    }

    public MaterialSupplier saveSupplier(MaterialSupplierDTO materialSupplierDTO) throws Exception{
        MaterialSupplier materialSupplier = MaterialSupplierWrapper.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.getMaterialSupplierLinkDTOList())){
                List<String> delIds = materialSupplierDTO.getMaterialSupplierLinkDTOList().stream().distinct().filter(item -> {
                    if (StringUtils.isNotBlank(item.getId())) {
                        return true;
                    }
                    return false;
                }).map(MaterialSupplierLinkDTO::getId).collect(Collectors.toList());
                if(CollectionUtil.isNotEmpty(delIds)){
                    materialSupplierLinkMapper.delete(new QueryWrapper<MaterialSupplierLink>().lambda()
                            .eq(MaterialSupplierLink::getSupplierId, materialSupplier.getId())
                            .notIn(MaterialSupplierLink::getId,delIds));
                }else{
                    materialSupplierLinkMapper.delete(new QueryWrapper<MaterialSupplierLink>().lambda().eq(MaterialSupplierLink::getSupplierId, materialSupplier.getId()));
                }
                materialSupplierDTO.getMaterialSupplierLinkDTOList().stream().forEach(item->{
                    MaterialSupplierLink materialSupplierLink = MaterialSupplierLinkWrapper.INSTANCE.toEntity(item);
                    if(StringUtils.isNotBlank(materialSupplierLink.getId())){
                        materialSupplierLinkMapper.updateById(materialSupplierLink);
                    }else{
                        materialSupplierLink.setSupplierId(materialSupplier.getId());
                        materialSupplierLinkMapper.insert(materialSupplierLink);
                    }
                });
            }else{
                materialSupplierLinkMapper.delete(new QueryWrapper<MaterialSupplierLink>().lambda().eq(MaterialSupplierLink::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<MaterialSupplierLink>().in(MaterialSupplierLink::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 MaterialSupplier findByName(String name) {
        MaterialSupplier materialSupplier = this.getOne(new LambdaQueryWrapper<MaterialSupplier>().eq(MaterialSupplier::getName, name));
        return materialSupplier;
    }

}
