package cn.iocoder.yudao.module.member.service.wxstoreorder;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.iocoder.yudao.module.member.controller.app.wxstoreorder.vo.WxStoreOrderDetailVO;
import cn.iocoder.yudao.module.member.controller.app.wxstoreorder.vo.WxStoreOrderVO;
import cn.iocoder.yudao.module.member.dal.dataobject.wxstoreorderdetail.WxStoreOrderDetailDO;
import cn.iocoder.yudao.module.member.dal.mysql.wxstoreorderdetail.WxStoreOrderDetailMapper;
import cn.iocoder.yudao.module.pay.api.order.PayOrderApi;
import cn.iocoder.yudao.module.pay.api.order.dto.PayCodesUnifiedDto;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.*;
import cn.iocoder.yudao.module.member.controller.admin.wxstoreorder.vo.*;
import cn.iocoder.yudao.module.member.dal.dataobject.wxstoreorder.WxStoreOrderDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.member.dal.mysql.wxstoreorder.WxStoreOrderMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.member.enums.ErrorCodeConstants.*;

/**
 * 微信付款码订单 Service 实现类
 *
 * @author 我是秦俊旗
 */
@Service
@Validated
public class WxStoreOrderServiceImpl implements WxStoreOrderService {

    @Resource
    private WxStoreOrderMapper wxStoreOrderMapper;
    @Resource
    private PayOrderApi orderApi;
    @Resource
    private WxStoreOrderDetailMapper wxStoreOrderDetailMapper;


    @Override
    public Long createWxStoreOrder(WxStoreOrderSaveReqVO createReqVO) {
        // 插入
        WxStoreOrderDO wxStoreOrder = BeanUtils.toBean(createReqVO, WxStoreOrderDO.class);
        wxStoreOrderMapper.insert(wxStoreOrder);
        // 返回
        return wxStoreOrder.getId();
    }

    @Override
    public void updateWxStoreOrder(WxStoreOrderSaveReqVO updateReqVO) {
        // 校验存在
        validateWxStoreOrderExists(updateReqVO.getId());
        // 更新
        WxStoreOrderDO updateObj = BeanUtils.toBean(updateReqVO, WxStoreOrderDO.class);
        wxStoreOrderMapper.updateById(updateObj);
    }

    @Override
    public void deleteWxStoreOrder(Long id) {
        // 校验存在
        validateWxStoreOrderExists(id);
        // 删除
        wxStoreOrderMapper.deleteById(id);
    }

    private void validateWxStoreOrderExists(Long id) {
        if (wxStoreOrderMapper.selectById(id) == null) {
            throw exception(WX_STORE_ORDER_NOT_EXISTS);
        }
    }

    @Override
    public WxStoreOrderDO getWxStoreOrder(Long id) {
        return wxStoreOrderMapper.selectById(id);
    }

    @Override
    public PageResult<WxStoreOrderDO> getWxStoreOrderPage(WxStoreOrderPageReqVO pageReqVO) {
        return wxStoreOrderMapper.selectPage(pageReqVO);
    }

    @Override
    public Boolean wxPay(WxStoreOrderVO vo) {
        String outTradeNo = IdUtil.getSnowflakeNextIdStr();

        double totalPrice = 0.0;
        for(WxStoreOrderDetailVO detailVO : vo.getGoodsList()) {
            totalPrice+=detailVO.getCustomPrice()*detailVO.getNumber();
        }

        PayCodesUnifiedDto payCodesUnifiedDto = new PayCodesUnifiedDto();
        payCodesUnifiedDto.setAuthCode(vo.getAuthCode());
        payCodesUnifiedDto.setBody(null);
        payCodesUnifiedDto.setSubject(vo.getCarteenName()+"-超市");
        payCodesUnifiedDto.setPrice((int)(totalPrice*100));
        payCodesUnifiedDto.setOutTradeNo(outTradeNo);
        // 获取本地机器的 InetAddress 对象
        InetAddress inetAddress = null;
        try {
            inetAddress = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        }

        // 获取本地机器的 IP 地址
        String ipAddress = inetAddress.getHostAddress();
        payCodesUnifiedDto.setUserIp(ipAddress);
        boolean b = orderApi.codePay(payCodesUnifiedDto);
        if(b){
            WxStoreOrderDO wxStoreOrderDO = new WxStoreOrderDO();
            wxStoreOrderDO.setOutTradeNo(outTradeNo);
            wxStoreOrderDO.setTotalPrice(totalPrice);
            wxStoreOrderDO.setAuthCode(vo.getAuthCode());
            wxStoreOrderDO.setCarteenId(vo.getCarteenId());
            wxStoreOrderDO.setStatus("SUCCESS");
            wxStoreOrderMapper.insert(wxStoreOrderDO);
            ArrayList<WxStoreOrderDetailDO> wxStoreOrderDetailDOS = new ArrayList<>();
            for (WxStoreOrderDetailVO detailVO : vo.getGoodsList()) {
                WxStoreOrderDetailDO detailDO= new WxStoreOrderDetailDO();
                BeanUtil.copyProperties(detailVO,detailDO);
                detailDO.setWxOrderId(wxStoreOrderDO.getId());
                wxStoreOrderDetailDOS.add(detailDO);
            }
            if(CollectionUtil.isNotEmpty(wxStoreOrderDetailDOS)){
                wxStoreOrderDetailMapper.insertBatch(wxStoreOrderDetailDOS);
            }
        }
        return b;
    }
}