package cn.pluss.platform.controller;

import cn.jiguang.common.utils.StringUtils;
import cn.pluss.platform.ali.AliService;
import cn.pluss.platform.api.PageInfo;
import cn.pluss.platform.api.Result;
import cn.pluss.platform.api.ResultGenerator;
import cn.pluss.platform.constants.ProjectConstant;
import cn.pluss.platform.device.DeviceOrderInfoService;
import cn.pluss.platform.deviceDetail.DeviceDetailService;
import cn.pluss.platform.deviceMerchantBuy.DeviceMerchantBuyService;
import cn.pluss.platform.dto.DeviceMerchantBuyDTO;
import cn.pluss.platform.entity.DeviceMerchantBuy;
import cn.pluss.platform.entity.DeviceOrderInfo;
import cn.pluss.platform.entity.MerchantChannelStatus;
import cn.pluss.platform.entity.UserApp;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.merchant.MerchantBaseInfoService;
import cn.pluss.platform.merchantChannelStatus.MerchantChannelStatusService;
import cn.pluss.platform.userApp.UserAppService;
import cn.pluss.platform.util.StringUtil;
import cn.pluss.platform.vo.DeviceMerchantBuyVO;
import cn.pluss.platform.wechat.WechatService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;


/**
 * @author DJH
 */
@RestController
@RequestMapping("/deviceMerchantBuy")
@Api(value = "DeviceMerchantBuy控制类", tags = {"DeviceMerchantBuy接口"})
public class DeviceMerchantBuyController {

    @Setter(onMethod_ = {@Autowired})
    private DeviceMerchantBuyService deviceMerchantBuyService;

    @Setter(onMethod_ = {@Autowired})
    private AliService aliService;

    @Setter(onMethod_ = {@Autowired})
    private WechatService wechatService;

    @Setter(onMethod_ = {@Autowired})
    private HttpServletRequest request;

    @Setter(onMethod_ = {@Autowired})
    private UserAppService userAppService;

    @Setter(onMethod_ = {@Autowired})
    private MerchantBaseInfoService mbiService;

    @Setter(onMethod_ = {@Autowired})
    private MerchantChannelStatusService mcsService;

    @Setter(onMethod_ = {@Autowired})
    private DeviceDetailService deviceDetailService;

    @Setter(onMethod_ = {@Autowired})
    private DeviceOrderInfoService doiService;

    @Autowired
    private DeviceMerchantBuyService dmbService;

