package com.kmall.admin.controller;

import com.kmall.admin.dto.OrderExpressDto;
import com.kmall.admin.entity.*;
import com.kmall.common.constant.JxlsXmlTemplateName;
import com.kmall.common.utils.excel.ExcelUtil;
import com.kmall.manager.manager.wechat.WechatUtil;
import com.kmall.manager.manager.wechat.WechatGlobalUtil;
import com.kmall.manager.manager.wechat.wxglobal.dto.WechatGlobalRefundApiResult;
import com.kmall.admin.service.*;
import com.kmall.admin.service.OrderExceptionRecordService;
import com.kmall.admin.service.OrderProcessRecordService;
import com.kmall.admin.service.OrderService;
import com.kmall.admin.utils.ParamUtils;
import com.kmall.admin.utils.ShiroUtils;
import com.kmall.common.constant.Dict;
import com.kmall.admin.fromcomm.entity.SysUserEntity;
import com.kmall.common.utils.*;
import com.kmall.common.utils.excel.ExcelExport;
import com.kmall.manager.manager.pingan.PinganUtil;
import com.kmall.manager.manager.pingan.dto.PinganResponseDto;
import com.kmall.common.utils.print.ticket.item.Ticket;
import com.kmall.common.utils.wechat.WechatMicropayApiResult;
import com.kmall.common.utils.wechat.WechatRefundApiResult;
import com.kmall.common.utils.wechat.WechatReverseApiResult;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @author Scott
 * @email
 * @date 2017-08-13 10:41:09
 */
