package cn.iocoder.yudao.module.member.controller.app.store;

import cn.hutool.core.collection.CollectionUtil;
import cn.iocoder.yudao.framework.common.pojo.StoreResult;
import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.member.controller.admin.storegoodsinventory.vo.AddReqVO;
import cn.iocoder.yudao.module.member.controller.app.store.dto.*;
import cn.iocoder.yudao.module.member.controller.app.store.vo.*;
import cn.iocoder.yudao.module.member.dal.dataobject.storegoods.StoreGoodsDO;
import cn.iocoder.yudao.module.member.dal.dataobject.storegoodstype.StoreGoodsTypeDO;
import cn.iocoder.yudao.module.member.dal.dataobject.user.MemberUserDO;
import cn.iocoder.yudao.module.member.enums.StoreOrderStatusEnum;
import cn.iocoder.yudao.module.member.service.async.MemberAsyncService;
import cn.iocoder.yudao.module.member.service.storegoods.StoreGoodsService;
import cn.iocoder.yudao.module.member.service.storegoodsinventory.StoreGoodsInventoryService;
import cn.iocoder.yudao.module.member.service.storegoodstype.StoreGoodsTypeService;
import cn.iocoder.yudao.module.member.service.storeorder.StoreOrderService;
import cn.iocoder.yudao.module.member.service.storeorderdetail.StoreOrderDetailService;
import cn.iocoder.yudao.module.member.service.storesalegoods.StoreSaleGoodsService;
import cn.iocoder.yudao.module.member.service.user.MemberUserService;
import cn.iocoder.yudao.module.system.api.cashregisterinfo.CashregisterinfoApi;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Tag(name = "用户 APP - 超市")
@RestController
@RequestMapping("/device")
@Validated
@Slf4j
public class AppStoreController {

    @Resource
    private MemberUserService userService;
    @Resource
    private StoreGoodsService storeGoodsService;
    @Resource
    private StoreGoodsTypeService goodsTypeService;
    @Resource
    private StoreSaleGoodsService saleGoodsService;
    @Resource
    private StoreOrderService orderService;
    @Resource
    private StoreOrderDetailService orderDetailService;
    @Resource
    private MemberAsyncService memberAsyncService;
    @Resource
    private CashregisterinfoApi cashregisterinfoApi;
    @Resource
    private StoreGoodsInventoryService storeGoodsInventoryService;

    @GetMapping("/mgcr/memberUser/getMenberTwoList")
    @Operation(summary = "获取用户关联信息")
    @PermitAll
    public StoreResult<List<StoreUserVo>> getStoreUser(@RequestBody StoreUserDto dto) {
        List<MemberUserDO> list = userService.getStoreUser();
        return StoreResult.success(StoreUserVo.convert(list));
    }

    @GetMapping("/mgcr/equipment/goodsList")
    @Operation(summary = "获取菜品库所有菜品")
    public String getGoods(String equipmentCode, HttpServletRequest request) {

        String equipment = request.getHeader("Authorization");
        Long storeId = cashregisterinfoApi.getStoreId(equipment);
        List<StoreGoodsDO> goodsDOS = storeGoodsService.getByCarteenId(storeId);
        List<StoreGoodsTypeDO> goodsTypeDOS = goodsTypeService.getAllDevice();
        List<StoreGoodsListVo> goodData = BeanUtils.toBean(goodsDOS, StoreGoodsListVo.class);
        List<StoreGoodsTypeListVo> categoryData = BeanUtils.toBean(goodsTypeDOS, StoreGoodsTypeListVo.class);
        GoodsResult goodsResult = new GoodsResult();
        goodsResult.setStatusCode(200);
        goodsResult.setCategoryData(categoryData);
        goodsResult.setGoodsData(goodData);
        goodsResult.setSuccess(true);
        goodsResult.setMessage("操作成功");

        return JsonUtils.toJsonString(goodsResult);
    }

    @PostMapping("/mgcr/equipment/bindGoods")
    @Operation(summary = "设置营业菜品")
    public String bindGoods(@RequestBody StoreSaleGoodsDto dto) {
        Boolean b = saleGoodsService.bindGoods(dto);
        StoreResult<String> result = new StoreResult<>();

        if (b) {
            result.setStatusCode(200);
            result.setMessage("操作成功");
            result.setSuccess(true);
        }else{
            result.setStatusCode(300);
            result.setSuccess(false);
        }
        return JsonUtils.toJsonString(result);
    }

