package com.kmall.admin.controller;

import com.kmall.admin.entity.OrderEntity;
import com.kmall.admin.entity.OrderExceptionRecordEntity;
import com.kmall.admin.entity.OrderRefundEntity;
import com.kmall.admin.service.*;
import com.kmall.admin.entity.OrderProcessRecordEntity;
import com.kmall.admin.service.OrderExceptionRecordService;
import com.kmall.admin.service.OrderProcessRecordService;
import com.kmall.admin.service.OrderService;
import com.kmall.api.contants.Dict;
import com.kmall.common.utils.print.ticket.item.Ticket;
import com.kmall.common.utils.PageUtils;
import com.kmall.common.utils.Query;
import com.kmall.common.utils.R;
import com.kmall.common.utils.wechat.WechatRefundApiResult;
import com.kmall.common.utils.wechat.WechatUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * @author Scott
 * @email
 * @date 2017-08-13 10:41:09
 */
@RestController
@RequestMapping("order")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderProcessRecordService orderProcessRecordService;
    @Autowired
    private OrderRefundService orderRefundService;
    @Autowired
    private OrderExceptionRecordService orderExceptionRecordService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("order:list")
    public R list(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);

        List<OrderEntity> orderList = orderService.queryList(query);
        int total = orderService.queryTotal(query);

        PageUtils pageUtil = new PageUtils(orderList, total, query.getLimit(), query.getPage());

        return R.ok().put("page", pageUtil);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("order:info")
    public R info(@PathVariable("id") Long id) {
        OrderEntity order = orderService.queryObject(id);
        return R.ok().put("order", order);
    }

    /**
     * 信息
     */
    @RequestMapping("/infos/{id}")
    @RequiresPermissions("order:infos")
    public R infos(@PathVariable("id") Long id) {
        OrderEntity order = orderService.queryInfos(id);
        return R.ok().put("order", order);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("order:save")
    public R save(@RequestBody OrderEntity order) {
        orderService.save(order);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("order:update")
    public R update(@RequestBody OrderEntity order) {
        orderService.update(order);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("order:delete")
    public R delete(@RequestBody Long[] ids) {
        orderService.deleteBatch(ids);

        return R.ok();
    }

    /**
     * 查看所有列表
     */
    @RequestMapping("/queryAll")
    public R queryAll(@RequestParam Map<String, Object> params) {

        List<OrderEntity> list = orderService.queryList(params);

        return R.ok().put("list", list);
    }

    /**
     * 总计
     */
    @RequestMapping("/queryTotal")
    public R queryTotal(@RequestParam Map<String, Object> params) {
        int sum = orderService.queryTotal(params);

        return R.ok().put("sum", sum);
    }

    /**
     * 确定收货
     *
     * @param id
     * @return
     */
    @RequestMapping("/confirm")
    @RequiresPermissions("order:confirm")
    public R confirm(@RequestBody Long id) {
        orderService.confirm(id);

        return R.ok();
    }

    /**
     * 发货
     *
     * @param order
     * @return
     */
    @RequestMapping("/sendGoods")
    @RequiresPermissions("order:sendGoods")
    public R sendGoods(@RequestBody OrderEntity order) {
        orderService.sendGoods(order);

        return R.ok();
    }

    /**
     * 跟踪快递轨迹
     * @param id
     * @return
     */
    @RequestMapping("/getLogistics/{id}")
    @RequiresPermissions("order:getLogistics")
    public R getLogistics(@PathVariable("id") Long id) {
        Map result = orderService.getLogistics(id);
        return R.ok().put("result", result);
    }

    /**
     * 获取订单清关信息
     * @param orderSn
     * @return
     */
    @RequestMapping("/getProcess/{orderSn}")
    @RequiresPermissions("order:getProcess")
    public R getProcess(@PathVariable("orderSn") String orderSn) {
        OrderProcessRecordEntity orderProcessRecordEntity = orderProcessRecordService.queryObjectByOrderSn(orderSn);
        return R.ok().put("orderProcessRecordEntity", orderProcessRecordEntity);
    }

    /**
     * 打印小票
     *
     * @param id
     * @return
     */
    @RequestMapping("/printMsg")
    public R printMsg(@RequestBody Long id) {
        Ticket ticket = orderService.printMsg(id);
        return R.ok().put("ticket", ticket);
    }

    /**
     * 订单取消请求
     */
    @RequiresPermissions(value = {"order:refund"})
    @RequestMapping(value = "cancel", method = RequestMethod.POST)
    public Object cancel(Long orderId) {
        OrderEntity orderInfo = orderService.queryObject(orderId);
        if (null == orderInfo) {
            return R.error("订单不存在");
        }
        if (orderInfo.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_401.getItem())
                || orderInfo.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_402.getItem())) {
            return R.error("订单已退款");
        }
        Double totalActualPrice = orderService.getTotalActualPrice(orderInfo.getMerchOrderSn());
        if(totalActualPrice == null){
            totalActualPrice = 0d;
        }

        if (orderInfo.getOrderStatus() != 0) {
            // todo 退款
//          WechatRefundApiResult result = WechatUtil.wxRefund(orderInfo.getOrderSn().toString(),
//                orderInfo.getActualPrice().doubleValue(), refundMoney.doubleValue());
            WechatRefundApiResult result = WechatUtil.wxRefund(orderInfo.getMerchOrderSn().toString(),
                    totalActualPrice, orderInfo.getActualPrice().doubleValue());
            if (result.getResult_code().equals("SUCCESS")) {
                orderService.cancelOrder(orderInfo,result);
            }else{
                OrderRefundEntity mallOrderRefund = orderRefundService.queryObjectByOrderId(orderInfo.getId());
                OrderRefundEntity orderRefund = new OrderRefundEntity();
                orderRefund.setRefundType(Integer.parseInt(Dict.RefundType.item_1.getItem()));
                orderRefund.setRefundMoney(BigDecimal.valueOf(orderInfo.getActualPrice().doubleValue()));
                orderRefund.setRefundStatus(Integer.parseInt(Dict.RefundStatus.item_4.getItem()));
                orderRefund.setModTime(new Date());
                if(mallOrderRefund !=null){
                    orderRefund.setId(mallOrderRefund.getId());
                    orderRefundService.update(orderRefund);//退款记录
                }

                OrderExceptionRecordEntity mallOrderExceptionRecord = new OrderExceptionRecordEntity();
                mallOrderExceptionRecord.setUserId(Integer.parseInt(orderInfo.getUserId()+""));
                mallOrderExceptionRecord.setOrderSn(orderInfo.getOrderSn());
                mallOrderExceptionRecord.setExceptionStatus(Dict.exceptionStatus.item_03.getItem());
                mallOrderExceptionRecord.setExceptionContent("退款失败"+result.getErr_code_des());
                mallOrderExceptionRecord.setCreateTime(new Date());
                orderExceptionRecordService.save(mallOrderExceptionRecord);

                return R.error(result.getErr_code_des());
            }
        }

        return R.ok();
    }

    /**
     * 订单退款请求
     */
    @RequiresPermissions(value = {"order:refund"})
    @RequestMapping(value = "refund", method = RequestMethod.POST)
    public Object refund(Long orderId, BigDecimal refundMoney) {
        OrderEntity orderInfo = orderService.queryObject(orderId);

        if (null == refundMoney) {
            return R.error("请输入退款金额");
        }

        if (null == orderInfo) {
            return R.error("订单已取消");
        }

        if (refundMoney.compareTo(orderInfo.getActualPrice()) > 0) {
            return R.error("退款金额不能大于订单金额");
        }

        if (orderInfo.getOrderStatus() == 401 || orderInfo.getOrderStatus() == 402) {
            return R.error("订单已退款");
        }

        if (orderInfo.getPayStatus() != 2) {
            return R.error("订单未付款，不能退款");
        }

//        WechatRefundApiResult result = WechatUtil.wxRefund(orderInfo.getOrderSn().toString(),
//                orderInfo.getActualPrice().doubleValue(), refundMoney.doubleValue());
        WechatRefundApiResult result = WechatUtil.wxRefund(orderInfo.getOrderSn().toString(),
                orderInfo.getActualPrice().doubleValue(),orderInfo.getActualPrice().doubleValue());
        if (result.getResult_code().equals("SUCCESS")) {
            orderService.refund(orderInfo, refundMoney);
            return R.ok();
        } else {
            return R.error(result.getErr_code_des());
        }
    }

    /**
     * 获取首页展示信息--会员购买率相关
     * @param params
     * @return
     */
    @RequestMapping("/getUserOrderInfo")
    public R getUserOrderInfo(@RequestParam Map<String, Object> params) {
        int result = orderService.getUserOrderInfo(params);

        return R.ok().put("result", result);
    }
}