    @GetMapping
    @ApiOperation(value = "获取全部", notes = "返回分页过后的数据", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "查询页码", paramType = "query", dataType = "Integer", defaultValue = "0"),
            @ApiImplicitParam(name = "size", value = "每页数据量", paramType = "query", dataType = "Integer", defaultValue = "0")
    })
    public Result<PageInfo<DeviceMerchantBuy>> list(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer size) {
        if (size == null || size == 0) {
            size = ProjectConstant.PAGE_SIZE;
        }
        if (page == null || page == 0) {
            page = 1;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("pageSize", size);
        map.put("offset", (page - 1) * size);
        List<DeviceMerchantBuy> deviceMerchantBuyList = deviceMerchantBuyService.queryDeviceMerchantBuyPage(map);
        Integer count = deviceMerchantBuyService.queryDeviceMerchantBuyPageCount(map);
        //返回参数
        PageInfo<DeviceMerchantBuy> pager = new PageInfo<>(count.longValue(), (long) StringUtil.getPageCount(count, size), page.longValue(), size.longValue(), deviceMerchantBuyList);
        return ResultGenerator.genSuccessResult(pager);
    }

    @PostMapping
    @ApiOperation(value = "添加数据", notes = "添加新的数据", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "DeviceMerchantBuy", value = "待添加的DeviceMerchantBuy实例", paramType = "body", dataType = "DeviceMerchantBuy", required = true)
    })
    public Result<?> add(@RequestBody DeviceMerchantBuy deviceMerchantBuy) {
        deviceMerchantBuyService.saveDeviceMerchantBuy(deviceMerchantBuy);
        return ResultGenerator.genSuccessResult();
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除数据", notes = "根据id删除数据", httpMethod = "DELETE")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "查询的id实例", paramType = "path", dataType = "Integer", required = true)
    })
    public Result<?> delete(@PathVariable Integer id) {
        DeviceMerchantBuy deviceMerchantBuy = new DeviceMerchantBuy();
        deviceMerchantBuy.setId(id);
        deviceMerchantBuyService.deleteDeviceMerchantBuy(deviceMerchantBuy);
        return ResultGenerator.genSuccessResult();
    }

    @PutMapping
    @ApiOperation(value = "更新数据", notes = "根据内容更新数据", httpMethod = "PUT")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "DeviceMerchantBuy", value = "更新的DeviceMerchantBuy实例", paramType = "body", dataType = "DeviceMerchantBuy", required = true)
    })
    public Result<?> update(@RequestBody DeviceMerchantBuy deviceMerchantBuy) {
        deviceMerchantBuyService.updateDeviceMerchantBuy(deviceMerchantBuy);
        return ResultGenerator.genSuccessResult();
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "获取单个值", notes = "查看单个项目的内容", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "查询的id", paramType = "path", required = true, dataType = "Integer", defaultValue = "0")
    })
    public Result<?> detail(@PathVariable Long id) {
        DeviceMerchantBuy deviceMerchantBuy = new DeviceMerchantBuy();
        deviceMerchantBuy.setId(id.intValue());
        deviceMerchantBuy = deviceMerchantBuyService.queryDeviceMerchantBuy(deviceMerchantBuy);
        return ResultGenerator.genSuccessResult(deviceMerchantBuy);
    }

    @PostMapping("/buyDevice")
    @ApiOperation(value = "购买设备生成订单", notes = "购买设备生成订单", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deviceMerchantBuyDTO", value = "订单信息", paramType = "DeviceMerchantBuyDTO", required = true, dataType = "DeviceMerchantBuyDTO")
    })
    public Result<?> buyDevice(@RequestBody DeviceMerchantBuyDTO deviceMerchantBuyDTO) {
        String orderNo = StringUtil.genRandomNum(3) + StringUtil.getBillno() + StringUtil.genRandomNum(3);
        Map<String, String> map = deviceMerchantBuyDTO.convert(orderNo);
        if ("aliPay".equals(deviceMerchantBuyDTO.getPayCode())) {
            return aliService.appPayParam(map, deviceMerchantBuyDTO);
        } else if ("wechatPay".equals(deviceMerchantBuyDTO.getPayCode())) {
            return wechatService.appPayParam(request, map, deviceMerchantBuyDTO);
        } else {
            return ResultGenerator.genFailResult("请选择正确的支付方式");
        }
    }

    @PostMapping("/v2/buyDevice")
    @ApiOperation(value = "购买设备生成订单", notes = "购买设备生成订单", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deviceMerchantBuyDTO", value = "订单信息", paramType = "DeviceMerchantBuyDTO", required = true, dataType = "DeviceMerchantBuyDTO")
    })
    public Result<?> buyDeviceV2(@RequestBody DeviceMerchantBuyDTO deviceMerchantBuyDTO) {
        if (deviceMerchantBuyDTO.getCode() == null) {
            throw new MsgException("缺少设备code");
        }

        if (Objects.equals(deviceMerchantBuyDTO.getQuantity(), 0)) {
            throw new MsgException("数量不能为0");
        }

        UserApp userApp = userAppService.queryUserAppByToken();
        if (deviceMerchantBuyDTO.getCode().startsWith("MP_NEW")) {
            if (StringUtils.isEmpty(userApp.getMerchantCode())) {
                throw new MsgException("非商户不允许购买新商户礼包");
            } else {
                MerchantChannelStatus mcs = mcsService.getValidData(userApp.getMerchantCode());
                if (!MerchantChannelStatus.isAudited(mcs)) {
                    throw new MsgException("非商户不允许购买新商户礼包");
                }

                if (!Objects.equals(deviceMerchantBuyDTO.getQuantity(), 1)) {
                    throw new MsgException("新商户礼包只能下单一个");
                }

                QueryWrapper<DeviceOrderInfo> qWrapper = new QueryWrapper<DeviceOrderInfo>()
                        .eq("userId", userApp.getUserId())
                        .eq("code", "MP_NEW");
                List<DeviceOrderInfo> data = doiService.list(qWrapper);
                for (DeviceOrderInfo datum : data) {
                    QueryWrapper<DeviceMerchantBuy> qWrapper2 = new QueryWrapper<>();
                    qWrapper2.eq("orderNo", datum.getOrderNo());
                    DeviceMerchantBuy one = dmbService.getOne(qWrapper2);
                    if (one != null && "1".equals(one.getStatus())) {
                        throw new MsgException("新商户礼包只能下单一次");
                    }
                }


            }
        }

        // List<DeviceDetailVO> deviceDetailsList = deviceDetailService.listByCode(Collections.singletonList(deviceMerchantBuyDTO.getCode()));
        // DeviceDetailVO devDetail = deviceDetailsList.get(0);
        // Long leftStock = devDetail.getTotalCount() - devDetail.getTotalSold();
        // BigDecimal leftGroup = leftStock.divideToIntegralValue(new BigDecimal(devDetail.get("groupSize").toString()));
//        if (leftGroup.compareTo(BigDecimal.ZERO) < 0) {
//            throw new MsgException("暂无库存");
//        }

        String orderNo = StringUtil.genRandomNum(3) + StringUtil.getBillno() + StringUtil.genRandomNum(3);
        Map<String, String> map = deviceMerchantBuyDTO.convert(orderNo);
        if ("aliPay".equals(deviceMerchantBuyDTO.getPayCode())) {
            return aliService.appPayParamV2(map, deviceMerchantBuyDTO);
        } else if ("wechatPay".equals(deviceMerchantBuyDTO.getPayCode())) {
            return wechatService.appPayParamV2(request, map, deviceMerchantBuyDTO);
        } else {
            return ResultGenerator.genFailResult("请选择正确的支付方式");
        }
    }

    @PostMapping("/deviceRefund")
    @ApiOperation(value = "设备订单退款", notes = "设备订单退款", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderNo", value = "订单号", paramType = "query", dataType = "orderNo"),
    })
    public Result<?> deviceRefund(String orderNo) {
        DeviceMerchantBuy deviceMerchantBuy = new DeviceMerchantBuy();
        deviceMerchantBuy.setOrderNo(orderNo);
        deviceMerchantBuy = deviceMerchantBuyService.queryDeviceMerchantBuy(deviceMerchantBuy);
        String payCode = deviceMerchantBuy.getPayCode();
        if ("aliPay".equals(payCode)) {//支付宝
            return aliService.appRefund(deviceMerchantBuy);
        } else if ("wechatPay".equals(payCode)) {//微信
            return wechatService.appRefund(deviceMerchantBuy);
        }
        return ResultGenerator.genFailResult("退款失败");
    }


    @GetMapping("/deviceOrderShow")
    @ApiOperation(value = "订单信息回显", notes = "订单信息回显", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "查询页码", paramType = "query", dataType = "Integer", defaultValue = "1"),
            @ApiImplicitParam(name = "size", value = "每页数据量", paramType = "query", dataType = "Integer", defaultValue = "10")
    })
    public Result<?> deviceOrderShow(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer size) {
        try {
            UserApp userApp = userAppService.queryUserAppByToken();
            Map<String, Object> map = new HashMap<String, Object>(16);
            map.put("userId", userApp.getUserId());
            map.put("pageSize", size);
            map.put("offset", (page - 1) * size);
            map.put("status", "1");
            List<DeviceMerchantBuyVO> deviceOrderShowPage = deviceMerchantBuyService.deviceOrderShowPage(map);
            Integer count = deviceMerchantBuyService.deviceOrderShowPageCount(map);
            PageInfo pageInfo = new PageInfo<>(count.longValue(), (long) StringUtil.getPageCount(count, size), page.longValue(), size.longValue(), deviceOrderShowPage);
            return ResultGenerator.genSuccessResult(pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultGenerator.genFailResult("系统繁忙，请稍后再试");
        }
    }

}

