package com.fzm.mall.server.front.asset.controller;


import com.alibaba.fastjson.JSONObject;
import com.fzm.mall.server.front.asset.model.Tran;
import com.fzm.mall.server.front.asset.model.TranOrder;
import com.fzm.mall.server.front.asset.model.TranPay;
import com.fzm.mall.server.front.asset.model.po.CreateTranOrderPo;
import com.fzm.mall.server.front.asset.model.vo.GoodsTransVO;
import com.fzm.mall.server.front.asset.model.vo.PriceVo;
import com.fzm.mall.server.front.asset.model.vo.TranOrderListVo;
import com.fzm.mall.server.front.asset.model.vo.TranOrderPayVO;
import com.fzm.mall.server.front.asset.service.ITranOrderService;
import com.fzm.mall.server.front.asset.service.ITranPayService;
import com.fzm.mall.server.front.asset.service.ITranService;
import com.fzm.mall.server.front.base.ResponseVO;
import com.fzm.mall.server.front.constant.MallResponseEnum;
import com.fzm.mall.server.front.enums.QueueTypeEnum;
import com.fzm.mall.server.front.goods.model.vo.PageVoWithOne;
import com.fzm.mall.server.front.goods.model.vo.SkuVo;
import com.fzm.mall.server.front.goods.service.IGoodSkuService;
import com.fzm.mall.server.front.mq.MsgProducer;
import com.fzm.mall.server.front.order.model.OrderDetail;
import com.fzm.mall.server.front.order.model.vo.PayVo;
import com.fzm.mall.server.front.order.service.IOrderDetailService;
import com.fzm.mall.server.front.user.model.Header;
import com.fzm.mall.server.front.user.model.User;
import com.fzm.mall.server.front.user.service.IRedisService;
import com.fzm.mall.server.front.user.service.IUserService;
import com.fzm.mall.server.front.util.Sha256Util;
import io.netty.util.internal.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import springfox.documentation.annotations.ApiIgnore;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author fzm
 * @since 2021-09-07
 */
