package cn.iocoder.yudao.module.system.service.restaurant;

import cn.hutool.core.collection.CollectionUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
import cn.iocoder.yudao.module.system.controller.admin.restaurant.vo.CateringPlanPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.restaurant.vo.CateringPlanRespVO;
import cn.iocoder.yudao.module.system.controller.admin.restaurant.vo.CateringPlanSaveReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.restaurant.CateringPlanDO;
import cn.iocoder.yudao.module.system.dal.dataobject.restaurant.CateringPlanItemDO;
import cn.iocoder.yudao.module.system.dal.dataobject.restaurant.DishesDO;
import cn.iocoder.yudao.module.system.dal.mysql.restaurant.CateringPlanItemMapper;
import cn.iocoder.yudao.module.system.dal.mysql.restaurant.CateringPlanMapper;
import cn.iocoder.yudao.module.system.dal.mysql.restaurant.DishesMapper;
import cn.iocoder.yudao.module.system.util.http.HttpClientUtil;
import cn.iocoder.yudao.module.system.util.http.HttpClientResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;

import java.util.Date;
import java.util.List;

/**
 * 餐谱计划 Service 实现类
 *
 * @author 系统管理员
 */
@Slf4j
@Service
@Validated
public class CateringPlanServiceImpl implements CateringPlanService {
    @Resource
    private DishesMapper dishesMapper;
    @Resource
    private CateringPlanMapper cateringPlanMapper;
    @Resource
    private CateringPlanItemMapper cateringPlanItemMapper;


    @Override
    public Long createCateringPlan(CateringPlanSaveReqVO createReqVO) {
        if (createReqVO.getId() != null) {
            createReqVO.setId(null);
        }
        CateringPlanDO cateringPlan = new CateringPlanDO();
        BeanUtils.copyProperties(createReqVO, cateringPlan);
        cateringPlan.setCreatedTime(new Date());
        cateringPlan.setCreatedBy(SecurityFrameworkUtils.getLoginUserNickname());
        cateringPlanMapper.insert(cateringPlan);

        List<CateringPlanItemDO> items = createReqVO.getItems();
        for (CateringPlanItemDO item : items) {
            item.setCateringPlanId(cateringPlan.getId());
            cateringPlanItemMapper.insert(item);
        }
        invokeWechatInterface(createReqVO.getRestaurantId(),createReqVO.getRestaurantName());
        return cateringPlan.getId();
    }

    @Override
    public PageResult<CateringPlanDO> getCateringPlanPage(CateringPlanPageReqVO pageReqVO) {
        return cateringPlanMapper.selectPage(pageReqVO);
    }

    @Override
    public void updateCateringPlan(CateringPlanSaveReqVO updateReqVO) {
        CateringPlanDO cateringPlan = cateringPlanMapper.selectById(updateReqVO.getId());
        BeanUtils.copyProperties(updateReqVO, cateringPlan);
        cateringPlanMapper.updateById(cateringPlan);
        //先删除在创建
        cateringPlanItemMapper.delete(new LambdaQueryWrapperX<CateringPlanItemDO>()
                .eq(CateringPlanItemDO::getCateringPlanId, updateReqVO.getId()));

        List<CateringPlanItemDO> items = updateReqVO.getItems();
        for (CateringPlanItemDO item : items) {
            item.setCateringPlanId(cateringPlan.getId());
            cateringPlanItemMapper.insert(item);
        }
        invokeWechatInterface(updateReqVO.getRestaurantId(),updateReqVO.getRestaurantName());
    }

    @Override
    public CateringPlanRespVO getCateringPlan(Long id) {
        CateringPlanDO cateringPlan = cateringPlanMapper.selectById(id);

        List<CateringPlanItemDO> cateringPlanItems = cateringPlanItemMapper
                .selectList(new LambdaQueryWrapperX<CateringPlanItemDO>()
                        .eq(CateringPlanItemDO::getCateringPlanId, cateringPlan.getId()));

        CateringPlanRespVO respVO = new CateringPlanRespVO();
        BeanUtils.copyProperties(cateringPlan, respVO);
        respVO.setItems(cateringPlanItems);
        return respVO;
    }

    @Override
    public void deleteCateringPlan(Long[] ids) {
        for (Long id : ids) {
            cateringPlanMapper.deleteById(id);
        }
    }

    @Override
    public List<CateringPlanItemDO> exportCateringPlanItemExcel(Long id) {
        CateringPlanDO cateringPlan = cateringPlanMapper.selectById(id);
        return cateringPlanItemMapper.selectList(new LambdaQueryWrapperX<CateringPlanItemDO>()
                .eq(CateringPlanItemDO::getCateringPlanId, cateringPlan.getId()));
    }