@RestController
@RequestMapping("order")
public class OrderController {
    private Log logger = LogFactory.getLog(OrderController.class);
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderProcessRecordService orderProcessRecordService;
    @Autowired
    private OrderRefundService orderRefundService;
    @Autowired
    private OrderExceptionRecordService orderExceptionRecordService;
    @Autowired
    private StoreService storeService;
    @Autowired
    private OrderWXPayRecordService orderWXPayRecordService;
    @Autowired
    private PinganResponseService pinganResponseService;
    @Autowired
    private ExcelUtil excelUtil;
    @Autowired
    private ShippingService shippingService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("order:list")
    public R list(@RequestParam Map<String, Object> params) {
        ParamUtils.setQueryPowerByRoleType(params, "storeId", "merchSn", "thirdPartyMerchCode");
        params = ParamUtils.setTimeMap(params);
        //查询列表数据
        Query query = new Query(params);
        query.put("isOnfiilineOrder", Dict.isOnfflineOrder.item_0.getItem());
        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) {
        ParamUtils.setQueryPowerByRoleType(params, "storeId", "merchSn", "thirdPartyMerchCode");
        List<OrderEntity> list = orderService.queryList(params);

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

    /**
     * 总计
     */
    @RequestMapping("/queryTotal")
    public R queryTotal(@RequestParam Map<String, Object> params) {
        ParamUtils.setQueryPowerByRoleType(params, "storeId", "merchSn", "thirdPartyMerchCode");
        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);
        if (orderProcessRecordEntity != null) {
            if (orderProcessRecordEntity.getShipmentStartTime() != null) {
                orderProcessRecordEntity.setShipmentStartTimeStr(
                        DateUtils.format(orderProcessRecordEntity.getShipmentStartTime(), DateUtils.DATE_TIME_PATTERN));
            }
            if (orderProcessRecordEntity.getShipmentSuccTime() != null) {
                orderProcessRecordEntity.setShipmentSuccTimeStr(
                        DateUtils.format(orderProcessRecordEntity.getShipmentSuccTime(), DateUtils.DATE_TIME_PATTERN));
            }
            if (orderProcessRecordEntity.getCustomsStartTime() != null) {
                orderProcessRecordEntity.setCustomsStartTimeStr(
                        DateUtils.format(orderProcessRecordEntity.getCustomsStartTime(), DateUtils.DATE_TIME_PATTERN));
            }
            if (orderProcessRecordEntity.getCustomsSuccTime() != null) {
                orderProcessRecordEntity.setCustomsSuccTimeStr(
                        DateUtils.format(orderProcessRecordEntity.getCustomsSuccTime(), DateUtils.DATE_TIME_PATTERN));
            }
            if (orderProcessRecordEntity.getWaybillStartTime() != null) {
                orderProcessRecordEntity.setWaybillStartTimeStr(
                        DateUtils.format(orderProcessRecordEntity.getWaybillStartTime(), DateUtils.DATE_TIME_PATTERN));
            }
            if (orderProcessRecordEntity.getWaybillSuccTime() != null) {
                orderProcessRecordEntity.setWaybillSuccTimeStr(
                        DateUtils.format(orderProcessRecordEntity.getWaybillSuccTime(), DateUtils.DATE_TIME_PATTERN));
            }
            if (orderProcessRecordEntity.getEleOrderStartTime() != null) {
                orderProcessRecordEntity.setEleOrderStartTimeStr(
                        DateUtils.format(orderProcessRecordEntity.getEleOrderStartTime(), DateUtils.DATE_TIME_PATTERN));
            }
            if (orderProcessRecordEntity.getEleOrderSuccTime() != null) {
                orderProcessRecordEntity.setEleOrderSuccTimeStr(
                        DateUtils.format(orderProcessRecordEntity.getEleOrderSuccTime(), DateUtils.DATE_TIME_PATTERN));
            }
            if (orderProcessRecordEntity.getAddOrderStartTime() != null) {
                orderProcessRecordEntity.setAddOrderStartTimeStr(
                        DateUtils.format(orderProcessRecordEntity.getAddOrderStartTime(), DateUtils.DATE_TIME_PATTERN));
            }
            if (orderProcessRecordEntity.getAddOrderSuccTime() != null) {
                orderProcessRecordEntity.setAddOrderSuccTimeStr(
                        DateUtils.format(orderProcessRecordEntity.getAddOrderSuccTime(), DateUtils.DATE_TIME_PATTERN));
            }
            if (orderProcessRecordEntity.getPaySuccTime() != null) {
                orderProcessRecordEntity.setPaySuccTimeStr(
                        DateUtils.format(orderProcessRecordEntity.getPaySuccTime(), DateUtils.DATE_TIME_PATTERN));
            }
            if (orderProcessRecordEntity.getPayStartTime() != null) {
                orderProcessRecordEntity.setPayStartTimeStr(
                        DateUtils.format(orderProcessRecordEntity.getPayStartTime(), DateUtils.DATE_TIME_PATTERN));
            }
            if (orderProcessRecordEntity.getPaymentStartTime() != null) {
                orderProcessRecordEntity.setPaymentStartTimeStr(
                        DateUtils.format(orderProcessRecordEntity.getPaymentStartTime(), DateUtils.DATE_TIME_PATTERN));
            }
            if (orderProcessRecordEntity.getPaymentSuccTime() != null) {
                orderProcessRecordEntity.setPaymentSuccTimeStr(
                        DateUtils.format(orderProcessRecordEntity.getPaymentSuccTime(), DateUtils.DATE_TIME_PATTERN));
            }
        }
        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() != 0) {
            return R.error("订单状态不支持取消");
        }

