package com.ruoyi.web.controller.common;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.RestResponse;
import com.ruoyi.common.core.redis.RedisService;
import com.ruoyi.mall.domain.dto.AddressDTO;
import com.ruoyi.mall.mapper.AddressMapper;
import com.ruoyi.system.service.FileService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.mall.domain.Address;

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

/**
 * 通用请求处理
 *
 * @author ruoyi
 */
@Slf4j
@RestController
@Tag(name = "文件上传")
@RequiredArgsConstructor
@RequestMapping("/com")
public class CommonController
{



    private final FileService fileService;


    private final RedisService redisService;


    private final AddressMapper addressMapper;

    @Operation(summary = "上传课程相关图片", description = "上传图片,上传后返回原图和缩略图的url")
    @PostMapping("/courseImage/upload")
    public RestResponse uploadCourseImage(@RequestParam("file") MultipartFile file) {
        return new RestResponse().setData(fileService.uploadCourseImage(file));
    }

    @Operation(summary = "上传商城相关图片", description = "上传图片,上传后返回原图和缩略图的url")
    @PostMapping("/productImage/upload")
    public RestResponse uploadProductImage(@RequestParam("file") MultipartFile file) {
        return new RestResponse().setData(fileService.uploadProductImage(file)).setSuccess(true);
    }

    @Operation(summary = "上传文件", description = "上传文件，上传后返回文件url")
    @PostMapping("/file/upload")
    public RestResponse uploadFile(@RequestParam("file") MultipartFile file) {
        return new RestResponse().setSuccess(true).setCode(200).setData(fileService.uploadFile(file));
    }

    @GetMapping("/common/area")
    public AjaxResult getAddressList() {
        String addresses = redisService.getAddressList();
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(addresses)) {
            List<AddressDTO> addressDTOList = JSON.parseArray(addresses, AddressDTO.class);
            if(addressDTOList.size()>0){
                return AjaxResult.success(addressDTOList);
            }
        }
        QueryWrapper<Address> addressQueryWrapper = new QueryWrapper<>();
        addressQueryWrapper.in("level", Arrays.asList(0,1,2));
        List<Address> addressList = addressMapper.selectList(addressQueryWrapper);
        Map<Long, List<Address>> cityMap = addressList.stream().filter(it -> it.getLevel() == 1).collect(Collectors.groupingBy(it -> it.getParentCode()));
        Map<Long, List<Address>> districtMap = addressList.stream().filter(it -> it.getLevel() == 2).collect(Collectors.groupingBy(it -> it.getParentCode()));
        List<AddressDTO> result = new ArrayList<>();
        addressList.stream().filter(it -> it.getLevel() == 0).forEach(it -> {
            AddressDTO dto = new AddressDTO();
            dto.setId(it.getCode());
            dto.setLevel("province");
            dto.setName(it.getName());
            dto.setPid(0L);
            //获取城市列表
            List<AddressDTO> child = new ArrayList<>();
            if (cityMap.containsKey(it.getCode())) {
                cityMap.get(it.getCode()).forEach(city -> {
                    AddressDTO cityDto = new AddressDTO();
                    cityDto.setId(city.getCode());
                    cityDto.setLevel("city");
                    cityDto.setName(city.getName());
                    cityDto.setPid(city.getParentCode());
                    cityDto.setChildren(districtMap.containsKey(city.getCode()) ?
                            districtMap.get(city.getCode()).stream().map(district -> {
                                AddressDTO districtDto = new AddressDTO();
                                districtDto.setId(district.getCode());
                                districtDto.setLevel("district");
                                districtDto.setName(district.getName());
                                districtDto.setPid(district.getParentCode());
                                return districtDto;
                            }).collect(Collectors.toList()) : Collections.EMPTY_LIST);
                    child.add(cityDto);
                });
            }
            dto.setChildren(child);
            result.add(dto);
        });
        redisService.setAddressList(JSON.toJSONString(result));
        return AjaxResult.success(result);
    }

}
