package com.qs.mp.web.controller.api.channel;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qs.mp.channel.domain.ChannelGoodsOrder;
import com.qs.mp.channel.domain.ChannelGoodsSettleOrder;
import com.qs.mp.channel.domain.ChannelGoodsSettleOrderItem;
import com.qs.mp.channel.domain.param.OrderPayParam;
import com.qs.mp.channel.domain.vo.ChannelGoodsSettleOrderItemVO;
import com.qs.mp.channel.domain.vo.ChannelSettleVO;
import com.qs.mp.channel.service.IChannelGoodsSettleOrderItemService;
import com.qs.mp.channel.service.IChannelGoodsSettleOrderService;
import com.qs.mp.common.core.domain.AjaxResult;
import com.qs.mp.common.core.page.TableDataInfo;
import com.qs.mp.common.enums.AppSourceEnum;
import com.qs.mp.common.enums.BizTypeEnum;
import com.qs.mp.common.enums.ErrorCodeEnum;
import com.qs.mp.common.exception.ServiceException;
import com.qs.mp.common.utils.LogUtil;
import com.qs.mp.common.utils.StringUtils;
import com.qs.mp.pay.service.IWalletService;
import com.qs.mp.system.domain.SysUser;
import com.qs.mp.system.service.ISysUserService;
import com.qs.mp.utils.SecurityUtils;
import com.qs.mp.web.controller.common.BaseApiController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import ma.glasnost.orika.MapperFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * @author zhangkaikai
 * @create 2023-06-08 6:56 PM
 **/

@Api(tags = "我的结算")
@RestController
@RequestMapping("/api/v1/mp/channel/goods/*")
public class ChannelGoodsSettleController extends BaseApiController {

    @Autowired
    private IChannelGoodsSettleOrderService settleOrderService;

    @Autowired
    private IChannelGoodsSettleOrderItemService  settleOrderItemService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IWalletService walletService;

    @Autowired
    private MapperFacade mapperFacade;


    @PostMapping("/settle/list")
    @ApiOperation("我的结算列表")
    @ApiResponses(
            @ApiResponse(code = 200, message = "成功", response = ChannelSettleVO.class)
    )
    public TableDataInfo list() {
        Long channelId = SecurityUtils.getLoginUser().getChannelId();
        startPage();
        List<ChannelSettleVO> list = settleOrderService.listGoodsSettleOrder(new QueryWrapper<ChannelGoodsSettleOrder>()
                .eq("t1.channel_id", channelId)
                .orderByAsc("t1.status")
                .orderByDesc("t1.created_time"));
        List<ChannelSettleVO> channelSettleVOS = mapperFacade.mapAsList(list, ChannelSettleVO.class);
        return getDataTable(channelSettleVOS);
    }

    @PostMapping("/settle/detail/{orderId}")
    @ApiOperation("我的结算详情")
    @ApiResponses(
            @ApiResponse(code = 200, message = "成功", response = ChannelSettleVO.class)
    )
    public AjaxResult detail(@PathVariable String orderId) {
        Long channelId = SecurityUtils.getLoginUser().getChannelId();
        ChannelGoodsSettleOrder settleOrder = settleOrderService.getById(orderId);
        ChannelSettleVO channelSettleVO = mapperFacade.map(settleOrder, ChannelSettleVO.class);
        List<ChannelGoodsSettleOrderItemVO> items = settleOrderItemService.listSettleOrderItemVO(new QueryWrapper<ChannelGoodsSettleOrderItem>()
                .eq("t1.channel_id", channelId)
                .eq("t1.order_id", orderId));
        channelSettleVO.setItems(items);
        channelSettleVO.setPurchaseOrderId(items.get(0).getPurchaseOrderId());
        return AjaxResult.success(channelSettleVO);
    }

    @PostMapping("/settle/order/pay")
    @ApiOperation("我的结算支付")
    public AjaxResult pay(@Valid @RequestBody OrderPayParam param) {
        Long userId = SecurityUtils.getLoginUser().getUserId();
        SysUser sysUser = sysUserService.selectUserById(userId);
        String channelOpenId = "";
        if (StringUtils.isNotBlank(param.getOpenId())) {
            channelOpenId = param.getOpenId();
        } else {
            channelOpenId = sysUser.getChannelOpenId();
        }
        if (StringUtils.isBlank(channelOpenId)) {
            return AjaxResult.error(ErrorCodeEnum.ERROR_CODE_1005);
        }

        ChannelGoodsSettleOrder channelGoodsOrder = settleOrderService.getById(param.getOrderId());
        JSONObject jsonObject;
        try {
            jsonObject = walletService.pay(BizTypeEnum.CHANNEL_GOODS__SETTLE_ORDER, param.getOrderId(), channelOpenId, channelGoodsOrder.getSettleAmt(), channelGoodsOrder.getTitle(), AppSourceEnum.CHANNEL.getValue());
        } catch (ServiceException e) {
            LogUtil.error(logger, e, "门店采购商品结算订单创建支付单失败。userId:{0},orderId:{1}", new Object[]{userId, param.getOrderId()});
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success(jsonObject);
    }
}
