package com.ruoyi.mall.controller;

import java.math.BigDecimal;
import java.util.*;

import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.ApiResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.sign.Md5Utils;
import com.ruoyi.common.weiXin.WeiXinUtils;
import com.ruoyi.mall.domain.*;
import com.ruoyi.mall.domain.vo.MallOrderGoodsExportVO;
import com.ruoyi.mall.service.IMallMemberUserService;
import com.ruoyi.mall.service.IMallOrderBackService;
import com.ruoyi.mall.service.IMallShopShopService;
import com.ruoyi.web.controller.utils.XiaochengxuPayService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.mall.service.IMallOrderOrderService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 订单Controller
 *
 * @author chang
 * @date 2021-11-25
 */
@RestController
@RequestMapping("/mall/mallOrderOrder")
public class MallOrderOrderController extends BaseController
{
    @Autowired
    private IMallOrderOrderService mallOrderOrderService;

    @Autowired
    private IMallOrderBackService orderBackService;

    @Autowired
    private WeiXinUtils weiXinUtils;

    @Autowired
    private IMallMemberUserService memberUserService;

    @Autowired
    private IMallShopShopService shopShopService;

    /**
     * 查询订单列表
     */
    @PreAuthorize("@ss.hasPermi('mall:mallOrderOrder:list')")
    @GetMapping("/list")
    public TableDataInfo list(MallOrderOrder mallOrderOrder)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();

        MallShopShop mallShopShop = shopShopService.selectMallShopShopBySysUserId(loginUser.getUserId());
        if (ObjectUtils.isNotEmpty(mallShopShop)){
            mallOrderOrder.setShopId(mallShopShop.getShopId());
        }