@Api(tags = "商品订单接口", description = "用户下单，撤销订单等")
@Slf4j
@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@RequestMapping(value = "/mall/tran/order", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class TranOrderController {


    private final ITranOrderService tranOrderService;

    private final ITranService tranService;

    private  final IRedisService redisService;

    private final MsgProducer msgProducer;

    private final ITranPayService tranPayService;

    private final IGoodSkuService goodSkuService;

    private final IOrderDetailService orderDetailService;

    private final IUserService userService;

    @ApiOperation(value = "转让商品下单")
    @PostMapping("/createOrder")
    public ResponseVO createOrder(@ApiIgnore @RequestAttribute Header header,@RequestBody CreateTranOrderPo createTranOrderPo) {
        if(StringUtil.isNullOrEmpty(createTranOrderPo.getTranId())||createTranOrderPo.getDelivery()==null||createTranOrderPo.getNumber()==null
        ||createTranOrderPo.getNumber()<=0){
            return new ResponseVO(MallResponseEnum.PARAMETER_ERR);
        }

        if(createTranOrderPo.getDelivery() == 1){
            if(StringUtil.isNullOrEmpty(createTranOrderPo.getUaddress())||StringUtil.isNullOrEmpty(createTranOrderPo.getProvince())||StringUtil.isNullOrEmpty(createTranOrderPo.getUname())||
            StringUtil.isNullOrEmpty(createTranOrderPo.getUphone())){
                return new ResponseVO(MallResponseEnum.PARAMETER_ERR);
            }
        }
        Tran tran = tranService.getByTranId(createTranOrderPo.getTranId());
        if(tran == null||tran.getStatus() != 1){
            return new ResponseVO(MallResponseEnum.SUCCESS);
        }
      /*  if(header.getUid().equals(tran.getUid())){
            return new ResponseVO(MallResponseEnum.NOT_SUPPORT_BUY_MYSELF);
        }*/
        if(!redisService.setNx(header.getUid()+"tran_createOrder")){
            return  new ResponseVO(MallResponseEnum.OPERATION_OFTEN);
        }
        TranPay pid = new TranPay();
        try{
            pid = tranOrderService.createOrder(header.getUid(),tran.getId(),createTranOrderPo);
        }catch (Exception e){
            if("stock_err".equals(e.getMessage())){
                return  new ResponseVO(MallResponseEnum.GOOD_STOCK_NOT_ENOUGH);
            }else if("当前地区不支持快递".equals(e.getMessage())){
                return  new ResponseVO(MallResponseEnum.NOT_SUPPORT_MAIL);
            }else{
                log.error(e.toString());
                return  new ResponseVO(MallResponseEnum.DB_ERROR);
            }
        }finally {
            redisService.del(header.getUid()+"tran_createOrder");
        }
        return  new ResponseVO(MallResponseEnum.SUCCESS,pid);
    }

    @ApiOperation(value = "转让订单支付")
    @PostMapping("/pay")
    public ResponseVO getTranGoods(@ApiIgnore @RequestAttribute Header header, @RequestBody PayVo payVo) {
        String pid = payVo.getPid();
        if (StringUtil.isNullOrEmpty(header.getPayPassword())) {
            return new ResponseVO<>(MallResponseEnum.NOT_SET_PAY_PASSWORD);
        }
        if (StringUtil.isNullOrEmpty(payVo.getPayPassword())) {
            return new ResponseVO<>(MallResponseEnum.PARAMETER_ERR);
        }
        if (!Sha256Util.sha256String(payVo.getPayPassword()).equals(header.getPayPassword())) {
            return new ResponseVO<>(MallResponseEnum.PAY_PASSWORD_ERR);
        }
        if (!redisService.setNx(header.getUid() + "_pay")) {
            return new ResponseVO<>(MallResponseEnum.OPERATION_OFTEN);
        }
        if(!redisService.setNx(header.getUid()+"tran_pay")){
            return  new ResponseVO(MallResponseEnum.OPERATION_OFTEN);
        }
        int i = tranPayService.pay(header.getUid(), pid);
        redisService.del(header.getUid()+"tran_pay");
        if (i == 1) {
            //发送消息队列
            msgProducer.send(pid, QueueTypeEnum.TRAN_PAY);
            return new ResponseVO(MallResponseEnum.SUCCESS);
            //资产不足
        } else if (i == 0) {
            return new ResponseVO(MallResponseEnum.ASSET_NOT_ENOUGH);
        } else if (i == -1) {
            return new ResponseVO(MallResponseEnum.ORDER_NOT_PAY);
        } else {
            return new ResponseVO(MallResponseEnum.DB_ERROR);
        }
    }

    @ApiOperation(value = "转让订单订单 param 1：全部 2转出 3转入")
    @PostMapping("/tranOrderList")
    public ResponseVO tranOrderList(@ApiIgnore @RequestAttribute Header header, @RequestBody PageVoWithOne pageVoWithOne) {
        List<TranOrderPayVO> tranOrderPayVOS = new ArrayList<>();
        List<TranOrder> tranOrders = new ArrayList<>();
        int size = 0;
        String type = pageVoWithOne.getParam();
        if(StringUtil.isNullOrEmpty(type)||pageVoWithOne.getPage()==null||pageVoWithOne.getPage()<0||pageVoWithOne.getSize()==null||
        pageVoWithOne.getSize()<=0){
            return  new ResponseVO(MallResponseEnum.PARAMETER_ERR);
        }
        if("1".equals(type)){
            tranOrders = tranOrderService.getListAll(header.getUid(),pageVoWithOne);
            size = tranOrderService.getAll(header.getUid());
        }else if("2".equals(type)){
            tranOrders = tranOrderService.getListOut(header.getUid(),pageVoWithOne);
            size = tranOrderService.getOut(header.getUid());
        }else{
            tranOrders = tranOrderService.getListIn(header.getUid(),pageVoWithOne);
            size = tranOrderService.getIn(header.getUid());
        }
        for (TranOrder tranOrder: tranOrders) {
            TranOrderPayVO tranOrderPayVO = new TranOrderPayVO();
            SkuVo skuVoBySkuId = goodSkuService.getSkuVoBySkuId(tranOrder.getSkuId());
            tranOrderPayVO.setSkuVo(skuVoBySkuId);
            TranPay tranPay = tranPayService.getByOid(tranOrder.getOid());
            tranOrderPayVO.setTranPay(tranPay);
            tranOrderPayVOS.add(tranOrderPayVO);
            User byUid = userService.getByUid(tranOrder.getSeller());
            tranOrder.setSellerInfo(byUid);
            tranOrderPayVO.setTranOrder(tranOrder);
        }
        TranOrderListVo tranOrderListVo = new TranOrderListVo();
        tranOrderListVo.setData(tranOrderPayVOS);
        tranOrderListVo.setTotalSize(size);
        return  new ResponseVO(MallResponseEnum.SUCCESS,tranOrderListVo);
    }

    @ApiOperation(value = "转让订单详情 param oid")
    @PostMapping("/tranOrderDetail")
    public ResponseVO tranOrderDetail(@ApiIgnore @RequestAttribute Header header, @RequestBody JSONObject data) {
        String oid = data.getString("oid");
        TranOrder tranOrder = tranOrderService.getByOid(oid);
        if(tranOrder == null){
            return  new ResponseVO(MallResponseEnum.PARAMETER_ERR);
        }
        TranOrderPayVO tranOrderPayVO = new TranOrderPayVO();
        tranOrderPayVO.setTranOrder(tranOrder);
        SkuVo skuVoBySkuId = goodSkuService.getSkuVoBySkuId(tranOrder.getSkuId());
        tranOrderPayVO.setSkuVo(skuVoBySkuId);
        TranPay tranPay = tranPayService.getByOid(tranOrder.getOid());
        tranOrderPayVO.setTranPay(tranPay);
        return  new ResponseVO(MallResponseEnum.SUCCESS,tranOrderPayVO);
    }

    @ApiOperation(value = "转让订单支付结果 参数pid")
    @PostMapping("/payResult")
    public ResponseVO getTranGoods(@RequestBody JSONObject data) {
        String pid = data.getString("pid");
        TranPay tranPay = tranPayService.getByPid(pid);
        if(tranPay == null){
            return  new ResponseVO(MallResponseEnum.PARAMETER_ERR);
        }
        return  new ResponseVO(MallResponseEnum.SUCCESS,tranPay);

    }
    @ApiOperation(value = "均价 参数skuId")
    @PostMapping("/getPrice")
    public ResponseVO getPrice(@ApiIgnore @RequestAttribute Header header,@RequestBody JSONObject data) {
        String skuId = data.getString("skuId");
        SkuVo skuVoBySkuId = goodSkuService.getSkuVoBySkuId(skuId);
        if(skuVoBySkuId==null){
            return  new ResponseVO(MallResponseEnum.PARAMETER_ERR);
        }
        List<OrderDetail> list = orderDetailService.getByUidAndSkuId(header.getUid(),skuId);
        int number = 0;
        BigDecimal all = BigDecimal.ZERO;
        for (OrderDetail orderDetail: list) {
            number = number + orderDetail.getNumber();
            all = all.add(new BigDecimal(orderDetail.getNumber()).multiply(orderDetail.getAmount()));
        }
        PriceVo priceVo = new PriceVo();
        priceVo.setNewPrice(skuVoBySkuId.getOriginalPrice());
        priceVo.setAvgPrice(all.divide(new BigDecimal(number)).setScale(2));
        return  new ResponseVO(MallResponseEnum.SUCCESS,priceVo);
    }
}