    @GetMapping("/mgcr/equipment/queryBindGoods")
    @Operation(summary = "获取营业菜品")
    public String getSaleGoods(String equipmentCode) {
        GoodsResult goodsResult = new GoodsResult();
        goodsResult.setStatusCode(200);
        goodsResult.setSuccess(true);
        goodsResult.setMessage("操作成功");

        Long storeId = cashregisterinfoApi.getStoreId(equipmentCode);
        List<Integer> goodsIds = saleGoodsService.getGoodsIds(storeId);
        if(CollectionUtil.isEmpty(goodsIds)){
            return JsonUtils.toJsonString(goodsResult);
        }
        List<StoreGoodsDO> goodsDOS = storeGoodsService.getAll(goodsIds);
        List<StoreGoodsTypeDO> goodsTypeDOS = goodsTypeService.getAllDevice();
        List<StoreGoodsListVo> goodData = BeanUtils.toBean(goodsDOS, StoreGoodsListVo.class);

        //库存处理
        Map<Integer, Integer> inventoryList = storeGoodsInventoryService.getInventoryList(goodsIds, storeId);
        for (StoreGoodsListVo listVo:goodData){
            listVo.setNumber(inventoryList.get(listVo.getGoodsId()));
        }

        List<StoreGoodsTypeListVo> categoryData = BeanUtils.toBean(goodsTypeDOS, StoreGoodsTypeListVo.class);
        goodsResult.setCategoryData(categoryData);
        goodsResult.setGoodsData(goodData);
        return JsonUtils.toJsonString(goodsResult);
    }


    @PostMapping("/mgcr/order/paymentCodePayOrder")
    @Operation(summary = "创建刷脸支付订单")
    public String paymentCodePayOrder(@RequestBody StoreOrderDto dto) {
        Integer order = orderService.createOrder(dto, StoreOrderStatusEnum.TO_PAY.getCode()).getOrderId();
        HashMap<String, Integer> map = new HashMap<>();
        map.put("orderId", order);
        return JsonUtils.toJsonString(StoreResult.success(map));
    }

    @PostMapping("/swipingFacePay")
    @Operation(summary = "提交刷脸支付")
    public String swipingFacePay(@RequestBody FacePayDto dto) {
        UserInfoVo userInfoVo = orderService.facePay(dto);
        if(userInfoVo.getBalance()>=0){
            return JsonUtils.toJsonString(StoreResult.success(userInfoVo));
        }else {
            return JsonUtils.toJsonString(StoreResult.fail("余额不足"));
        }
    }

    @PostMapping("/mgcr/order/payByCardOrder")
    @Operation(summary = "添加刷卡订单")
    public String payByCardOrder(@RequestBody StoreOrderDto dto) {
        String s1 = reverseHexAndConvert(dto.getCardNumber());
        System.out.println(s1);
        dto.setCardNumber(s1);
        String s = orderService.cardPay(dto);

        if("true".equals(s)){
            return JsonUtils.toJsonString(StoreResult.success(null));
        } else if ("false".equals(s)) {
            return JsonUtils.toJsonString(StoreResult.fail("余额不足"));
        }else {
            return JsonUtils.toJsonString(StoreResult.fail(s));
        }
    }

    @PostMapping("/mgcr/order/batchCacheOrder")
    @Operation(summary = "缓存订单批量上传")
    public String batchCacheOrder(@RequestBody StoreOrderUploadDto dto) {
        orderService.batchCacheOrder(dto);
        return JsonUtils.toJsonString(StoreResult.success(null));
    }

    @GetMapping("/mgcr/equipment/heartbeat")
    @Operation(summary = "心跳")
    public String heartbeat() {
        return JsonUtils.toJsonString(StoreResult.success(null));
    }



    @PostMapping("/mgcr/order/payByCodeOrder")
    @Operation(summary = "添加二维码订单")
    public String payByCodeOrder(@RequestBody StoreOrderDto dto) {
        AddReqVO addReqVO = orderService.codePay(dto);
        if(CollectionUtil.isNotEmpty(addReqVO.getList())){
            memberAsyncService.batchRecord(addReqVO);
        }
        return JsonUtils.toJsonString(StoreResult.success(null));

    }

    @GetMapping("/mgcr/discount")
    @Operation(summary = "获取门店折扣")
    public String getDiscount(String equipmentCode) {
        return JsonUtils.toJsonString(StoreResult.success(orderService.getDiscount(equipmentCode)));

    }

    public  String reverseHexAndConvert(String hexStr) {
        // 将十六进制字符串反转，每两位一组
        StringBuilder reversedHex = new StringBuilder();
        for (int i = 0; i < hexStr.length(); i += 2) {
            reversedHex.insert(0, hexStr.substring(i, i + 2));
        }

        // 将反转后的十六进制字符串转换为十进制
        long decimalNumber = Long.parseLong(reversedHex.toString(), 16);

        // 将十进制数转换为字符串，并确保它有10位，不足的前面补零
        String decimalStr = String.valueOf(decimalNumber);
        while (decimalStr.length() < 10) {
            decimalStr = "0" + decimalStr;
        }

        return decimalStr;
    }





}