        startPage();
        List<MallOrderOrder> list = mallOrderOrderService.selectMallOrderOrderList(mallOrderOrder);
        return getDataTable(list);
    }

    /**
     * 导出订单列表
     */
    @PreAuthorize("@ss.hasPermi('mall:mallOrderOrder:export')")
    @Log(title = "订单", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(MallOrderOrder mallOrderOrder)
    {
        List<MallOrderGoodsExportVO> list = mallOrderOrderService.selectExportOrderList(mallOrderOrder);
        ExcelUtil<MallOrderGoodsExportVO> util = new ExcelUtil<MallOrderGoodsExportVO>(MallOrderGoodsExportVO.class);
        return util.exportExcel(list, "订单数据");
    }

    /**
     * 获取订单详细信息
     */
    @PreAuthorize("@ss.hasPermi('mall:mallOrderOrder:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(mallOrderOrderService.selectMallOrderOrderById(id));
    }

    /**
     * 新增订单
     */
    @PreAuthorize("@ss.hasPermi('mall:mallOrderOrder:add')")
    @Log(title = "订单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MallOrderOrder mallOrderOrder)
    {
        return toAjax(mallOrderOrderService.insertMallOrderOrder(mallOrderOrder));
    }

    /**
     * 批量发货
     */
    @Log(title = "订单批量发货", businessType = BusinessType.UPDATE)
    @PostMapping("/deliveryByOrderIds")
    public AjaxResult deliveryByOrderIds(@RequestBody Integer[] orderIds)
    {
        return mallOrderOrderService.deliveryByOrderIds(orderIds);
    }

    /**
     * 批量打印数据
     */
    @Log(title = "批量打印数据", businessType = BusinessType.UPDATE)
    @PostMapping("/batchPrintData")
    public AjaxResult batchPrintData(@RequestBody Long[] orderIds)
    {
        return mallOrderOrderService.batchPrintData(orderIds);
    }

    /**
     * 修改订单
     */
    @PreAuthorize("@ss.hasPermi('mall:mallOrderOrder:edit')")
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MallOrderOrder mallOrderOrder)
    {
        if ("6".equals(mallOrderOrder.getStatus()) || "9".equals(mallOrderOrder.getStatus())){
            Map<String, Object> map = new HashMap<>();
            List<MallOrderBack> list = orderBackService.selectMallOrderBackByOrderId(mallOrderOrder.getId());
            MallOrderBack result = new MallOrderBack();
            for (MallOrderBack orderBack: list) {
                result = orderBack;
            }
            map.put("refundId",result.getId());
            if ("6".equals(mallOrderOrder.getStatus())) {
                //退款
                map.put("isAccept", "1");
                Map<String, Object> map1  = new HashMap<>();
                map1.put("backId",result.getId().toString());
                return refundAgree(map1);
            }

            if ("9".equals(mallOrderOrder.getStatus())) {
                map.put("isAccept", "0");
            }

            Boolean isAccept = mallOrderOrderService.refundStatusRoute(Integer.parseInt("1"),map.get("refundId").toString());
            if (isAccept == true) {
                int status = orderBackService.handleRefund(map);
                return status > 0 ? AjaxResult.success("操作成功") : AjaxResult.error("操作失败");
            }else {
                return AjaxResult.error("订单异常");
            }
        }

        // 原订单状态
        //MallOrderOrder oldInfo = mallOrderOrderService.selectMallOrderOrderById(mallOrderOrder.getId());
        //if("1".equals(oldInfo.getStatus()) && "2".equals(mallOrderOrder.getStatus())){
        //    // 查询用户openId
        //    MallMemberUser mallMemberUser = memberUserService.selectMallMemberUserById(mallOrderOrder.getUserId());
        //    // 设置发货时候同步发货信息给微信
        //    if (StringUtils.isNotBlank(mallMemberUser.getOpenid())){
        //
        //        String s = weiXinUtils.deliveryInfo(mallOrderOrder.getTotalOrderSn(), mallMemberUser.getOpenid());
        //        //if (!"SUCCESS".equals(s)){
        //        //    System.out.println("发货信息同步失败");
        //        //}
        //    }
        //}
        return toAjax(mallOrderOrderService.updateMallOrderOrder(mallOrderOrder));
    }

    /**
     * 删除订单
     */
    @PreAuthorize("@ss.hasPermi('mall:mallOrderOrder:remove')")
    @Log(title = "订单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(mallOrderOrderService.deleteMallOrderOrderByIds(ids));
    }

    /**
     * 发货
     */
    @PostMapping("/order/sendOrder")
    public ApiResult sendOrder(@RequestBody Map<String, Object> params)
    {
        try {
            if(!params.containsKey("shippingMark") || StringUtils.isEmpty(params.get("shippingMark").toString())
                    || !params.containsKey("shippingName") || StringUtils.isEmpty(params.get("shippingName").toString()) ||
                    !params.containsKey("shippingCode") || StringUtils.isEmpty(params.get("shippingCode").toString()) ||
                    !params.containsKey("orderId") || StringUtils.isEmpty(params.get("orderId").toString())){
                return ApiResult.error("缺少参数");
            }
            MallOrderOrder order = mallOrderOrderService.selectMallOrderOrderById(Long.parseLong(params.get("orderId").toString()));
            order.setShippingMark(params.get("shippingMark").toString());
            order.setShippingName(params.get("shippingName").toString());
            order.setShippingCode(params.get("shippingCode").toString());
            order.setConsignAt(new Date().toString());
            Boolean isAccept = mallOrderOrderService.orderStatusRoute(Integer.parseInt("2"),params.get("orderId").toString());
            if (isAccept == true) {
                order.setStatus("2");
                int status = mallOrderOrderService.updateMallOrderOrder(order);
                return status > 0 ? ApiResult.ok("成功") : ApiResult.error("失败");
            }else {
                return ApiResult.error("订单异常");
            }

        } catch (Exception e) {
            e.printStackTrace();
            return ApiResult.error("失败");
        }
    }

    public AjaxResult refundAgree(Map<String, Object> map) {
        MallOrderBack orderBack = orderBackService.selectMallOrderBackById(Long.parseLong(map.get("backId").toString()));
        if (orderBack == null) {
            return AjaxResult.error("退款信息异常");
        }
        if (!"0".equals(orderBack.getStatus())) {
            return AjaxResult.error("只有待审核状态才能退款");
        }
        MallOrderOrder orderOrder = mallOrderOrderService.selectMallOrderOrderById(orderBack.getOrderId());
        if (orderOrder == null) {
            return AjaxResult.error("订单信息异常");
        }

        try{

            return AjaxResult.success("退款成功");
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 获取退货订单详细信息
     */
    @GetMapping(value = "/orderBack/{orderBackId}")
    public AjaxResult getOrderBackInfo(@PathVariable("orderBackId") Long orderBackId)
    {
        MallOrderBack mallOrderBack = orderBackService.selectMallOrderBackById(orderBackId);
        return AjaxResult.success(mallOrderOrderService.selectMallOrderBackById(mallOrderBack.getOrderId()));
    }

    /**
     * 导出订单列表
     */
    @PreAuthorize("@ss.hasPermi('mall:mallOrderOrder:export')")
    @Log(title = "导出订单", businessType = BusinessType.EXPORT)
    @PostMapping("/exportOrder")
    public AjaxResult exportOrder(@RequestBody Long[] orderIds)
    {
        List<MallOrderGoodsExportVO> list = mallOrderOrderService.selectExportOrderMallOrderOrderList(orderIds);
        ExcelUtil<MallOrderGoodsExportVO> util = new ExcelUtil<MallOrderGoodsExportVO>(MallOrderGoodsExportVO.class);
        return util.exportExcel(list, "订单数据");
    }
}
