package com.yunniu.farming.webadmin.controller;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.yunniu.farming.common.plugin.PageInfo;
import com.yunniu.farming.result.Result;
import com.yunniu.farming.util.COSUtil;
import com.yunniu.farming.util.FileUtil;
import com.yunniu.farming.webadmin.model.GroupArea;
import com.yunniu.farming.webadmin.model.GroupBuy;
import com.yunniu.farming.webadmin.model.Product;
import com.yunniu.farming.webadmin.service.GroupAreaService;
import com.yunniu.farming.webadmin.service.GroupBuyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zyf
 * @date 2023/5/12
 * @apiNote
 */
@Controller
@RequestMapping("/groupBuy")
public class GroupBuyController {

    @Autowired
    private GroupBuyService groupBuyService;
    @Autowired
    private GroupAreaService groupAreaService;

    @RequestMapping(value = "/list")
    public String list(Model model) {
        return "groupBuy/list";
    }

    @RequestMapping(value = "/productList")
    public String productList(Model model) {
        return "groupBuy/productList";
    }

    @RequestMapping(value = "/addOrEdit")
    public String addOrEdit(Model model, Long id) {
        model.addAttribute("id", id);
        if (id == null || id.equals("")) {
            model.addAttribute("obj", new GroupBuy());
        } else {
            GroupBuy groupBuy = groupBuyService.findById(id);
            model.addAttribute("obj", groupBuy);
        }
        List<GroupArea> areas = groupAreaService.findList();
        model.addAttribute("areaList", areas);
        return "groupBuy/addOrEdit";
    }

    /**
     * 分页查询
     * @return
     */
    @RequestMapping(value = "/findPageList", method = RequestMethod.POST)
    @ResponseBody
    public Result findPageList(@RequestBody GroupBuy item) {
        //这里对返回对象用Map处理，map.pageinfo=>分页信息；map.items=>结果数据集；
        Map<String,Object> rmap = new HashMap<String,Object>(2);

        //传入当前页数，适配PC端Layui分页
        if (item.getCurpage() != null || item.getPagesize() != null) {
            PageInfo pinfo = new PageInfo();

            if (item.getCurpage() != null) {
                pinfo.setCurPage(item.getCurpage());
            }
            if (item.getPagesize() != null) {
                pinfo.setPageSize(item.getPagesize());
            }
            item.setPageinfo(pinfo);
        }
        // 1.查询前 需要对分页对象 做处理，主要是 分页 开始记录数 limit arg0开始记录，arg1每页几条记录
        PageInfo pinfo = item.getPageinfo();
        if (pinfo == null) {
            pinfo = new PageInfo();
            item.setPageinfo(pinfo);
        } else {
            // 分页开始记录数
            int curRecord = (pinfo.getCurPage() - 1) * pinfo.getPageSize();
            pinfo.setCurRecord(curRecord);
            item.setPageinfo(pinfo);
        }

        List<GroupBuy> list = groupBuyService.findPageList(item);

        // 3.将查询结果的 分页数据封装后返回
        int totalRs = pinfo.getTotalRecords();        //总记录数
        int totalPs = 0;                            //总页数
        if (totalRs % pinfo.getPageSize() == 0) {        //总页数计算
            totalPs = totalRs / pinfo.getPageSize();
        } else {
            totalPs = 1 + totalRs / pinfo.getPageSize();
        }
        pinfo.setTotalPages(totalPs);

        // 4.将分页对象、结果集合 封装后返回前台
        rmap.put("pageinfo", pinfo);
        rmap.put("items", list);
        return Result.success(rmap);
    }

    @RequestMapping(value = "/{id}/deleteById",method = RequestMethod.GET)
    @ResponseBody
    public Result deleteById(@PathVariable Long id){

        return Result.success(groupBuyService.delById(id));
    }

    /**
     * 新增团购活动
     * @param item
     * @return
     */
    @RequestMapping(value = "/addOrUpdate", method = RequestMethod.POST)
    @ResponseBody
    public Result addOrUpdate(@RequestBody GroupBuy item) {
        if (StringUtils.isEmpty(item.getGroupBuyTitle())) {
            return Result.error("活动标题不能为空");
        }
        if (ObjectUtils.isEmpty(item.getStartTime()) || ObjectUtils.isEmpty(item.getEndTime())){
            return Result.error("活动有效期不能为空");
        }
        if (ObjectUtils.isEmpty(item.getGroupSize())){
            return Result.error("最低起送人数不能为空");
        }
        if (StringUtils.isEmpty(item.getGroupBuyPic())){
            return Result.error("图片不能为空");
        }
        if (CollectionUtils.isEmpty(item.getAreaIdList())){
            return Result.error("配送小区不能为空");
        }
        if (CollectionUtils.isEmpty(item.getProducts())){
            return Result.error("商品不能为空");
        }
        return this.groupBuyService.addOrEdit(item);
    }

    /**
     * 分页查询商品
     * @return
     */
    @RequestMapping(value = "/getProductList", method = RequestMethod.POST)
    @ResponseBody
    public Result productList(@RequestBody Product item) {
        //这里对返回对象用Map处理，map.pageinfo=>分页信息；map.items=>结果数据集；
        Map<String,Object> rmap = new HashMap<String,Object>(2);

        //传入当前页数，适配PC端Layui分页
        if (item.getCurpage() != null || item.getPagesize() != null) {
            PageInfo pinfo = new PageInfo();

            if (item.getCurpage() != null) {
                pinfo.setCurPage(item.getCurpage());
            }
            if (item.getPagesize() != null) {
                pinfo.setPageSize(item.getPagesize());
            }
            item.setPageinfo(pinfo);
        }
        // 1.查询前 需要对分页对象 做处理，主要是 分页 开始记录数 limit arg0开始记录，arg1每页几条记录
        PageInfo pinfo = item.getPageinfo();
        if (pinfo == null) {
            pinfo = new PageInfo();
            item.setPageinfo(pinfo);
        } else {
            // 分页开始记录数
            int curRecord = (pinfo.getCurPage() - 1) * pinfo.getPageSize();
            pinfo.setCurRecord(curRecord);
            item.setPageinfo(pinfo);
        }

        List<Product> list = groupBuyService.productList(item);

        // 3.将查询结果的 分页数据封装后返回
        int totalRs = pinfo.getTotalRecords();        //总记录数
        int totalPs = 0;                            //总页数
        if (totalRs % pinfo.getPageSize() == 0) {        //总页数计算
            totalPs = totalRs / pinfo.getPageSize();
        } else {
            totalPs = 1 + totalRs / pinfo.getPageSize();
        }
        pinfo.setTotalPages(totalPs);

        // 4.将分页对象、结果集合 封装后返回前台
        rmap.put("pageinfo", pinfo);
        rmap.put("items", list);
        return Result.success(rmap);
    }

    @RequestMapping(value = "uploads")
    @ResponseBody
    public Map<String, Object> uploads(@RequestParam(value = "upfile", required = false) MultipartFile upfile)
            throws Exception {
        Map<String, Object> rs = new HashMap<String, Object>();
        try {
            if (!upfile.isEmpty()) {
                String path = FileUtil.saveFile(upfile, "group");
                String url = COSUtil.uploadFileByPath(path);
                rs.put("state", "SUCCESS");// UEDITOR的规则:不为SUCCESS则显示state的内容
                rs.put("url", url); // 能访问到你如今图片的路径
            }
        } catch (Exception e) {
            e.printStackTrace();
            rs.put("state", e.getMessage());
            rs.put("url", "");
            rs.put("title", "");
            rs.put("original", "");
        }
        return rs;
    }
}
