package com.storlead.sales.service.impl.customer;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.storlead.framework.common.constant.CommonConstant;
import com.storlead.framework.common.util.DateUtils;
import com.storlead.framework.common.util.OssBootUtil;
import com.storlead.framework.util.LoginUserUtil;
import com.storlead.framework.auth.vo.LoginUser;
import com.storlead.framework.common.result.Result;
import com.storlead.framework.mybatis.entity.SysBaseField;
import com.storlead.framework.mybatis.service.impl.MyBaseServiceImpl;
import com.storlead.sales.pojo.dto.customer.SysResourceSearchDTO;
import com.storlead.sales.pojo.entity.customer.SysResourceEntity;
import com.storlead.sales.pojo.entity.customer.CustomerEntity;
import com.storlead.sales.pojo.entity.customer.SysResourceEntity;
import com.storlead.sales.pojo.vo.customer.CustomerFollowUpLastVO;
import com.storlead.sales.pojo.vo.customer.SysResourceListVO;
import com.storlead.sales.pojo.vo.customer.SysResourceVO;
import com.storlead.sales.enums.ResourceTypeEnum;
import com.storlead.sales.mapper.customer.SysResourceMapper;
import com.storlead.sales.service.customer.SysResourceService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

import static cn.hutool.core.date.DateTime.now;

/**
 * <p>
 * 系统资源表 服务实现类
 * </p>
 *
 * @author YPZ
 * @since 2024-04-29
 */
@Service
public class SysResourceServiceImpl extends MyBaseServiceImpl<SysResourceMapper, SysResourceEntity> implements SysResourceService {