        orderService.cancelOrder(orderInfo);
        return R.ok();
    }

    /**
     * 订单退款请求
     */
    @RequiresPermissions(value = {"order:refund"})
    @RequestMapping(value = "refund", method = RequestMethod.POST)
    public Object refund(Long orderId, String refundId, BigDecimal refundMoney) {
        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;
        }
        OrderProcessRecordEntity processRecordEntity = orderProcessRecordService.queryObjectByOrderSn(orderInfo.getOrderSn());
        if(org.apache.commons.lang.StringUtils.isNotEmpty(processRecordEntity.getIsCustomsSend())) {
            if (processRecordEntity.getIsCustomsSend().equalsIgnoreCase("2")) {
                return R.error("订单正在清关中，不能退款");
            }
            if (processRecordEntity.getIsCustomsSend().equalsIgnoreCase("1")) {
                return R.error("订单已清关完成，不能退款");
            }
        }
        String refundResult = "";
        if (orderInfo.getOrderStatus() != Integer.parseInt(Dict.orderStatus.item_0.getItem())) {
            if (orderInfo.getPayFlag().equalsIgnoreCase(Dict.payFlag.item_wxglobalpay.getItem())) {
                refundResult = wxGlobalRefund(orderInfo, totalActualPrice);
                if (StringUtils.isNotBlank(refundResult)) {
                    return R.error(refundResult);
                }
            } else if (orderInfo.getPayFlag().equalsIgnoreCase(Dict.payFlag.item_pingan.getItem())) {
                refundResult = pinganRefund(orderInfo, refundId);
                if (StringUtils.isNotBlank(refundResult)) {
                    return R.error(refundResult);
                }
            } else{
                refundResult = wxRefund(orderInfo,totalActualPrice);
                if(StringUtils.isNotBlank(refundResult)){
                    return R.error(refundResult);
                }
            }
        }
        return R.ok("退款成功");
    }

    /**
     * 平安申请退款
     * @param orderInfo
     * @return
     */
    private String pinganRefund(OrderEntity orderInfo, String refundId){
        Integer refundAmount =  orderInfo.getActualPrice().multiply(new BigDecimal(100)).intValue();
        PinganResponseDto responseDto = PinganUtil.pinganPayRefund(orderInfo.getMerchOrderSn(), refundId, refundAmount, null);

        if (!Objects.isNull(responseDto)) {
            responseDto.setOutNo(orderInfo.getMerchOrderSn());
            responseDto.setCreateTime(new Date());
            pinganResponseService.save(responseDto);

            if ("0".equals(responseDto.getErrcode())) {
                JSONObject tradeResult = JSONObject.fromObject(responseDto.getDatajson());
                if (Dict.pinganRefundStatus.item_1.getItem().equals(tradeResult.getString("status"))) {
                    orderService.pinganRefund(orderInfo, tradeResult, refundId);
                } 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()));
                    SysUserEntity user = ShiroUtils.getUserEntity();
                    orderRefund.setModerSn(user.getUsername());
                    orderRefund.setModTime(new Date());
                    orderRefund.setOutRefundNo(tradeResult.getString("ord_no"));
                    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("退款失败");
                    mallOrderExceptionRecord.setCreateTime(new Date());
                    orderExceptionRecordService.save(mallOrderExceptionRecord);
                    return "发起平安支付退款失败！";
                }
            } else {
                return responseDto.getMsg();
            }
        }
        return "";
    }

    /**
     * 微信申请退款
     * @param orderInfo
     * @param totalActualPrice
     * @return
     */
    private String wxRefund(OrderEntity orderInfo,Double totalActualPrice){
        WechatRefundApiResult result = WechatUtil.wxRefund(orderInfo.getMerchOrderSn().toString(), totalActualPrice,
                orderInfo.getActualPrice().doubleValue());
        if (result.getResult_code().equals(WechatUtil.WXTradeState.SUCCESS.getCode())) {
            orderService.refund(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()));
            SysUserEntity user = ShiroUtils.getUserEntity();
            orderRefund.setModerSn(user.getUsername());
            orderRefund.setModTime(new Date());
//            orderRefund.setOutRefundNo(result.getOut_refund_no());
            if (mallOrderRefund != null) {
                orderRefund.setId(mallOrderRefund.getId());
                orderRefundService.update(orderRefund);//退款记录
            }
            OrderExceptionRecordEntity mallOrderExceptionRecord = new OrderExceptionRecordEntity();
            mallOrderExceptionRecord.setOrderSn(orderInfo.getOrderSn());
            mallOrderExceptionRecord.setUserId(Integer.parseInt(orderInfo.getUserId() + ""));
            mallOrderExceptionRecord.setExceptionStatus(Dict.exceptionStatus.item_03.getItem());
            mallOrderExceptionRecord.setExceptionContent("退款失败" + result.getErr_code_des());
            mallOrderExceptionRecord.setCreateTime(new Date());
            orderExceptionRecordService.save(mallOrderExceptionRecord);
            return result.getErr_code_des();
        }
        return "";
    }

    /**
     * 微信国际申请退款
     * @param orderInfo
     * @param totalActualPrice
     * @return
     */
    private String wxGlobalRefund(OrderEntity orderInfo,Double totalActualPrice){
        WechatGlobalRefundApiResult result = WechatGlobalUtil.wxRefund(orderInfo.getMerchOrderSn().toString(), totalActualPrice,
                orderInfo.getActualPrice().doubleValue());
        if (result.getResult_code().equals(WechatUtil.WXTradeState.SUCCESS.getCode())) {
            orderService.globalRefund(orderInfo, result);
        } else {
            OrderRefundEntity mallOrderRefund = orderRefundService.queryObjectByOrderId(orderInfo.getId());
            OrderRefundEntity orderRefund = new OrderRefundEntity();
            orderRefund.setRefundType(Integer.parseInt(Dict.RefundType.item_1.getItem()));
            orderRefund.setRefundStatus(Integer.parseInt(Dict.RefundStatus.item_4.getItem()));
            orderRefund.setRefundMoney(BigDecimal.valueOf(orderInfo.getActualPrice().doubleValue()));
//            orderRefund.setOutRefundNo(result.getOut_refund_no());
            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 result.getErr_code_des();
        }
        return "";
    }
    /**
     * 订单退款请求
     */
    @RequiresPermissions(value = {"order:offilineRefund"})
    @RequestMapping(value = "offilineRefund", method = RequestMethod.POST)
    public Object offilineRefund(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("订单已退款");
        }

        if (orderInfo.getOrderStatus() != Integer.parseInt(Dict.orderStatus.item_0.getItem())) {
            if (Dict.payFlag.item_cash.getItem().equals(orderInfo.getPayFlag())) {
                //现金支付，直接修改订单状态
                orderService.refund(orderInfo, null);
            } else if (Dict.payFlag.item_weixin.getItem().equals(orderInfo.getPayFlag())) {
                //微信线下扫码支付
                WechatRefundApiResult result = WechatUtil
                        .wxRefund(orderInfo.getOrderSnWx(), orderInfo.getActualPrice().doubleValue(),
                                  orderInfo.getActualPrice().doubleValue());
                if (result.getResult_code().equals(WechatUtil.WXTradeState.SUCCESS.getCode())) {
                    orderService.refund(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.setOutRefundNo(result.getOut_refund_no());
                    SysUserEntity user = ShiroUtils.getUserEntity();
                    orderRefund.setModerSn(user.getUsername());
                    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("退款成功");
    }

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

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

    @RequiresPermissions(value = {"order:orderSubmit"})
    @RequestMapping(value = "orderSubmit", method = RequestMethod.POST)
    @ResponseBody
    public R orderSubmit(@RequestBody List<OfflineCartEntity> offlineCartEntityList) {
        Map resultObj = null;
        try {
            SysUserEntity user = ShiroUtils.getUserEntity();
            resultObj = orderService.orderSubmit(offlineCartEntityList, user);
            if (((Integer) resultObj.get("errno")) != 0) {
                return R.error((String) resultObj.get("errmsg"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.ok("订单提交成功");
    }

    /**
     * 确认付款
     *
     * @param id
     * @return
     */
    @RequestMapping("/confirmPay")
    @RequiresPermissions("order:confirmPay")
    public R confirmPay(@RequestBody Long id) {
        orderService.confirmPay(id, Dict.payFlag.item_cash.getItem(), null);

        return R.ok();
    }

    @RequestMapping("/offilineOrderList")
    @RequiresPermissions("order:offilineOrderList")
    public R offilineOrderList(@RequestParam Map<String, Object> params) {
        ParamUtils.setQueryPowerByRoleType(params, "storeId", "merchSn", "thirdPartyMerchCode");
        //查询列表数据
        Query query = new Query(params);
        query.put("isOnfiilineOrder", Dict.isOnfflineOrder.item_1.getItem());
        List<OrderEntity> orderList = orderService.queryOffilineOrderList(query);
        int total = orderService.queryTotal(query);

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

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

    @RequestMapping("/offlineInfos/{id}")
    @RequiresPermissions("order:offlineInfos")
    public R queryObjectBySysUser(@PathVariable("id") Long id) {
        OrderEntity order = orderService.queryObjectBySysUser(id);
        List<OrderWXPayRecordEntity> payRecords = orderWXPayRecordService.getRecordsByOutTradeNo(order.getOrderSn());
        order.setPayRecordList(payRecords);
        return R.ok().put("order", order);
    }


    @RequestMapping("/wxMicropayPay")
    @RequiresPermissions("order:wxMicropayPay")
    public R wxMicropayPay(Long id, String auth_code) {
        R r = null;
        SysUserEntity user = ShiroUtils.getUserEntity();
        if (user == null) {
            throw new RRException("用户登录超时，请重新登录");
        }
        if (!user.getRoleType().equalsIgnoreCase("2")) {
            throw new RRException("该操作只允许店员账户操作");
        }
        OrderEntity orderEntity = orderService.queryObject(id);
        if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_201.getItem())) {
            throw new RRException("此订单已付款！");
        }
        if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_301.getItem())) {
            throw new RRException("此订单已完成！");
        }
        if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_101.getItem())) {
            throw new RRException("此订单已取消！");
        }
        if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_102.getItem())) {
            throw new RRException("此订单已删除！");
        }

        //保存支付记录
        OrderWXPayRecordEntity orderWXPayRecordCurrent = orderWXPayRecordService.saveRecord(orderEntity);

        StoreEntity store = storeService.queryObject(orderEntity.getStoreId());
        WechatMicropayApiResult wechatMicropayApiResult = WechatUtil
                .wxMicropay(store.getMerchName() + "-" + store.getStoreName(), orderEntity.getOrderBizType(), null,
                            orderWXPayRecordCurrent.getOutTradeNoWX(), orderEntity.getActualPrice().doubleValue(),
                            "127.0.0.1", auth_code);
        orderWXPayRecordService.updateRecord(orderWXPayRecordCurrent.getId(), wechatMicropayApiResult);

        //当支付成功时,修改订单,并把其他支付记录撤销
        if (WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatMicropayApiResult.getTrade_state())) {
            //查询当前订单所有的支付记录
            List<OrderWXPayRecordEntity> orderWXPayRecordEntitys =
                    orderWXPayRecordService.getRecordsByOutTradeNo(orderEntity.getOrderSn());
            for (OrderWXPayRecordEntity orderWXPayRecordTemp : orderWXPayRecordEntitys) {
                //查询出来的记录排除当前已支付成功的记录,对其他记录交易状态为未撤销,未关闭的订单，调用撤销订单
                if (orderWXPayRecordTemp.getId() != orderWXPayRecordCurrent.getId() &&
                    (!WechatUtil.WXTradeState.REVOKED.getCode().equals(orderWXPayRecordTemp.getTradeState()) ||
                     !WechatUtil.WXTradeState.CLOSED.getCode().equals(orderWXPayRecordTemp.getTradeState()))) {
                    WechatReverseApiResult wechatReverseApiResult =
                            WechatUtil.wxReverse(orderWXPayRecordTemp.getOutTradeNoWX());
                    //撤销订单成功
                    if (WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatReverseApiResult.getReturn_code()) &&
                            WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatReverseApiResult.getResult_code())) {
                        //调用订单查询接口
                        WechatRefundApiResult wechatRefundApiResult =
                                WechatUtil.wxOrderQuery(orderWXPayRecordTemp.getOutTradeNoWX());
                        if (WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatRefundApiResult.getReturn_code()) &&
                                WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatRefundApiResult.getResult_code())) {
                            // 修改订单支付记录
                            orderWXPayRecordService
                                    .updateWXPayRecordTradeState(orderWXPayRecordTemp.getId(), wechatRefundApiResult);
                        }
                    }
                }
            }
            orderService.confirmPay(id, Dict.payFlag.item_weixin.getItem(), orderWXPayRecordCurrent.getOutTradeNoWX());
            r = R.ok();
            //用户支付中
        } else if (WechatUtil.WXTradeState.USERPAYING.getCode().equals(wechatMicropayApiResult.getTrade_state())) {
            r = R.error(WechatUtil.WXTradeState.USERPAYING.getCodeZn() + ",稍等片刻后请刷新页面重新查看订单状态");
            //用户支付失败
        } else if (WechatUtil.WXTradeState.PAYERROR.getCode().equals(wechatMicropayApiResult.getTrade_state())) {
            WechatReverseApiResult wechatReverseApiResult =
                    WechatUtil.wxReverse(orderWXPayRecordCurrent.getOutTradeNoWX());
            //撤销订单成功
            if (WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatReverseApiResult.getReturn_code()) &&
                    WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatReverseApiResult.getResult_code())) {
                //调用订单查询接口
                WechatRefundApiResult wechatRefundApiResult =
                        WechatUtil.wxOrderQuery(orderWXPayRecordCurrent.getOutTradeNoWX());
                if (WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatRefundApiResult.getReturn_code()) &&
                        WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatRefundApiResult.getResult_code())) {
                    // 修改订单支付记录
                    orderWXPayRecordService
                            .updateWXPayRecordTradeState(orderWXPayRecordCurrent.getId(), wechatRefundApiResult);
                }
                r = R.error(orderWXPayRecordCurrent.getErrCodeDes());
            } else {
                r = R.error(wechatReverseApiResult.getErr_code_des());
            }

        }
        return r;
    }
    /**
     * 订单导出请求
     */
    @RequiresPermissions(value = {"order:export"})
    @RequestMapping(value = "export")
    public Object export(@RequestParam Map<String, Object> params, HttpServletResponse response, HttpServletRequest request) {
        ParamUtils.setQueryPowerByRoleType(params, "storeId", "merchSn", "thirdPartyMerchCode");
        params = ParamUtils.setTimeMap(params);
        //查询列表数据
        params.put("isOnfiilineOrder", Dict.isOnfflineOrder.item_0.getItem());
        List<OrderEntity> orderList = orderService.queryExportList(params);

        ExcelExport ee = new ExcelExport("订单信息");

        String[] header = new String[]{"订单编号","商户订单编号", "所属门店", "供应商", "供应商第三方商户代码", "订单状态", "SKU", "商品名称", "数量", "销售价", "实际支付金额", "保税模式", "快递公司名称", "快递单编号", "海关清单编号", "收货人姓名", "收件人手机", "收件人省份", "收件人城市", "收件人区县", "收件人地址", "下单时间", "支付流水号","身份证号"
                ,"原产国","规格型号","品牌","单位","毛重(kg)","净重"};

        List<Map<String, Object>> list = new ArrayList<>();
        if (orderList != null && orderList.size() != 0) {
            for (OrderEntity orderEntity : orderList) {
                LinkedHashMap<String, Object> map = new LinkedHashMap<>();
                Integer orderStatus = orderEntity.getOrderStatus();
                String orderBizType = orderEntity.getOrderBizType();

                map.put("OrderSn", orderEntity.getOrderSn());
                map.put("MerchOrderSn", orderEntity.getMerchOrderSn());
                map.put("StoreName", orderEntity.getStoreName());
                map.put("SupplierThirdPartyMerchName", orderEntity.getSupplierThirdPartyMerchName());
                map.put("SupplierThirdPartyMerchCode", orderEntity.getSupplierThirdPartyMerchCode());
                map.put("OrderStatus", StringUtils.isEmpty(orderStatus.toString())? "":Dict.orderStatus.valueOf("item_"+ orderStatus).getItemName());
                map.put("SKU", orderEntity.getSku());
                map.put("GoodsName", orderEntity.getGoodsName());
                map.put("Number", orderEntity.getNumber());
                map.put("RetailPrice", orderEntity.getRetailPrice());
                map.put("ActualPrice", orderEntity.getActualPrice());

                map.put("OrderBizType", StringUtils.isEmpty(orderBizType)? "":Dict.orderBizType.valueOf("item_"+orderBizType).getItemName());
                map.put("ShippingName", orderEntity.getShippingName());
                map.put("ShippingNo", orderEntity.getShippingNo());
                map.put("InvtNo", orderEntity.getOrderProcessRecord()==null?"":orderEntity.getOrderProcessRecord().getInvtNo());
                map.put("Consignee", orderEntity.getConsignee());
                map.put("Mobile", orderEntity.getMobile());
                map.put("Province", orderEntity.getProvince());
                map.put("City", orderEntity.getCity());
                map.put("District", orderEntity.getDistrict());
                map.put("Address", orderEntity.getAddress());

                map.put("OrderStartTime", orderEntity.getOrderProcessRecord()==null?"":DateUtils.format(orderEntity.getOrderProcessRecord().getAddOrderStartTime(),"yyyy-MM-dd HH:mm:ss"));
                map.put("PayId", orderEntity.getPayTransactionId());
                map.put("IdNo", orderEntity.getIdNo());
                map.put("OriCntCode", orderEntity.getOriCntCode());
                map.put("CiqProdModel", orderEntity.getCiqProdModel());
                map.put("Brand", orderEntity.getBrand());
                map.put("UnitCode", orderEntity.getUnitCode());
                map.put("GrossWeight", orderEntity.getGrossWeight());
                map.put("NetWeight", orderEntity.getNetWeight());

                list.add(map);
            }
        }

        ee.addSheetByMap("订单信息", list, header);
        ee.export(response);
        return R.ok();
    }

    /**
     * 订单修改已发货的快递信息
     */
    @RequestMapping("/updateExpressInfo")
    @RequiresPermissions("order:updateExpressInfo")
    public Object updateExpressInfo(@RequestBody OrderEntity orderEntity) {
        OrderEntity orderInfo = orderService.queryObject(orderEntity.getId());
        if (orderInfo != null){
            if(orderInfo.getShippingStatus() == Integer.parseInt(Dict.shippingStatus.item_1.getItem())) {
                OrderEntity order = new OrderEntity();
                order.setId(orderInfo.getId());
                order.setShippingCode(orderEntity.getShippingCode());
                Map map = new HashMap();
                map.put("code", orderEntity.getShippingCode());
                ShippingEntity shippingEntity = shippingService.queryObjectByCode(orderEntity.getShippingCode());
                if(shippingEntity != null) {
                    order.setShippingName(shippingEntity.getName());
                }else{
                    throw new RRException("此订单修改的快递公司信息不存在！不能操作");
                }
                order.setShippingNo(orderEntity.getShippingNo());
                order.setModerSn(ShiroUtils.getUserEntity().getUsername());
                order.setModTime(new Date());
                orderService.update(order);
            }else{
                throw new RRException("此订单"+Dict.shippingStatus.valueOf("item_"+orderInfo.getShippingStatus()).getItemName()+"！不能操作");
            }
        }
        return R.ok();
    }


    /**
     * 上传文件
     */
    @RequestMapping("/expressUpload")
    public R expressUpload(@RequestParam("file") MultipartFile file) {
        List<OrderExpressDto> orderExpressList = new ArrayList<>();//快递信息
        try {
            Map<String, Object> beans = new HashMap<String, Object>();
            beans.put("OrderExpressList", orderExpressList);
            if (file.isEmpty()) {
                return R.error("文件不能为空！");
            }
            excelUtil.readExcel(JxlsXmlTemplateName.ORDER_EXPRESS_LIST, beans, file.getInputStream());
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("导入失败！");
        }
        orderService.uploadExcel(orderExpressList);
        //上传文件
        return R.ok();
    }

    /**
     * 获取ccnet需要重发的订单数据
     */
    @RequestMapping("/wxOrderResendQueryAllList")
    public R wxOrderResendQueryAllList(@RequestParam Map<String, Object> params) {
        ParamUtils.setQueryPowerByRoleType(params, "storeId", "merchSn", "thirdPartyMerchCode");
        //查询列表数据
        Query query = new Query(params);

        List<WxOrderEntity> orderList = orderService.wxOrderResendQueryAllList(query);

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

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