package com.ruoyi.database.controller;

import cn.hutool.core.util.ReUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUserByPhone;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.database.domain.*;
import com.ruoyi.database.mapper.ParkingBillInfoMapper;
import com.ruoyi.database.service.CustomerPlateNoInfoService;
import com.ruoyi.database.service.ParkingBillInfoService;
import com.ruoyi.database.service.ParkingBillPaymentInfoService;
import com.ruoyi.database.util.HaiKangApiUtils;
import com.ruoyi.database.util.LicensePlateValidator;
import com.ruoyi.framework.web.service.TokenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Api(tags = "小程序接口")
@RestController
@RequiredArgsConstructor
@RequestMapping("/SmallProgram")
public class SmallProgramController extends BaseController {

    private final ParkingBillInfoService parkingBillInfoService;
    private final ParkingBillPaymentInfoService parkingBillPaymentInfoService;
    private final CustomerPlateNoInfoService customerPlateNoInfoService;
    private final TokenService tokenService;
    private final HaiKangApiUtils haiKangApiUtils;
    private final ObjectMapper objectMapper = new ObjectMapper();



    @GetMapping("/getOrder")
    @ApiOperation("根据车牌号查询缴费订单")
    public AjaxResult getOrder(String plateNo) {
        String parkingPaymentInfo = haiKangApiUtils.getParkingPaymentInfo(plateNo);
        if(parkingPaymentInfo==null){
            return AjaxResult.error("未查询到停车信息");
        }
        JSONObject jsonObject = new JSONObject(parkingPaymentInfo);
        String data = jsonObject.getJSONObject("data").toString();
        if(data==null){
            return AjaxResult.error("未查询到停车信息");
        }
        try {
            ParkingBill vehicleRecord = objectMapper.readValue(data, ParkingBill.class);
            ParkingBillInfo parkingBillInfo = new ParkingBillInfo();
            BeanUtils.copyProperties(vehicleRecord,parkingBillInfo);
            parkingBillInfo.setPayMoneyYuan(vehicleRecord.getPayMoneyYuan());
            parkingBillInfo.setDeductMoneyYuan(vehicleRecord.getDeductMoneyYuan());
            parkingBillInfo.setTotalCostYuan(vehicleRecord.getTotalCostYuan());
            LambdaUpdateWrapper<ParkingBillInfo> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(ParkingBillInfo::getBillCode,parkingBillInfo.getBillCode());
            parkingBillInfoService.saveOrUpdate(parkingBillInfo,updateWrapper);
            return AjaxResult.success(parkingBillInfo);
        } catch (JsonProcessingException e) {
            return AjaxResult.error("未查询到停车信息");
        }
    }



    @GetMapping("/getHistoryPlateNo")
    @ApiOperation("历史缴费车牌列表")
    public AjaxResult getHistoryOrder(HttpServletRequest request){
        LoginUserByPhone loginUserByPhone = tokenService.getLoginUserByPhone(request);
        String phone = loginUserByPhone.getPhone();
        List<ParkingBillPaymentInfo> list = parkingBillPaymentInfoService.lambdaQuery()
                .eq(ParkingBillPaymentInfo::getPhone, phone)
                .eq(ParkingBillPaymentInfo::getPayStatus, 1)
                .list();
        Map<String, List<ParkingBillPaymentInfo>> groupedByPlateNo = list.stream()
                .collect(Collectors.groupingBy(
                        ParkingBillPaymentInfo::getPlateNo,  // 按车牌分组
                        Collectors.toList()                   // 收集为List
                ));
        ArrayList<Map<String, String>> maps = new ArrayList<>();
        for (String plateNo : groupedByPlateNo.keySet()) {
            List<ParkingBillPaymentInfo> list1 = groupedByPlateNo.get(plateNo);
            ParkingBillPaymentInfo parkingBillPaymentInfo = list1.get(0);
            Map<String, String> map = new HashMap<>();
            map.put("plateNo", plateNo);
            map.put("plateColor",parkingBillPaymentInfo.getPlateColorCn());
            maps.add(map);
        }
        return AjaxResult.success(maps);
    }



    @GetMapping("/getHistoryNoPayOrder")
    @ApiOperation("查询历史未缴费订单")
    public AjaxResult getHistoryNoPayOrder(HttpServletRequest request){
        LoginUserByPhone loginUserByPhone = tokenService.getLoginUserByPhone(request);

        return AjaxResult.success();
    }




    @GetMapping("/getBindTheVehicle")
    @ApiOperation("查询已绑定车辆")
    public AjaxResult getBindTheVehicle(HttpServletRequest request){
        LoginUserByPhone loginUserByPhone = tokenService.getLoginUserByPhone(request);
        List<CustomerPlateNoInfo> list = customerPlateNoInfoService.lambdaQuery()
                .eq(CustomerPlateNoInfo::getPhone, loginUserByPhone.getPhone())
                .list();
        return AjaxResult.success(list);
    }



    @PostMapping("/bindTheVehicle")
    @ApiOperation("绑定车辆")
    public AjaxResult bindTheVehicle(@RequestBody BindTheVehicle bindTheVehicle,HttpServletRequest request){
        LoginUserByPhone loginUserByPhone = tokenService.getLoginUserByPhone(request);
        String plateNo = bindTheVehicle.getPlateNo();
        if (plateNo == null || "".equals(plateNo)) {
            return AjaxResult.error("绑定的车牌不能为空");
        }else{
            boolean valid = LicensePlateValidator.isValid(plateNo);
            if (!valid) {
                return AjaxResult.error("绑定的车牌格式不正确");
            }
        }
        List<CustomerPlateNoInfo> list = customerPlateNoInfoService.lambdaQuery()
                .eq(CustomerPlateNoInfo::getPlateNo, plateNo)
                .list();
        if (list != null && list.size() > 0) {
            return AjaxResult.error("车牌已被绑定");
        }
        CustomerPlateNoInfo customerPlateNoInfo = new CustomerPlateNoInfo();
        customerPlateNoInfo.setPlateNo(plateNo);
        customerPlateNoInfo.setPlateType(bindTheVehicle.getPlateType());
        customerPlateNoInfo.setPhone(loginUserByPhone.getPhone());
        return toAjax(customerPlateNoInfoService.saveOrUpdate(customerPlateNoInfo));
    }



    @PostMapping("/payFees")
    @ApiOperation("缴费")
    public AjaxResult payFees(@RequestBody PayFees payFees,HttpServletRequest request){
        LoginUserByPhone loginUserByPhone = tokenService.getLoginUserByPhone(request);
        return AjaxResult.success();
    }

}