    @Override
    public boolean changeResourceCustomerId(Long fromId, Long customerId) {
        if (Objects.isNull(customerId) || Objects.isNull(fromId)) {
            return false;
        }
        LambdaUpdateWrapper<SysResourceEntity> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SysResourceEntity::getResourceType, ResourceTypeEnum.CUSTOMER.code);
        updateWrapper.eq(SysResourceEntity::getResourceTypeId,fromId);
        updateWrapper.set(SysResourceEntity::getResourceTypeId,customerId);
        return this.update(updateWrapper);
    }

    @Override
    public boolean delete(String resourceType, Long resourceTypeId) {
        LambdaQueryWrapper<SysResourceEntity> wrapper =  new LambdaQueryWrapper();
        wrapper.eq(SysResourceEntity::getResourceType, resourceType);
        wrapper.eq(SysResourceEntity::getResourceTypeId,resourceTypeId);
        return this.baseMapper.delete(wrapper)>0 ;
    }

    @Override
    public boolean updateDelete(String resourceType, Long resourceTypeId) {
        LambdaUpdateWrapper<SysResourceEntity> wrapper =  new LambdaUpdateWrapper();
        wrapper.eq(SysResourceEntity::getResourceType, resourceType);
        wrapper.eq(SysResourceEntity::getResourceTypeId,resourceTypeId);
        wrapper.set(SysResourceEntity::getIsDelete, CommonConstant.DEL_FLAG_1);
        return update(wrapper);
    }

    @Override
    public Result<IPage<SysResourceListVO>> selectListVO(SysResourceSearchDTO sysResourceSearchDTO) {
        IPage<SysResourceListVO> pageVO = new Page<>(sysResourceSearchDTO.getPageIndex(), sysResourceSearchDTO.getPageSize());
        IPage<SysResourceEntity> page = new Page<>(sysResourceSearchDTO.getPageIndex(), sysResourceSearchDTO.getPageSize());
        LambdaQueryWrapper<SysResourceEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysResourceEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        wrapper.eq(!ObjectUtils.isEmpty(sysResourceSearchDTO.getCustomerId()),SysResourceEntity::getCustomerId, sysResourceSearchDTO.getCustomerId());
        wrapper.eq(!ObjectUtils.isEmpty(sysResourceSearchDTO.getResourceType()),SysResourceEntity::getResourceType, sysResourceSearchDTO.getResourceType());
        wrapper.eq(!ObjectUtils.isEmpty(sysResourceSearchDTO.getResourceTypeId()),SysResourceEntity::getResourceTypeId, sysResourceSearchDTO.getResourceTypeId());
        wrapper.like(!ObjectUtils.isEmpty(sysResourceSearchDTO.getRemark()),SysResourceEntity::getRemark, sysResourceSearchDTO.getRemark());
//        page = pageWithScope(page, wrapper,sysResourceSearchDTO,"");
        page = page(page, wrapper);
        if (CollectionUtils.isEmpty(page.getRecords())){
            return Result.result(pageVO);
        }
//        List<CustomerListVO> customerListVO = new ArrayList<>();
        //复制list给VO类
        pageVO = SysBaseField.page(page, SysResourceListVO.class);

        SysBaseField.dictFileds(pageVO.getRecords());
        SysBaseField.orgFileds(pageVO.getRecords());
        return Result.result(pageVO);
    }



    /***
     * @Description: 更新附件
     * @Param: resourceType,typeId,resourceList
     * @return: boolean
     * @Author: YPZ
     * @Date: 2022/11/16 15:53
     */
    @Override
    public boolean updateResource(String resourceType, Long typeId, List<SysResourceEntity> resourceList){
        //删除已有资源
        this.delete(resourceType,typeId);
        if(resourceList!=null&& resourceList.size()>0) {
            resourceList.forEach(
                    (resource) -> {
                        resource.setResourceType(resourceType);
                        resource.setResourceTypeId(typeId);
                    }
            );
            this.saveBatch(resourceList);
        }
        return true;
    }

    @Override
    public Result saveVo(SysResourceVO sysResourceVO) {
        MultipartFile file = sysResourceVO.getFile();
        long fileSize = file.getSize();
        if (file == null || fileSize <= 0) {
            return Result.error("file不存在");
        }

        String uploadFilePath = file.getOriginalFilename();
        if (StringUtils.isNotBlank(uploadFilePath)) {
            String url = upload(file);
            SysResourceEntity sysResourceEntity =  new SysResourceEntity();
            BeanUtils.copyProperties(sysResourceVO, sysResourceEntity);
            String resourceName = sysResourceVO.getResourceName() == null ? file.getOriginalFilename() : sysResourceVO.getResourceName();
            sysResourceEntity.setResourceName(resourceName);
            sysResourceEntity.setResourceSize(getFileSize(file.getSize()));
            sysResourceEntity.setResourceUrl(url);
            LoginUser loginUser = LoginUserUtil.getLoginUser();
            sysResourceEntity.setCreateBy(Long.parseLong(loginUser.getId()+""));
            sysResourceEntity.setCreateTime(now());
            boolean save = this.save(sysResourceEntity);
            return Result.result(sysResourceEntity);
        }
        return Result.error("上传文件失败,请检查文件是否提交");
    }



    //String newBucketName,String newEndPoint

    @Override
    public Result saveFileList(SysResourceVO sysResourceVO) {
        List<MultipartFile> fileList = sysResourceVO.getFileList();
        List<SysResourceEntity> sysResourceList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(fileList)){
            for (MultipartFile file : fileList){
                SysResourceEntity sysResource = addFile(file);
                if (!ObjectUtils.isEmpty(sysResource)){
                    if (!ObjectUtils.isEmpty(sysResourceVO.getRemark())){
                        sysResource.setRemark(sysResourceVO.getRemark());
                    }
                    sysResourceList.add(sysResource);
                }
            }
        }
        if (!CollectionUtils.isEmpty(sysResourceList)){
            boolean isOk = this.saveBatch(sysResourceList);
            if (isOk){
                List<Long> idList = sysResourceList.stream().map(SysResourceEntity::getId).collect(Collectors.toList());
                return Result.result(idList);
            }
        }


        return null;
    }

    @Override
    public Result uploadFileList(SysResourceVO sysResourceVO) {
        //storlead-material-entry-test
        List<MultipartFile> fileList = sysResourceVO.getFileList();
        List<SysResourceEntity> sysResourceList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(fileList)){
            for (MultipartFile file : fileList){
                SysResourceEntity sysResource = addFile(file);
                if (!ObjectUtils.isEmpty(sysResource)){
                    if (!ObjectUtils.isEmpty(sysResourceVO.getRemark())){
                        sysResource.setRemark(sysResourceVO.getRemark());
                    }
                    sysResourceList.add(sysResource);
                }
            }
        }
        if (!CollectionUtils.isEmpty(sysResourceList)){
            boolean isOk = this.saveBatch(sysResourceList);
            if (isOk){
                return Result.result(sysResourceList);
            }
        }
        return null;
    }

    @Override
    public Result saveVo(SysResourceVO sysResourceVO,String newBucketName,String newEndPoint) {
        MultipartFile file = sysResourceVO.getFile();
        long fileSize = file.getSize();
        if (file == null || fileSize <= 0) {
            return Result.error("file不存在");
        }

        String uploadFilePath = file.getOriginalFilename();
        if (StringUtils.isNotBlank(uploadFilePath)) {
            String url = upload(file,newBucketName,newEndPoint);
            log.error("--------------------url="+url);
            SysResourceEntity sysResourceEntity =  new SysResourceEntity();
            BeanUtils.copyProperties(sysResourceVO, sysResourceEntity);
            String resourceName = sysResourceVO.getResourceName() == null ? file.getOriginalFilename() : sysResourceVO.getResourceName();
            sysResourceEntity.setResourceName(resourceName);
            sysResourceEntity.setResourceSize(getFileSize(file.getSize()));
            sysResourceEntity.setResourceUrl(url);
            LoginUser loginUser = LoginUserUtil.getLoginUser();
            sysResourceEntity.setCreateBy(Long.parseLong(loginUser.getId()+""));
            sysResourceEntity.setCreateTime(now());
            boolean save1 = this.save(sysResourceEntity);
            return Result.result(sysResourceEntity);
        }
        return Result.error("上传文件失败,请检查文件是否提交");
    }

    @Override
    public Result uploadFileList(SysResourceVO sysResourceVO,String newBucketName,String newEndPoint) {

        List<MultipartFile> fileList = sysResourceVO.getFileList();
        List<SysResourceEntity> sysResourceList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(fileList)){
            for (MultipartFile file : fileList){
                SysResourceEntity sysResource = addFile(file,newBucketName,newEndPoint);
                if (!ObjectUtils.isEmpty(sysResource)){
                    if (!ObjectUtils.isEmpty(sysResourceVO.getRemark())){
                        sysResource.setRemark(sysResourceVO.getRemark());
                    }
                    sysResourceList.add(sysResource);
                }
            }
        }

        if (!CollectionUtils.isEmpty(sysResourceList)){
            boolean isOk = this.saveBatch(sysResourceList);
            if (isOk){
                return Result.result(sysResourceList);
            }
        }
        return null;
    }

    @Override
    public Result addResourceByIdList(SysResourceVO sysResourceVO) {
        if (CollectionUtils.isEmpty(sysResourceVO.getIdList())){
            return Result.error("idList参数异常");
        }

            List<SysResourceEntity> sysResourceList = new ArrayList<>();
            for (Long id : sysResourceVO.getIdList()){
                SysResourceEntity sysResource = new SysResourceEntity();
                BeanUtils.copyProperties(sysResourceVO,sysResource);
                sysResource.setId(id);
                if (!ObjectUtils.isEmpty(sysResourceVO.getCustomerId())){
                    sysResource.setCustomerId(sysResourceVO.getCustomerId());
                }
                sysResourceList.add(sysResource);
           }
            boolean isOk = saveOrUpdateBatch(sysResourceList);
            if (isOk){
                return Result.result("上传成功");
            }
        return Result.error("上传失败");
    }

    private SysResourceEntity addFile(MultipartFile file) {
        long fileSize = file.getSize();
        if (file == null || fileSize <= 0) {
            return null;
        }

        String uploadFilePath = file.getOriginalFilename();
        if (StringUtils.isNotBlank(uploadFilePath)) {
            String url = upload(file);
            SysResourceEntity sysResourceEntity =  new SysResourceEntity();
//            BeanUtils.copyProperties(sysResourceVO, sysResourceEntity);
            String resourceName = file.getOriginalFilename();
            sysResourceEntity.setResourceName(resourceName);
            sysResourceEntity.setResourceSize(getFileSize(file.getSize()));
            sysResourceEntity.setResourceUrl(url);
            LoginUser loginUser = LoginUserUtil.getLoginUser();
            sysResourceEntity.setCreateBy(Long.parseLong(loginUser.getId()+""));
            sysResourceEntity.setCreateTime(now());
            return sysResourceEntity;
        }
        return null;
    }

    private SysResourceEntity addFile(MultipartFile file,String newBucketName,String newEndPoint) {
        long fileSize = file.getSize();
        if (file == null || fileSize <= 0) {
            return null;
        }

        String uploadFilePath = file.getOriginalFilename();
        if (StringUtils.isNotBlank(uploadFilePath)) {
            String url = upload(file,newBucketName,newEndPoint);
            SysResourceEntity sysResourceEntity =  new SysResourceEntity();
//            BeanUtils.copyProperties(sysResourceVO, sysResourceEntity);
            String resourceName = file.getOriginalFilename();
            sysResourceEntity.setResourceName(resourceName);
            sysResourceEntity.setResourceSize(getFileSize(file.getSize()));
            sysResourceEntity.setResourceUrl(url);
            LoginUser loginUser = LoginUserUtil.getLoginUser();
            sysResourceEntity.setCreateBy(Long.parseLong(loginUser.getId()+""));
            sysResourceEntity.setCreateTime(now());
            return sysResourceEntity;
        }
        return null;
    }


    private SysResourceEntity addFile(MultipartFile file,Long configId) {
        long fileSize = file.getSize();
        if (file == null || fileSize <= 0) {
            return null;
        }

        String uploadFilePath = file.getOriginalFilename();
        if (StringUtils.isNotBlank(uploadFilePath)) {
            String url = upload(file);
            SysResourceEntity sysResourceEntity =  new SysResourceEntity();
//            BeanUtils.copyProperties(sysResourceVO, sysResourceEntity);
            String resourceName = file.getOriginalFilename();
            sysResourceEntity.setResourceName(resourceName);
            sysResourceEntity.setResourceSize(getFileSize(file.getSize()));
            sysResourceEntity.setResourceUrl(url);
            LoginUser loginUser = LoginUserUtil.getLoginUser();
            sysResourceEntity.setCreateBy(Long.parseLong(loginUser.getId()+""));
            sysResourceEntity.setCreateTime(now());
            return sysResourceEntity;
        }
        return null;
    }

    /***
     * @Description: 根据typeId及TypeEnum获取附件资源
     * @Param: resourceType，typeIds
     * @return:
     * @Author: YPZ
     * @Date: 2022/11/16 17:37
     */
    @Override
    public Map<Long, List<SysResourceEntity>> getResourceMap(String resourceType, List<Long> typeIds) {
        Map<Long, List<SysResourceEntity>> resourceListMap = new HashMap<>();
        if (CollectionUtils.isEmpty(typeIds)){
            return resourceListMap;
        }
        LambdaQueryWrapper<SysResourceEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysResourceEntity::getResourceType,resourceType);
        wrapper.in(SysResourceEntity::getResourceTypeId,typeIds);
        wrapper.eq(SysResourceEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        List<SysResourceEntity> resourceList = this.list(wrapper);

        if (!CollectionUtils.isEmpty(resourceList)){
            resourceListMap = resourceList.stream().collect(Collectors.groupingBy(SysResourceEntity::getResourceTypeId));
        }
        return resourceListMap;

    }

    /***
     * @Description: 通过附件id更新附件
     * @Param: resourceType,typeId,resourceList
     * @return: boolean
     * @Author: YPZ
     * @Date: 2022/11/16 15:53
     */
    @Override
    public boolean updateResourceById(Long customerId,String resourceType, Long typeId, List<Long> resourceIdList){
        //删除已有资源
        this.updateDelete(resourceType,typeId);
        if (CollectionUtils.isEmpty(resourceIdList)){
            return true;
        }
        List<SysResourceEntity> resourceList = new ArrayList<>();
        for (Long resourceId : resourceIdList){

            SysResourceEntity resource = new SysResourceEntity();
            resource.setId(resourceId);
            resource.setCustomerId(customerId);
            resource.setResourceType(resourceType);
            resource.setResourceTypeId(typeId);
            resource.setIsDelete(CommonConstant.DEL_FLAG_0);
            resourceList.add(resource);
        }
        return this.updateBatchById(resourceList);
    }

    /**
     * 获取文件大小
     *
     * @author timo
     * @date 2018/9/3 14:03
     */
    public static String getFileSize(Long size) {
        BigDecimal fileSize = BigDecimal.valueOf(size);
        long B_SIZE = 1024;
        long KB_SIZE = B_SIZE;
        long MB_SIZE = KB_SIZE * B_SIZE;
        long GB_SIZE = MB_SIZE * B_SIZE;

        if (size / GB_SIZE > 0) {
            // GB
            return fileSize.divide(BigDecimal.valueOf(GB_SIZE), 2, RoundingMode.HALF_UP) + "GB";
        }
        if (size / MB_SIZE > 0) {
            // GB
            return fileSize.divide(BigDecimal.valueOf(MB_SIZE), 2, RoundingMode.HALF_UP) + "MB";
        }
        if (size / KB_SIZE > 0) {
            // GB
            return fileSize.divide(BigDecimal.valueOf(KB_SIZE), 2, RoundingMode.HALF_UP) + "KB";
        }
        if (size < B_SIZE) {
            return size + "B";
        }
        return 0 + "B";
    }

    /***
      * @Description: 上传文件
      * @Param:
      * @return:
      * @Author: YPZ
      * @Date: 2024/5/27 16:15
      */
    public String upload(MultipartFile multipartFile) {
        return OssBootUtil.upload(multipartFile, DateUtils.getUploadDir());
    }

    public String upload(MultipartFile multipartFile,String newBucketName,String newEndPoint) {
        return OssBootUtil.upload(multipartFile, DateUtils.getUploadDir(),newBucketName,newEndPoint);
    }
}
