package com.izouma.nineth.web;

import com.izouma.nineth.domain.PriceList;
import com.izouma.nineth.domain.Result;
import com.izouma.nineth.dto.PriceListVo;
import com.izouma.nineth.repo.CollectionRepo;
import com.izouma.nineth.service.PriceListService;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.PriceListRepo;
import com.izouma.nineth.utils.ObjUtils;
import com.izouma.nineth.utils.excel.ExcelUtils;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/priceList")
@AllArgsConstructor
public class PriceListController extends BaseController {
    private PriceListService priceListService;
    private PriceListRepo    priceListRepo;
    private CollectionRepo   collectionRepo;

    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/save")
    public PriceList save(@RequestBody PriceList record) {
        if (record.getId() != null) {
            PriceList orig = priceListRepo.findById(record.getId()).orElseThrow(new BusinessException("无记录"));
            ObjUtils.merge(orig, record);
            orig.setPrice(collectionRepo.lowestPrice(orig.getSearch()));
            return priceListRepo.save(orig);
        }
        record.setPrice(collectionRepo.lowestPrice(record.getSearch()));
        return priceListRepo.save(record);
    }


    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/all")
    public Page<PriceList> all(@RequestBody PageQuery pageQuery) {
        return priceListService.all(pageQuery);
    }

    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/get/{id}")
    public PriceList get(@PathVariable Long id) {
        return priceListRepo.findById(id).orElseThrow(new BusinessException("无记录"));
    }

    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/del/{id}")
    public void del(@PathVariable Long id) {
        priceListRepo.deleteById(id);
    }

    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/excel")
    @ResponseBody
    public void excel(HttpServletResponse response, PageQuery pageQuery) throws IOException {
        List<PriceList> data = all(pageQuery).getContent();
        ExcelUtils.export(response, data);
    }

    @GetMapping("/list")
    @Cacheable("priceList")
    public List<Map<String, String>> list() {
        return priceListRepo.findAll().stream().map(priceList -> {
            Map<String, String> map = new HashMap<>();
            map.put("name", priceList.getName());
            map.put("img", priceList.getPic());
            map.put("price", priceList.getPrice());
            map.put("lockNum", priceList.getLockNum());
            if (StringUtils.isNotEmpty(priceList.getColumnA())) {
                if (Double.parseDouble(priceList.getColumnA()) != 0) {
                    map.put("price", priceList.getColumnA());
                }
            }
            return map;
        }).collect(Collectors.toList());
    }
    @GetMapping("/priceListVo")
    @Cacheable("priceListVo")
    public Result<PriceListVo> priceList() {
        ArrayList<PriceListVo> list = new ArrayList<>();
        List<PriceList> priceLists = priceListRepo.findAll();
        for (PriceList priceList : priceLists) {
            PriceListVo priceListVo = new PriceListVo().builder()
                    .name(priceList.getName())
                    .img(priceList.getPic())
                    .price(priceList.getPrice())
                    .origin_price(collectionRepo.lowestOriginPrice(priceList.getSearch()))
                    .build();
            if (StringUtils.isNotEmpty(priceList.getColumnA())) {
                if (Double.parseDouble(priceList.getColumnA()) != 0) {
                    priceListVo.setPrice(priceList.getColumnA());
                }
            }
            list.add(priceListVo);
        }
         return Result.OK().success(list);
    }
}

