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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
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.admin.storegoodsinventory.vo.GoodsInfoReqVO;
import cn.iocoder.yudao.module.member.controller.app.orderdetail.vo.AppOrderDetailSaveReqVO;
import cn.iocoder.yudao.module.member.controller.app.orderdetail.vo.OtherVO;
import cn.iocoder.yudao.module.member.dal.dataobject.diningplates.DiningPlatesDO;
import cn.iocoder.yudao.module.member.dal.dataobject.orderdetail.OrderDetailDO;
import cn.iocoder.yudao.module.member.dal.dataobject.storegoods.StoreGoodsDO;
import cn.iocoder.yudao.module.member.dal.dataobject.storegoodsinventoryrecord.StoreGoodsInventoryRecordDO;
import cn.iocoder.yudao.module.member.dal.mysql.diningplates.DiningPlatesMapper;
import cn.iocoder.yudao.module.member.dal.mysql.orderdetail.OrderDetailMapper;
import cn.iocoder.yudao.module.member.dal.mysql.storegoodsinventoryrecord.StoreGoodsInventoryRecordMapper;
import cn.iocoder.yudao.module.member.service.orderdetaillog.OrderDetailLogService;
import cn.iocoder.yudao.module.member.service.storegoods.StoreGoodsService;
import cn.iocoder.yudao.module.system.api.dishesnutrition.DishesNutritionApi;
import cn.iocoder.yudao.module.system.api.dishesnutrition.dto.DishesNutritionRespDTO;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zt
 * @description <description class purpose>
 * @since 2024/10/10
 */
@Service
@Slf4j
public class MemberAsyncServiceImpl implements MemberAsyncService{

    @Resource
    private DiningPlatesMapper diningPlatesMapper;

    @Resource
    private DishesNutritionApi dishesNutritionApi;

    @Resource
    private OrderDetailMapper orderDetailMapper;

    @Resource
    private StoreGoodsService storeGoodsService;

    @Resource
    private OrderDetailLogService detailLogService;


    @Resource
    private StoreGoodsInventoryRecordMapper storeGoodsInventoryRecordMapper;

    @Async
    @Override
    public void flashTime(DiningPlatesDO diningPlatesDO){
        diningPlatesDO.setBindingTime(LocalDateTime.now());
        diningPlatesMapper.updateById(diningPlatesDO);
    }


    @Async
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createOrderDetail(AppOrderDetailSaveReqVO createReqVO, OtherVO otherVO) {
        DishesNutritionRespDTO dishEnergy = dishesNutritionApi.getDishEnergy(createReqVO.getDishesId());

        // 插入数据
        OrderDetailDO orderDetail = BeanUtils.toBean(createReqVO, OrderDetailDO.class);

        //计算热量
        if (dishEnergy != null && StrUtil.isNotEmpty(dishEnergy.getDishesNumber())) {
            BigDecimal dishesNumber = new BigDecimal(dishEnergy.getDishesNumber());
            BigDecimal nutritionNumber = new BigDecimal(dishEnergy.getNutritionNumber());
            if (BigDecimal.ZERO.compareTo(dishesNumber) != 0) {
                BigDecimal bigDecimal = createReqVO.getWeight().multiply(nutritionNumber).divide(dishesNumber.multiply(new BigDecimal("4.184")), 2, RoundingMode.HALF_UP);
                orderDetail.setHeat(bigDecimal.doubleValue());
            }
        }
        orderDetail.setOrderId(otherVO.getOrderId()).setDishesName(otherVO.getDishesName()).setDishUrl(otherVO.getDishesImageUrl());
        orderDetail.setSn(otherVO.getSn());
        orderDetail.setPrice(otherVO.getPrice());
        orderDetail.setUnitPrice(otherVO.getUnitPrice());
        orderDetailMapper.insert(orderDetail);
    }

    @Async
    @Override
    public void batchRecord(AddReqVO addReqVO) {
        List<StoreGoodsInventoryRecordDO> addList = new ArrayList<>();
        List<GoodsInfoReqVO> list = addReqVO.getList();
        List<Integer> goodsIds = list.stream().map(GoodsInfoReqVO::getGoodsId).collect(Collectors.toList());
        Map<Integer, StoreGoodsDO> map = storeGoodsService.getPrice(goodsIds);
        for (GoodsInfoReqVO vo :list){
            StoreGoodsInventoryRecordDO add = new StoreGoodsInventoryRecordDO();
            BeanUtil.copyProperties(vo,add);
            add.setType(addReqVO.getType());
            add.setOutType(addReqVO.getOutType());
            add.setPrice(map.get(vo.getGoodsId()).getPrice());
            add.setGoodsName(map.get(vo.getGoodsId()).getGoodsName());
            addList.add(add);
        }
        storeGoodsInventoryRecordMapper.insertBatch(addList);
    }

    @Async
    @Override
    public void saveFace(String faceData, String path) {
        if (StringUtil.isNotBlank(faceData)){
            try {
                // 解码 Base64 字符串
                // 过滤非法字符
                String s = faceData.replaceAll("\n", "");
                byte[] decodedBytes = Base64.getDecoder().decode(s);

                // 指定保存文件的路径// 根据实际情况修改文件路径和文件名
                String uploadDirPath= "orderFaceData/";

                // 创建上传文件目录
                File uploadDir = new File(uploadDirPath);
                if (!uploadDir.exists()) {
                    uploadDir.mkdir();
                }
                // 创建文件输出流
                try (FileOutputStream fos = new FileOutputStream(path)) {
                    // 将解码后的数据写入文件
                    fos.write(decodedBytes);
                    System.out.println("文件保存成功！");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

//    @Async
//    @Override
//    public void saveOrderDetailLog(AppOrderDetailSaveReqVO vo) {
//        detailLogService.insertOne(logDO);
//    }

    public void discard(){
        //DishesNutritionRespDTO dishEnergy = dishesNutritionApi.getDishEnergy(createReqVO.getDishesId());
        //
        //// 插入数据
        //OrderDetailDO orderDetail = BeanUtils.toBean(createReqVO, OrderDetailDO.class);
        //
        ////计算热量
        //if (dishEnergy != null && StrUtil.isNotEmpty(dishEnergy.getDishesNumber())) {
        //    BigDecimal dishesNumber = new BigDecimal(dishEnergy.getDishesNumber());
        //    BigDecimal nutritionNumber = new BigDecimal(dishEnergy.getNutritionNumber());
        //    if (BigDecimal.ZERO.compareTo(dishesNumber) != 0) {
        //        BigDecimal bigDecimal = createReqVO.getWeight().multiply(nutritionNumber).divide(dishesNumber.multiply(new BigDecimal("4.184")), 2, RoundingMode.HALF_UP);
        //        orderDetail.setHeat(bigDecimal.doubleValue());
        //    }
        //}
        //
        //orderDetail.setOrderId(diningPlatesDO.getOrderId()).setDishesName(dish.getDishesName()).setDishUrl(dish.getDishesImageUrl());
        //orderDetail.setSn(this.getHearder());
        //orderDetail.setPrice(bigDecimal1);
        //orderDetailMapper.insert(orderDetail);
    }
}
