package com.yunniu.farming.app;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yunniu.farming.common.plugin.PageInfo;
import com.yunniu.farming.result.Result;
import com.yunniu.farming.webadmin.model.OrderMain;
import com.yunniu.farming.webadmin.service.impl.OrderMainServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@CrossOrigin(origins = "*", maxAge = 3600)
@RequestMapping("/app/order/")
public class OrderMainAppController {

    @Autowired
    private OrderMainServiceImpl orderService;


    /**
     * 多参数条件分页
     */
    @RequestMapping(value = "/findPageList", method = RequestMethod.POST)
    @ResponseBody
    public Result findPageList(@RequestBody OrderMain item) {

        if (item.getCustomerid() == null || item.getCustomerid().equals("")) return Result.success();

        //这里对返回对象用Map处理，map.pageinfo=>分页信息；map.items=>结果数据集；
        Map<String, Object> rmap = new HashMap<String, Object>();

        //传入当前页数，适配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);
        }
        item.setAppflag(1);
        // 2.1 执行主表 查询
        List<OrderMain> items = this.orderService.selectByParamPageList(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", items);
        return Result.success(rmap);
    }


    /**
     * FRICE TODO 根据 ”多参数“ 查找对象集合
     */
    @RequestMapping(value = "/findByParam", method = RequestMethod.POST)
    @ResponseBody
    public Result findByParam(@RequestBody OrderMain item) {

        List<OrderMain> docs = this.orderService.findByParam(item);

        return Result.success(docs);
    }


    /**
     * 更新订单
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public Result update(@RequestBody JSONObject json) {

        OrderMain orderM = JSONObject.toJavaObject(json, OrderMain.class);

        return this.orderService.update(orderM);

    }


    /**
     * 创建订单
     */
    @RequestMapping(value = "/addOrder", method = RequestMethod.POST)
    @ResponseBody
    public Result addOrder(@RequestBody JSONObject json) {

        OrderMain main = JSONObject.toJavaObject(json, OrderMain.class);

        main = this.orderService.addOrder(main);

        return Result.success(main);
    }


    /**
     * 创建积分订单
     */
    @RequestMapping(value = "/addIntOrder", method = RequestMethod.POST)
    @ResponseBody
    public Result addIntOrder(@RequestBody JSONObject json) {

        OrderMain main = JSONObject.toJavaObject(json, OrderMain.class);

        return this.orderService.addIntOrder(main);

    }


    /**
     * 根据”对象id“ 查找对象
     */
    @RequestMapping(value = "/{id}/findById", method = RequestMethod.GET)
    @ResponseBody
    public Result findById(@PathVariable Integer id) {

        OrderMain titem = this.orderService.findByid(id);

        return Result.success(titem);
    }


    /**
     * 根据”对象id“ 删除对象
     */
    @RequestMapping(value = "/{id}/deleteById", method = RequestMethod.POST)
    @ResponseBody
    public Result deleteById(@PathVariable Integer id) {

        return this.orderService.deleteByid(id);

    }


    /**
     * 根据参数，查询订单数量
     */
    @RequestMapping(value = "/findOrderNum", method = RequestMethod.POST)
    @ResponseBody
    public Result findOrderNum(@RequestBody JSONObject json) {

        OrderMain user = JSONObject.toJavaObject(json, OrderMain.class);

        int orderNum = this.orderService.findOrderNum(user);

        return Result.success(orderNum);

    }


    /**
     * 取消订单
     */
    @RequestMapping(value = "/cancelOrder", method = RequestMethod.POST)
    @ResponseBody
    public Result cancelOrder(@RequestBody JSONObject json) {
        //1. 将前台传过来的json对象转换成具有业务属性的 Java 对象
        OrderMain user = JSONObject.toJavaObject(json, OrderMain.class);
        return this.orderService.cancelOrder(user);
    }

    /**
     * 申请退款
     */
    @RequestMapping(value = "/refundOrder", method = RequestMethod.POST)
    @ResponseBody
    public Result refundOrder(@RequestBody JSONObject json) {
        //1. 将前台传过来的json对象转换成具有业务属性的 Java 对象
        OrderMain user = JSONObject.toJavaObject(json, OrderMain.class);
        JSONArray ids = json.getJSONArray("ids");
        return this.orderService.refundOrder(user,ids);
    }

    /**
     * 退货
     */
    @RequestMapping(value = "/saveCourierNumber", method = RequestMethod.POST)
    @ResponseBody
    public Result saveCourierNumber(@RequestBody JSONObject json) {
        //1. 将前台传过来的json对象转换成具有业务属性的 Java 对象
        OrderMain user = JSONObject.toJavaObject(json, OrderMain.class);
        return this.orderService.saveCourierNumber(user);
    }


    /**
     * 订单已完成
     */
    @RequestMapping(value = "/updateOkStatus", method = RequestMethod.POST)
    @ResponseBody
    public Result updateOkStatus(@RequestBody JSONObject json) {
        //1. 将前台传过来的json对象转换成具有业务属性的 Java 对象
        OrderMain user = JSONObject.toJavaObject(json, OrderMain.class);

        return this.orderService.updateOkStatus(user);

    }


    /**
     * @积分兑换 商品
     */
    @RequestMapping(value = "/integralPay", method = RequestMethod.POST)
    public Result integralPay(Integer userId, Integer orderId) {

        return this.orderService.integralPay(userId, orderId);

    }

    /**
     * 微信支付
     */
    @RequestMapping(value = "/appWxPay", method = RequestMethod.POST)
    public Result appWxPay(Integer userId, Integer orderId, HttpServletRequest request) {
        try {
            return orderService.appWxPay(userId, orderId, request);
        } catch (Exception e) {
            return Result.error();
        }
    }

    /**
     * 获取用户最后一次填写的地址信息
     */
    @RequestMapping(value = "/getLastOrderAddres", method = RequestMethod.GET)
    public Result getLastOrderAddres(Integer userId) {
        return orderService.getLastOrderAddres(userId);
    }

}
