package com.bonus.sharedstation.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bonus.common.core.utils.StringUtils;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.sharedstation.app.domain.GreenUserInfo;
import com.bonus.sharedstation.app.dto.RepairServiceDTO;
import com.bonus.sharedstation.app.dto.RepairServiceOrderDTO;
import com.bonus.sharedstation.app.entity.RepairService;
import com.bonus.sharedstation.app.entity.RepairServiceOrder;
import com.bonus.sharedstation.app.mapper.RepairServiceMapper;
import com.bonus.sharedstation.app.mapper.RepairServiceOrderMapper;
import com.bonus.sharedstation.app.service.RepairServiceOrderService;
import com.bonus.sharedstation.common.utils.OrderNumberGeneratorUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 便民服务信息表保洁(CleaningServicesOrder)表服务实现类
 *
 * @author makejava
 * @since 2024-12-10 17:02:11
 */
@Service("repairServiceOrderService")
@Slf4j
public class RepairServiceOrderServiceImpl extends ServiceImpl<RepairServiceOrderMapper, RepairServiceOrder> implements RepairServiceOrderService {

    @Resource
    private RepairServiceOrderMapper dao;

    @Resource
    private BaseService baseService;

//    @Value("${niu.niupayurl}")
//    private String niupayurl;
//
//    @Value("${niu.niusearchuserurl}")
//    private String niusearchuserurl;
//
//    @Value("${niu.niupayreturnurl}")
//    private String niupayreturnurl;
//
//    @Value("${niu.applicationid}")
//    private String applicationid;
//
//    @Value("${niu.applicationidpsw}")
//    private String applicationidpsw;
//
//    @Value("${niu.sncode}")
//    private String sncode;
//
//    @Value("${niu.serialnum}")
//    private String serialnum;


    @Resource
    private RepairServiceMapper repairServiceMapper;

    @Override
    public AjaxResult getListPageApp(RepairServiceOrderDTO dto) {
        log.info("查询 入参: {}", dto);
        LambdaQueryWrapper<RepairServiceOrder> queryWrapper = new LambdaQueryWrapper<>();
        // 创建分页对象
        GreenUserInfo userInfo = baseService.getUserInfo(dto.getUserId());

        Page<RepairServiceOrder> page = new Page<>(dto.getCurrentPage(), dto.getLimit());
        if (userInfo != null) {
            queryWrapper.eq(RepairServiceOrder::getUserId, userInfo.getUserId());
        } else {
            throw new RuntimeException("请先登录!");
        }
        queryWrapper
                .eq(RepairServiceOrder::getIsDeleted, dto.getIsDeleted())
                .orderByDesc(RepairServiceOrder::getCreatedTime);     // 降序排序

        Page<RepairServiceOrder> result = dao.selectPage(page, queryWrapper);
        //处理参数问题
        return AjaxResult.success(result);
    }


