package com.ff.weijinxiao.controller;


import com.ff.weijinxiao.domain.AccountBook;
import com.ff.weijinxiao.domain.CUser;
import com.ff.weijinxiao.domain.OrderGoods;
import com.ff.weijinxiao.domain.UserInfo;
import com.ff.weijinxiao.jwt.JwtHelper;
import com.ff.weijinxiao.service.AccountBookService;
import com.ff.weijinxiao.service.CUserService;
import com.ff.weijinxiao.service.OrderGoodsService;
import com.ff.weijinxiao.service.UserInfoService;
import com.ff.weijinxiao.util.JsonTool;
import com.ff.weijinxiao.util.RandomUtil;
import com.ff.weijinxiao.util.ResultTool;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

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

/**
 * 订单接口
 */
@RestController
@RequestMapping("api/ordergoods")
@Api(value = "订单controller", tags = {"订单接口"})
public class OrderGoodsController {

    @Resource
    private OrderGoodsService orderGoodsService;

    @Resource
    private AccountBookService accountBookService;

    @Resource
    private UserInfoService userInfoService;

    @Resource
    private CUserService cUserService;

    public UserInfo getUserInfoByToken(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)) {
            return null;
        }
        String openId = JwtHelper.parseToken(token);
        if (StringUtils.isBlank(openId)) {
            return null;
        }

        CUser cUser = cUserService.findByOpenId(openId);
        if (null == cUser) {
            return null;
        }
        return cUser.getUserInfo();
    }

    @PostMapping("/update")
    @ApiOperation(value = "更新订单信息", notes = "更新订单信息")
    public Map<String, Object> updateOrderGoods(@RequestBody OrderGoods orderGoods, HttpServletRequest request) {
        try {
            orderGoodsService.saveOrderGoods(orderGoods);
            return ResultTool.genSuccessResult("修改成功");
        } catch (Exception e) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_2, "修改失败:" + e.getMessage());
        }
    }

    @PostMapping("/create")
    @ApiOperation(value = "创建订单信息", notes = "创建订单信息")
    public Map<String, Object> saveOrderGoods(@RequestBody OrderGoods orderGoods, HttpServletRequest request) {
        try {
            orderGoodsService.saveOrderGoods(orderGoods);
            return ResultTool.genSuccessResult("创建成功");
        } catch (Exception e) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_2, "创建失败:" + e.getMessage());
        }
    }


    @PostMapping("/delete")
    @ApiOperation(value = "删除订单信息", notes = "删除订单信息")
    public Map<String, Object> deleteOrderGoods(@ApiParam(required = true, value = "订单id") @RequestBody String jsonId) {
        Integer id = JsonTool.parseJsonIdStr(jsonId);
        if (id < 0) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "id参数错误");
        }
        OrderGoods orderGoods = orderGoodsService.findById(id);
        if (null == orderGoods) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "订单不存在");
        }
        orderGoods.setIsDelete(1);
        orderGoodsService.saveOrderGoods(orderGoods);
        return ResultTool.genSuccessResult("删除成功");
    }

    @GetMapping("/findbyid")
    @ApiOperation(value = "根据id查询订单信息", notes = "根据id查询订单信息")
    public Map<String, Object> findById(@ApiParam(required = true, value = "订单id") @RequestParam String id,
                                        HttpServletRequest request) {

        Map<String, Object> result = new HashMap<>();
        try {
            OrderGoods orderGoods = orderGoodsService.findById(Integer.valueOf(id));
            if (null != orderGoods) {
                result.put("data", orderGoods);
                result.put("message", "查询成功");
                result.put("code", ResultTool.SuccessCode);
            } else {
                result.put("message", "查询失败，没有结果");
                result.put("code", ResultTool.ErrorCode_1);
            }

        } catch (Exception e) {
            e.printStackTrace();
            result.put("message", "查询失败" + e.getMessage());
            result.put("code", ResultTool.ErrorCode_2);
        }

        return result;
    }


    @GetMapping("/list")
    @ApiOperation(value = "查询订单列表", notes = "查询订单列表")
    public Map<String, Object> findList(@ApiParam(required = false, value = "订单名字") @RequestParam(required = false) String phone,
                                        HttpServletRequest request) {

        Map<String, Object> result = new HashMap<>();
        Map<String, Object> param = new HashMap<>();
        param.put("GT_id", 0);
        param.put("EQ_isDelete", 0);
        if (null != phone && phone.length() > 0) {
            param.put("LIKE_phone", phone);
        }
        List<OrderGoods> list = orderGoodsService.findList(param);
        if (null != list && list.size() > 0) {
            result.put("data", list);
            result.put("total", list.size());
            result.put("message", "查询成功");
            result.put("code", 10000);
        } else {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "没有查询到数据");
        }

        return result;
    }

    @GetMapping("/listpage")
    @ApiOperation(value = "查询订单分页列表", notes = "查询订单分页列表")
    public Map<String, Object> findListPage(@ApiParam(required = false, value = "订单名字") @RequestParam(required = false) String phone,
                                            @ApiParam(required = false, value = "页码 1开始") @RequestParam(required = false) Integer pageNo,
                                            @ApiParam(required = false, value = "每页显示条数 默认10") @RequestParam(required = false) Integer pageSize) {

        Map<String, Object> result = new HashMap<>();
        Map<String, Object> param = new HashMap<>();
        if (null == pageNo) {
            pageNo = 1;
        } else if (pageNo < 1) {
            pageNo = 1;
        }
        if (null == pageSize) {
            pageSize = 10;
        }
        param.put("GT_id", 0);
        param.put("EQ_isDelete", 0);
        if (null != phone && phone.length() > 0) {
            param.put("LIKE_phone", phone);
        }
        Page<OrderGoods> list = orderGoodsService.findPage(pageNo, pageSize, param);
        if (null != list && list.getTotalElements() > 0) {
            List<OrderGoods> data = list.getContent();
            for (OrderGoods orderGoods : data) {
                UserInfo userInfo = userInfoService.findByUid(orderGoods.getUid());
                if (null != userInfo) {
                    orderGoods.setUserName(userInfo.getWechatName());
                }
            }
            result.put("data", list);
            result.put("message", "分页查询成功");
            result.put("code", 10000);
        } else {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "没有查询到数据");
        }

        return result;
    }

    @PostMapping("/wxapi/update")
    @ApiOperation(value = "更新订单信息", notes = "更新订单信息")
    public Map<String, Object> wxupdateOrderGoods(@RequestBody OrderGoods orderGoods, HttpServletRequest request) {
        try {
            orderGoodsService.saveOrderGoods(orderGoods);
            return ResultTool.genSuccessResult("修改成功");
        } catch (Exception e) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_2, "修改失败:" + e.getMessage());
        }
    }

    //调用order/create创建，此接口已不再使用
    @PostMapping("/wxapi/create")
    @ApiOperation(value = "创建订单信息", notes = "创建订单信息")
    public Map<String, Object> wxsaveOrderGoods(@RequestBody OrderGoods orderGoods, HttpServletRequest request) {
        try {
            UserInfo userInfo = getUserInfoByToken(request);
            if (null == userInfo) {
                return ResultTool.genFailResult(ResultTool.ErrorCode_2, "创建失败:用户获取失败");
            }
            //Order order = orderGoods.getOrder();
            //order.setUid(userInfo.getUid());
            //order.setOnlyID(RandomUtil.genOnlyId());
            //order = orderService.saveOrder(order);
            orderGoods.setOnlyID(RandomUtil.genOnlyId());
            AccountBook accountBook = accountBookService.getDefaultAccountBook(userInfo);
            orderGoods.setOnlyID(RandomUtil.genOnlyId());
            orderGoods.setUid(userInfo.getUid());
            //orderGoods.setOrder(order);
            orderGoodsService.saveOrderGoods(orderGoods);
            return ResultTool.genSuccessResult("创建成功");
        } catch (Exception e) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_2, "创建失败:" + e.getMessage());
        }
    }

    @GetMapping("/wxapi/listpage")
    @ApiOperation(value = "查询订单分页列表", notes = "查询订单分页列表")
    public Map<String, Object> wxfindListPage(@ApiParam(required = false, value = "订单客户电话") @RequestParam(required = false) String phone,
                                              @ApiParam(required = false, value = "页码 1开始") @RequestParam(required = false) Integer pageNo,
                                              @ApiParam(required = false, value = "每页显示条数 默认10") @RequestParam(required = false) Integer pageSize,
                                              HttpServletRequest request) {

        Map<String, Object> result = new HashMap<>();
        Map<String, Object> param = new HashMap<>();
        if (null == pageNo) {
            pageNo = 1;
        } else if (pageNo < 1) {
            pageNo = 1;
        }
        if (null == pageSize) {
            pageSize = 10;
        }
        param.put("GT_id", 0);
        param.put("EQ_isDelete", 0);
        if (null != phone && phone.length() > 0) {
            param.put("LIKE_order.customer.phone", phone);
        }
        UserInfo userInfo = getUserInfoByToken(request);
        if (null == userInfo) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "获取失败，未注册有效账号");
        }
        //param.put("EQ_uid", userInfo.getUid());
        param.put("EQ_accountBook.id", userInfo.getAccountBookId());
        Page<OrderGoods> list = orderGoodsService.findPage(pageNo, pageSize, param);
        if (null != list && list.getTotalElements() > 0) {
            List<OrderGoods> data = list.getContent();
            for (OrderGoods orderGoods : data) {
                UserInfo user = userInfoService.findByUid(orderGoods.getUid());
                if (null != user) {
                    orderGoods.setUserName(user.getWechatName());
                }
            }
            result.put("data", list);
            result.put("message", "分页查询成功");
            result.put("code", 10000);
        } else {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "没有查询到数据");
        }

        return result;
    }


}
