package com.ruoyi.mall.controller;

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

import com.ruoyi.common.utils.ApiResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.sign.Md5Utils;
import com.ruoyi.mall.domain.MallOrderBack;
import com.ruoyi.mall.service.IMallOrderBackService;
import com.ruoyi.web.controller.utils.XiaochengxuPayService;
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.domain.MallOrderOrder;
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;

    /**
     * 查询订单列表
     */
    @PreAuthorize("@ss.hasPermi('mall:mallOrderOrder:list')")
    @GetMapping("/list")
    public TableDataInfo list(MallOrderOrder mallOrderOrder)
    {
        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<MallOrderOrder> list = mallOrderOrderService.selectMallOrderOrderList(mallOrderOrder);
        ExcelUtil<MallOrderOrder> util = new ExcelUtil<MallOrderOrder>(MallOrderOrder.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));
    }

    /**
     * 修改订单
     */
    @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("订单异常");
            }
        }
        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{
//            orderBack.setStatus("1");
//            orderBack.setUpdateAt(DateUtils.getTime());
//            orderOrder.setStatus("6");
//            SortedMap<String, String> data = new TreeMap<>();
//            //退款到用户微信
//            String nonce_str = Md5Utils.getRandomStringByLength(32);
//            data.put("nonce_str", nonce_str);
//            data.put("out_trade_no", orderOrder.getOrderNo());//商户订单号
//            data.put("out_refund_no", orderOrder.getId().toString());//商户退款单号,一笔退款失败后重新提交，请不要更换退款单号，请使用原商户退款单号
//            int total_fee = Math.round(Float.valueOf(orderOrder.getPayment().multiply(new BigDecimal(100)).toString()));
//            data.put("total_fee", String.valueOf(Math.round(total_fee)));//支付金额，微信支付提交的金额是不能带小数点的，且是以分为单位,这边需要转成字符串类型，否则后面的签名会失败
//            data.put("refund_fee", String.valueOf(Math.round(total_fee)));//退款总金额,单位为分,只能为整数
//            boolean fl = XiaochengxuPayService.wxXcxRefund(data);
//            if (!fl) {
//                return AjaxResult.error("微信app退款异常");
//            }
//
//            mallOrderOrderService.updateRefundRestlt(orderBack,orderOrder);

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