    @Override
    public CateringPlanRespVO exportCateringPlanItemExcelDate(Long id) {
        CateringPlanRespVO respVO = new CateringPlanRespVO();
        CateringPlanDO cateringPlan = cateringPlanMapper.selectById(id);
        BeanUtils.copyProperties(cateringPlan, respVO);
        List<CateringPlanItemDO> cateringPlanItems = cateringPlanItemMapper
                .selectList(new LambdaQueryWrapperX<CateringPlanItemDO>()
                        .eq(CateringPlanItemDO::getCateringPlanId, cateringPlan.getId()));

        for (CateringPlanItemDO cateringPlanItem : cateringPlanItems) {
            String monday = cateringPlanItem.getMonday();
            List<String> mondayList = JSONArray.parseArray(monday, String.class);
            if (CollectionUtil.isNotEmpty(mondayList)) {
                for (int i = 0; i < mondayList.size(); i++) {
                    DishesDO dishesDO = dishesMapper.selectOne(new LambdaQueryWrapperX<DishesDO>().eq(DishesDO::getFoodName, mondayList.get(i)));
                    mondayList.set(i,mondayList.get(i) + "-" + dishesDO.getPrice().setScale(2) + "元");
                }
            }

            List<String> tuesdayList = JSONArray.parseArray(cateringPlanItem.getTuesday(), String.class);
            if (CollectionUtil.isNotEmpty(tuesdayList)) {
                for (int i = 0; i < tuesdayList.size(); i++) {
                    DishesDO dishesDO = dishesMapper.selectOne(new LambdaQueryWrapperX<DishesDO>().eq(DishesDO::getFoodName, tuesdayList.get(i)));
                    tuesdayList.set(i,tuesdayList.get(i) + "-" + dishesDO.getPrice().setScale(2) + "元");
                }
            }


            List<String> wednesdayList = JSONArray.parseArray(cateringPlanItem.getWednesday(), String.class);
            if (CollectionUtil.isNotEmpty(wednesdayList)) {
                for (int i = 0; i < wednesdayList.size(); i++) {
                    DishesDO dishesDO = dishesMapper.selectOne(new LambdaQueryWrapperX<DishesDO>().eq(DishesDO::getFoodName, wednesdayList.get(i)));
                    wednesdayList.set(i,wednesdayList.get(i) + "-" + dishesDO.getPrice().setScale(2) + "元");
                }
            }

            List<String> thursdayList = JSONArray.parseArray(cateringPlanItem.getThursday(), String.class);
            if (CollectionUtil.isNotEmpty(thursdayList)) {
                for (int i = 0; i < thursdayList.size(); i++) {
                    DishesDO dishesDO = dishesMapper.selectOne(new LambdaQueryWrapperX<DishesDO>().eq(DishesDO::getFoodName, thursdayList.get(i)));
                    thursdayList.set(i,thursdayList.get(i) + "-" + dishesDO.getPrice().setScale(2) + "元");
                }
            }

            List<String> fridayList = JSONArray.parseArray(cateringPlanItem.getFriday(), String.class);
            if (CollectionUtil.isNotEmpty(fridayList)) {
                for (int i = 0; i < fridayList.size(); i++) {
                    DishesDO dishesDO = dishesMapper.selectOne(new LambdaQueryWrapperX<DishesDO>().eq(DishesDO::getFoodName, fridayList.get(i)));
                    fridayList.set(i,fridayList.get(i) + "-" + dishesDO.getPrice().setScale(2) + "元");
                }
            }

            List<String> saturdayList = JSONArray.parseArray(cateringPlanItem.getSaturday(), String.class);
            if (CollectionUtil.isNotEmpty(saturdayList)) {
                for (int i = 0; i < saturdayList.size(); i++) {
                    DishesDO dishesDO = dishesMapper.selectOne(new LambdaQueryWrapperX<DishesDO>().eq(DishesDO::getFoodName, saturdayList.get(i)));
                    saturdayList.set(i,saturdayList.get(i) + "-" + dishesDO.getPrice().setScale(2) + "元");
                }
            }
            List<String> sundayList = JSONArray.parseArray(cateringPlanItem.getSunday(), String.class);
            if (CollectionUtil.isNotEmpty(sundayList)) {
                for (int i = 0; i < sundayList.size(); i++) {
                    DishesDO dishesDO = dishesMapper.selectOne(new LambdaQueryWrapperX<DishesDO>().eq(DishesDO::getFoodName, sundayList.get(i)));
                    sundayList.set(i,sundayList.get(i) + "-" + dishesDO.getPrice().setScale(2) + "元");
                }
            }
            cateringPlanItem.setMonday(String.join(",", mondayList));
            cateringPlanItem.setTuesday(String.join(",", tuesdayList));
            cateringPlanItem.setThursday(String.join(",", thursdayList));
            cateringPlanItem.setWednesday(String.join(",", wednesdayList));
            cateringPlanItem.setFriday(String.join(",", fridayList));
            cateringPlanItem.setSaturday(String.join(",", saturdayList));
            cateringPlanItem.setSunday(String.join(",", sundayList));
        }
        respVO.setItems(cateringPlanItems);
        return respVO;
    }

    private void invokeWechatInterface(Long restaurantId,String restaurantName){
        // 调用外部接口更新餐厅周菜单
        try {
            JSONObject requestJson = new JSONObject();
            requestJson.put("tenantId", TenantContextHolder.getTenantId());
            requestJson.put("restaurantId", restaurantId);
            requestJson.put("restaurantName", restaurantName);

            String url = "http://home.ynims.com:80/api/eldercare/event/updateRestaurantWeeklyMenu?tenantId=" + TenantContextHolder.getTenantId()
                    + "&restaurantId="+restaurantId+"&restaurantName="+restaurantName;
            String jsonParam = JSON.toJSONString(requestJson);

            HttpClientResult httpClientResult = HttpClientUtil.doPostJson(url, jsonParam, null);
            // 可以根据需要处理返回结果
            if (httpClientResult.getCode() != 200) {
                // 记录日志或处理错误
                log.error("调用更新餐厅周菜单接口失败，状态码：{}，返回内容：{}", httpClientResult.getCode(), httpClientResult.getContent());
            } else {
                log.info("调用更新餐厅周菜单接口成功，参数：{}", jsonParam);
            }
        } catch (Exception e) {
            // 记录异常日志，但不影响主流程
            log.error("调用更新餐厅周菜单接口异常：{}", e.getMessage(), e);
        }
    }
}