    @Override
    public AjaxResult getListWeb(RepairServiceOrderDTO dto) {
        log.info("查询 入参: {}", dto);
        LambdaQueryWrapper<RepairServiceOrder> queryWrapper = new LambdaQueryWrapper<>();
        // 创建分页对象
        Page<RepairServiceOrder> page = new Page<>(dto.getCurrentPage(), dto.getLimit());
        queryWrapper
                .eq(RepairServiceOrder::getIsDeleted, dto.getIsDeleted())
                .orderByDesc(RepairServiceOrder::getCreatedTime);     // 降序排序

        Page<RepairServiceOrder> result = dao.selectPage(page, queryWrapper);
        //处理参数问题
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult selectInfoById(RepairServiceOrder dto) {
        RepairServiceOrder result = dao.selectById(dto.getId());
        if (StringUtils.isNull(result)) {
            return AjaxResult.error("此维修服务订单不存在");
        }
        //处理参数问题
        return AjaxResult.success(result);
    }

    /**
     * 分页查询
     *
     * @param dto
     * @return
     */
    @Override
    public AjaxResult getListPage(RepairServiceDTO dto) {
        log.info("查询 入参: {}", dto);
        LambdaQueryWrapper<RepairService> queryWrapper = new LambdaQueryWrapper<>();
        // 创建分页对象
        Page<RepairService> page = new Page<>(dto.getCurrentPage(), dto.getLimit());
        if (StringUtils.isNotEmpty(dto.getServiceName())) {
            queryWrapper.like(RepairService::getServiceName, dto.getServiceName());
        }
        queryWrapper
                .eq(RepairService::getIsDeleted, dto.getIsDeleted())
                .orderByDesc(RepairService::getCreatedTime);     // 降序排序

        Page<RepairService> result = repairServiceMapper.selectPage(page, queryWrapper);
        //处理参数问题
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult insertToPay(RepairServiceOrder dto) {
        log.info("新增入参 : " + dto);
        GreenUserInfo userInfo = baseService.getUserInfo(dto.getUserId());
        //三方扣款
        //流水号
        dto.setOrdno(OrderNumberGeneratorUtils.generateOrderNumber());
        //支付相关接入第三方小牛支付
//        return payByNiu(userInfo, dto);
        return null;
    }

//
//    /**
//     * 支付相关接入第三方小牛支付
//     *
//     * @param userInfo
//     * @param dto
//     * @return
//     */
//    private RestResult payByNiu(GreenUserInfo userInfo, RepairServiceOrder dto) {
//        //1 先查询人员对应的卡号
//        //应用秘钥
//        String appsecret = applicationidpsw;
//        //传参
//        HashMap<Object, Object> bodyMap = new HashMap<>(2);
//        if (StringUtils.isEmpty(userInfo.getMobile())) {
//            log.info("下单没有配置手机号,无法下单,请联系管理员配置");
//            return new RestResult(Constant.FAILED, "用户信息获取失败！");
//        }
//        //根据手机号查询
//        bodyMap.put("mobile", userInfo.getMobile());
////        bodyMap.put("mobile", "15996330508");
//        //请求内容字典排序，转换为String
//        String content = JSON.toJSONString(bodyMap, SerializerFeature.MapSortField, SerializerFeature.WriteMapNullValue);
//        log.info("请求内容转换为JSON字符串，字典排序：{}", content);
//        //构造请求验签参数方法
//        //加签 防止篡改
//        Map<String, Object> map = makeSign(content, appsecret, bodyMap);
//        HttpRequest request = HttpUtil.createPost(niusearchuserurl);
//        log.info("request=" + JSONUtil.toJsonStr(map));
//        request.body(JSONUtil.toJsonStr(map), ContentType.JSON.toString());
//        HttpResponse response = request.execute();
//        log.info("response={}", response.body());
//        //转成实体类
//        ObjectMapper objectMapper = new ObjectMapper();
//        try {
//            ApiResponse apiResponse = objectMapper.readValue(response.body(), ApiResponse.class);
//            ResponseDatad data = apiResponse.getData();
//            List<Customer> customerList = data.getCustomerList();
//            if (StringUtils.isEmpty(customerList)) {
//                log.info("没有找到对应餐卡,无法下单,请联系管理员配置");
//                return new RestResult(Constant.FAILED, "没有找到对应餐卡,无法下单,请联系管理员配置");
//            }
//            Customer customer = customerList.get(0);
//            //传参
//            HashMap<Object, Object> bodyMapForPayContent = new HashMap<>(2);
//            //构建 content
//            intoMapEnity(bodyMapForPayContent, dto, customer);
//            String payContent = JSON.toJSONString(bodyMapForPayContent, SerializerFeature.MapSortField, SerializerFeature.WriteMapNullValue);
//            log.info("content: " + payContent);
//            Map<String, Object> payBodyMap = makeSign(payContent, appsecret, bodyMapForPayContent);
//
//            HttpRequest requestForPay = HttpUtil.createPost(niupayurl);
//            log.info("request=" + JSONUtil.toJsonStr(payBodyMap));
//            System.err.println("请求参数---: " + JSONUtil.toJsonStr(payBodyMap));
//            requestForPay.body(JSONUtil.toJsonStr(payBodyMap), ContentType.JSON.toString());
//            HttpResponse responseForPay = requestForPay.execute();
//            log.info("responseForPay={}", responseForPay.body());
//            //转成实体类响应数据
//            ApiResponseForPay apiResponseForPay = objectMapper.readValue(responseForPay.body(), ApiResponseForPay.class);
//            if (apiResponseForPay == null) {
//                log.error("扣款食堂卡失败,请检查");
//                throw new RuntimeException("扣款食堂卡失败,请检查");
//            }
//            if (StringUtils.isNotNull(apiResponseForPay) && apiResponseForPay.getCode() == 10000) {
//                int result = dao.insert(dto);
//                if (result == 1) {
//                    return new RestResult(Constant.SUCCESS, "扣款成功," + "扣款金额为:" + apiResponseForPay.getData().getRealAmount() + "余额为:" + apiResponseForPay.getData().getWalletBal());
//                }
//            }
//            return new RestResult(Constant.FAILED, "小牛支付提示:" + apiResponseForPay.getMsg());
//
//        } catch (Exception e) {
//            log.error("下单失败");
//            e.printStackTrace();
//            return new RestResult(Constant.FAILED,"下单失败");
//        }
//    }
//
//    /**
//     * 加签 防止篡改
//     * @param content
//     * @param appsecret
//     * @param bodyMap
//     * @return
//     */
//    private Map<String, Object> makeSign(String content, String appsecret, HashMap<Object, Object> bodyMap) {
//        Map<String, Object> map = new TreeMap<>();
//        map.put("appid", applicationid);
//        map.put("version", "1.0.0");
//        map.put("signtype", "md5");
//        map.put("timestamp", String.valueOf(System.currentTimeMillis()));
//        map.put("nonce", RandomUtil.randomNumbers(10));
//        map.put("content", content);
//        //生成sign，防篡改
//        String toSignStr = Joiner.on("&")
//                .useForNull("")
//                .withKeyValueSeparator("=")
//                .join(map) + "&appsecret=" + appsecret;
//        log.info("所有参数字典排序，待加签String：{}", toSignStr);
//
//        // md5/sha256 加签（其他方式待提供）
//        String sign = DigestUtils.md5Hex(toSignStr).toUpperCase();
//        System.err.println("sign: " + sign);
//        log.info("加签String：{}", sign);
//        map.put("sign", sign);
//
//        //post请求
//        map.replace("content", bodyMap);
//        return map;
//    }
//
//    private void intoMapEnity(HashMap bodyMap, RepairServiceOrder dto, Customer customer) {
//        //金额
//        Double usePrice = dto.getUsePrice();
//        int convertedPrice = (int) (usePrice * 100);
//        bodyMap.put("amount", convertedPrice);
//        //人员 id
//        bodyMap.put("custId", Long.valueOf(customer.getCustId()));
//        //流水号
//        bodyMap.put("macOrdId", dto.getOrdno());
//        //sn码
//        bodyMap.put("machineSn", sncode);
//        //
//        bodyMap.put("nuClearMode", 2);
//
//        bodyMap.put("ordTime", DateUtils.formatDate(dto.getOrderTime()));
//
//        bodyMap.put("deliveryType", "2");
//        //
//    }

}

