package com.sky.ioc.service.canteen.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sky.ioc.entity.Indeicator;
import com.sky.ioc.entity.Label;
import com.sky.ioc.entity.Cake;
import com.sky.ioc.entity.domain.canteen.Cuisine;
import com.sky.ioc.entity.domain.canteen.CuisineOrderItem;
import com.sky.ioc.entity.domain.canteen.FoodMenu;
import com.sky.ioc.entity.domain.canteen.Order;
import com.sky.ioc.entity.domain.security.SecurityDoorRecord;
import com.sky.ioc.entity.domain.system.Users;
import com.sky.ioc.entity.params.IocParam;
import com.sky.ioc.entity.params.IocTimeRange;
import com.sky.ioc.mapper.CuisineMapper;
import com.sky.ioc.mapper.CuisineOderItemMapper;
import com.sky.ioc.mapper.CuisineOrderMapper;
import com.sky.ioc.mapper.FoodMenusMapper;
import com.sky.ioc.mapper.job.TokenMapper;
import com.sky.ioc.mapper.security.SecurityDoorRecordMapper;
import com.sky.ioc.service.canteen.RestaurantService;
import com.sky.ioc.tool.DateUtil;
import com.sky.ioc.tool.FalseData;
import com.sky.ioc.tool.GeneralMethod;
import com.sky.ioc.tool.ReturnMsg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;


/**
 * @author LunCe
 */
@Service
@Slf4j
public class RestaurantServiceImpl implements RestaurantService {

    @Autowired
    CuisineOrderMapper cuisineOrderMapper;

    @Autowired
    FoodMenusMapper foodMenusMapper;

    @Autowired
    TokenMapper tokenMapper;

    @Value("${sky.dataIp}")
    private String dataIp;

    @Autowired
    CuisineMapper cuisineMapper;

    @Autowired
    CuisineOderItemMapper cuisineOderItemMapper;

    final static  String CANTEEN_ORDER_URL="%s/api/canteen/CANTEEN/order/list";
    /**
     * TODO  查询智慧生活中智慧餐厅的支付分析
     *
     * @Description
     * @Param dateType
     * @Return java.lang.String
     * @Author LunCe
     * @date 2023/2/10 11:25
     */
    @Override
    public ReturnMsg getPaymentAnalysis(IocParam iocParam) {
        List<Cake> lists = new ArrayList<>();
       // Double offline = cuisineOrderMapper.getTotalPriceByCompanyIdAndDeptId(iocParam,19);
        Double scanningCode =cuisineOrderMapper.getTotalPriceByCompanyIdAndDeptId(iocParam,13);
        Double payCard =cuisineOrderMapper.getTotalPriceByCompanyIdAndDeptId(iocParam,2);
        Double face = cuisineOrderMapper.getTotalPriceByCompanyIdAndDeptId(iocParam,1);
     //   offline = offline==null?0:offline;
        scanningCode = scanningCode==null?0:new BigDecimal(scanningCode).divide(new BigDecimal("100"),2,RoundingMode.HALF_UP).doubleValue();
        payCard = payCard==null?0:new BigDecimal(payCard).divide(new BigDecimal("100"),2,RoundingMode.HALF_UP).doubleValue();
        face = face==null?0:new BigDecimal(face).divide(new BigDecimal("100"),2,RoundingMode.HALF_UP).doubleValue();
       // Cake cake1 = new Cake();
        Cake cake2 = new Cake();
        Cake cake3 = new Cake();
        Cake cake4 = new Cake();
        //cake1.setName("线下");
        cake2.setName("扫码");
        cake3.setName("人脸");
        cake4.setName("刷卡");
        cake4.setValue(payCard);
        cake3.setValue(face);
        cake2.setValue(scanningCode);
        //cake1.setValue(offline);
        lists.add(cake3);
       // lists.add(cake1);
        lists.add(cake2);
        lists.add(cake4);
        return ReturnMsg.ok(lists);
    }


    /**
     * 查询智慧生活中智慧餐厅的核心指标
     */
    @Override
    public ReturnMsg getCoreIndicators(IocParam iocParam) {
        Indeicator indeicator = new Indeicator();
        List<JSONObject> objects = indeicator.getList();
        ThreadLocalRandom random = ThreadLocalRandom.current();
        Double totalPrice = cuisineOrderMapper.getTotalPriceByCompanyIdAndDeptId(iocParam,null);
        totalPrice = totalPrice == null ? 0 : totalPrice;
        BigDecimal bigDecimal = new BigDecimal(totalPrice);
        Integer totalOrder = cuisineOrderMapper.getTotalOrderByCompanyIdAndDeptId(iocParam);
        Integer totalPerson = cuisineOrderMapper.getTotalPersonByCompanyIdAndDeptId(iocParam);
        int dayPerson = 0;
        if(totalPerson>0){
           dayPerson = random.nextInt(0,totalPerson);
        }
        // 转换为万元(除以10000)保留两位小数
        BigDecimal decimal = bigDecimal.divide(new BigDecimal("10000"), 2, RoundingMode.HALF_UP);
        totalPrice = decimal.doubleValue();
        double compare = random.nextDouble(-1, 1);
        DecimalFormat decimalFormat = new DecimalFormat("#.0");
        compare = Double.parseDouble(decimalFormat.format(compare));

        Integer flow = 0;
        if(totalOrder>0){
            flow = random.nextInt(85,95);
        }

        objects.get(0).put("value",dayPerson);
        objects.get(0).put("compare",compare);

        objects.get(1).put("value",flow);
        objects.get(1).put("compare",compare);

        objects.get(2).put("value",totalPrice);
        objects.get(2).put("compare",compare);

        objects.get(3).put("value",totalOrder);
        objects.get(3).put("compare",compare);
        indeicator.setWorthAttention("餐厅今⽇运⾏状态良好");
        indeicator.setList(objects);
        return ReturnMsg.ok(indeicator);
    }

    /**
     * 查询智慧生活中智慧餐厅的欢迎菜品
     */
    @Override
    public ReturnMsg getWelcomeDishes(IocParam iocParam) {
        List<Cuisine> cuisineList = new ArrayList<>();
        List<Map<String,String>> lists = cuisineOrderMapper.getTopListByCompanyIdAndDeptId(iocParam);
        for (Map<String,String> map:lists){
            Cuisine cuisine = new Cuisine();
            cuisine.setCuisineImg(map.get("cuisine_img"));
            cuisine.setCuisineName(map.get("p_name"));
            cuisine.setPrice(map.get("price"));
            cuisine.setSaleNumber(String.valueOf(map.get("total")));
            cuisineList.add(cuisine);
        }
        return ReturnMsg.ok(cuisineList);
    }



    /**
     * 查询智慧生活中智慧餐厅的消费分析
     */
    @Override
    public ReturnMsg getConsumptionAnalysis(IocParam iocParam) {
        String[] param = {"breakfast","lunch","dinner","breakfastPrice","lunchPrice","dinnerPrice"};
       // String[] labKey = {"1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"};
        //List<Label> labels1 = GeneralMethod.getInstance().dataGeneration(param, labKey);
        String startStr = iocParam.getTimeRange().getStartDate();
        String endStr = iocParam.getTimeRange().getEndDate();
        List<String> list = DateUtil.getBetweenDays(startStr, endStr);
        String[] labKey = list.toArray(new String[0]);
        List<Label> labels1 = new ArrayList<>();
        DecimalFormat decimalFormat = new DecimalFormat("#.0");
        for (int i = 0; i < labKey.length; i++) {
            Label label = new Label();
            JSONObject jsonObject = new JSONObject();
            IocParam iocParam1 = new IocParam();
            iocParam1.setCompanyId(iocParam.getCompanyId());
            iocParam1.setDeptId(iocParam.getDeptId());
            IocTimeRange iocTimeRange = new IocTimeRange();
            iocTimeRange.setStartDate(labKey[i]+" 00:00:00");
            iocTimeRange.setEndDate(labKey[i]+" 10:00:00");
            iocParam1.setTimeRange(iocTimeRange);

            IocParam iocParam2 = new IocParam();
            iocParam2.setCompanyId(iocParam.getCompanyId());
            iocParam2.setDeptId(iocParam.getDeptId());
            IocTimeRange iocTimeRange2 = new IocTimeRange();
            iocTimeRange2.setStartDate(labKey[i]+" 10:00:00");
            iocTimeRange2.setEndDate(labKey[i]+" 15:00:00");
            iocParam2.setTimeRange(iocTimeRange2);

            IocParam iocParam3 = new IocParam();
            IocTimeRange iocTimeRange3 = new IocTimeRange();
            iocTimeRange3.setStartDate(labKey[i]+" 15:00:00");
            iocTimeRange3.setEndDate(labKey[i]+" 23:59:00");
            iocParam3.setTimeRange(iocTimeRange3);

            Integer totalBreakfastPerson = cuisineOrderMapper.getTotalPersonByCompanyIdAndDeptId(iocParam1);
            Integer totalLunchPerson = cuisineOrderMapper.getTotalPersonByCompanyIdAndDeptId(iocParam2);
            Integer totalDinnerPerson = cuisineOrderMapper.getTotalPersonByCompanyIdAndDeptId(iocParam3);
            Double breakfastPrice = cuisineOrderMapper.getAvgPriceByCompanyIdAndDeptId(iocParam1);
            Double lunchPrice = cuisineOrderMapper.getAvgPriceByCompanyIdAndDeptId(iocParam2);
            Double dinnerPrice = cuisineOrderMapper.getAvgPriceByCompanyIdAndDeptId(iocParam3);
            breakfastPrice = breakfastPrice==null?0:new BigDecimal(breakfastPrice).divide(new BigDecimal("100"),2,RoundingMode.HALF_UP).doubleValue();
            lunchPrice = lunchPrice==null?0:new BigDecimal(lunchPrice).divide(new BigDecimal("100"),2,RoundingMode.HALF_UP).doubleValue();
            dinnerPrice = dinnerPrice==null?0:new BigDecimal(dinnerPrice).divide(new BigDecimal("100"),2,RoundingMode.HALF_UP).doubleValue();
            jsonObject.put(param[0],totalBreakfastPerson);
            jsonObject.put(param[1],totalLunchPerson);
            jsonObject.put(param[2],totalDinnerPerson);
            jsonObject.put(param[3],breakfastPrice);
            jsonObject.put(param[4],lunchPrice);
            jsonObject.put(param[5],dinnerPrice);
            label.setJsonObject(jsonObject);
            label.setLabel(labKey[i]);
            labels1.add(label);
        }
        return ReturnMsg.ok(labels1);
    }


    /**
     * 查询智慧生活中智慧餐厅的今日菜谱
     */
    @Override
    public ReturnMsg getTodayMenu() {
        List<FoodMenu> list = foodMenusMapper.getListByType(null);
        return ReturnMsg.ok(list);
    }

    /**
     * 查询智慧生活中智慧餐厅的盈利分析
     */
    @Override
    public ReturnMsg getProfitAnalysis(IocParam iocParam) throws ParseException {
        List<Cake> lists = new ArrayList<>();
        List<Order> list = cuisineOrderMapper.getListByCompanyIdAndDeptId(iocParam);
        Double breakfast = 0d;
        Double lunch = 0d;
        Double dinner = 0d;
        Cake cakeBreakfast = new Cake();
        Cake cakeLunch = new Cake();
        Cake cakeDinner = new Cake();
        cakeBreakfast.setName("早餐");
        cakeLunch.setName("午餐");
        cakeDinner.setName("晚餐");
        if(list==null){

        }else{
            for (Order order:list){
                String time = order.getOrderTime().substring(10);
                SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
                Date date1 = sdf.parse(time);
                Date date2 = sdf.parse("10:00:00");
                if(date1.before(date2)&&date1.after(sdf.parse("00:00:00"))){
                    //早餐
                    breakfast+=order.getOrderPrice();
                }
                if(date1.before(sdf.parse("15:00:00"))&&date1.after(sdf.parse("10:00:00"))){
                    //午餐
                    lunch += order.getOrderPrice();
                }
                if(date1.before(sdf.parse("23:59:00"))&&date1.after(sdf.parse("15:00:00"))){
                    //晚餐
                    dinner += order.getOrderPrice();
                }
            }
            breakfast = new BigDecimal(breakfast).divide(new BigDecimal("100"),2,RoundingMode.HALF_UP).doubleValue();
            lunch = new BigDecimal(lunch).divide(new BigDecimal("100"),2,RoundingMode.HALF_UP).doubleValue();
            dinner = new BigDecimal(dinner).divide(new BigDecimal("100"),2,RoundingMode.HALF_UP).doubleValue();
        }
        cakeBreakfast.setValue(breakfast);
        cakeDinner.setValue(dinner);
        cakeLunch.setValue(lunch);
       lists.add(cakeBreakfast);
       lists.add(cakeLunch);
       lists.add(cakeDinner);


        return ReturnMsg.ok(lists);
    }

    /**
     * 查询智慧生活中智慧餐厅的用餐分析
     */
    @Override
    public ReturnMsg getMealAnalysis(IocParam iocParam) {
        String[] param = {"passengerFlow","eat","proportion"};
       // String[] labKey = {"1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"};
        String startStr = iocParam.getTimeRange().getStartDate();
        String endStr = iocParam.getTimeRange().getEndDate();
        List<String> list = DateUtil.getBetweenDays(startStr, endStr);
        String[] labKey = list.toArray(new String[0]);
        //List<Label> labels1 = GeneralMethod.getInstance().dataGeneration(param, labKey);
        List<Label> labels1 = new ArrayList<>();
        DecimalFormat decimalFormat = new DecimalFormat("#");
        for (int i = 0; i < labKey.length; i++) {
            Label label = new Label();
            JSONObject jsonObject = new JSONObject();
            IocParam iocParam1 = new IocParam();
            iocParam1.setCompanyId(iocParam.getCompanyId());
            iocParam1.setDeptId(iocParam.getDeptId());
            IocTimeRange iocTimeRange = new IocTimeRange();
            iocTimeRange.setStartDate(labKey[i]+" 00:00:00");
            iocTimeRange.setEndDate(labKey[i]+" 23:59:00");
            iocParam1.setTimeRange(iocTimeRange);
            Integer totalPerson = cuisineOrderMapper.getTotalPersonByCompanyIdAndDeptId(iocParam1);
            ThreadLocalRandom random = ThreadLocalRandom.current();
            double add = random.nextDouble(1, 1.5);
            Integer passengerFlow = Integer.valueOf(decimalFormat.format( totalPerson*add));
            double proportion = 0d;
            if(totalPerson>0){
                BigDecimal bigDecimal = new BigDecimal(totalPerson);
                BigDecimal decimal = bigDecimal.divide(new BigDecimal(passengerFlow), 2, RoundingMode.HALF_UP);
                proportion = decimal.doubleValue()*100;
            }
            jsonObject.put(param[0],passengerFlow);
            jsonObject.put(param[1],totalPerson);
            jsonObject.put(param[2],proportion);
            label.setJsonObject(jsonObject);
            label.setLabel(labKey[i]);
            labels1.add(label);
        }
        return ReturnMsg.ok(labels1);
    }

    /**
     * TODO 查询智能看板统计画像的餐厅消费态势的核心指标
     * @Description
     * @Return com.sky.ioc.tool.ReturnMsg
     * @Author LunCe
     * @date 2023/2/22 15:22
     */
    @Override
    public ReturnMsg getRestaurantConsumption(IocParam iocParam) {
        Indeicator indeicator = new Indeicator();
        List<JSONObject> objects = indeicator.getList();
       /* double thirdPay = 0d;
        ThreadLocalRandom random = ThreadLocalRandom.current();
        Double totalPrice = cuisineOrderMapper.getTotalPriceByCompanyIdAndDeptId(iocParam,null);
        totalPrice = totalPrice == null ? 0 : totalPrice;
        BigDecimal bigDecimal = new BigDecimal(totalPrice);
        Integer totalOrder = cuisineOrderMapper.getTotalOrderByCompanyIdAndDeptId(iocParam);
        double avgPrice = 0d;
        if (totalPrice > 0) {
            if (totalOrder > 0) {
                BigDecimal avgPriceDec = bigDecimal.divide(new BigDecimal(totalOrder), 2, RoundingMode.HALF_UP);
                avgPrice = avgPriceDec.doubleValue();
            }
        }
        DecimalFormat decimalFormat = new DecimalFormat("#.0");
        totalPrice = Double.parseDouble(decimalFormat.format(totalPrice));*/
        double compare = 0.5;
        //compare = Double.parseDouble(decimalFormat.format(compare));
        objects.get(0).put("value",16278.5);
        objects.get(0).put("compare",compare);
        objects.get(1).put("value",1182);
        objects.get(1).put("compare",compare);
        objects.get(2).put("value",13.8);
        objects.get(2).put("compare",compare);
        objects.get(3).put("value",41.81);
        objects.get(3).put("compare",compare);
        indeicator.setWorthAttention("餐厅今⽇运⾏状态良好");
        indeicator.setList(objects);
        return ReturnMsg.ok(indeicator);
    }


    /**
     * TODO
     * @Description 查询智能看板统计画像的餐厅统计消费信息报表
     * @Return com.sky.ioc.tool.ReturnMsg
     * @Author LunCe
     * @date 2023/2/22 15:22
     */
    @Override
    public ReturnMsg getRestaurantConsumptionChart(IocParam iocParam) {
        String[] param = {"consumptionAmount","consumptionOrder"};
        String startStr = iocParam.getTimeRange().getStartDate();
        String endStr = iocParam.getTimeRange().getEndDate();
        List<String> list = DateUtil.getBetweenDays(startStr, endStr);
        String[] labKey = list.toArray(new String[0]);
        List<Label> labels1 = new ArrayList<>();
        DecimalFormat decimalFormat = new DecimalFormat("#.0");
        for (int i = 0; i < labKey.length; i++) {
            Label label = new Label();
            JSONObject jsonObject = new JSONObject();
            IocParam iocParam1 = new IocParam();
            IocTimeRange iocTimeRange = new IocTimeRange();
            iocTimeRange.setStartDate(labKey[i]+" 00:00:00");
            iocTimeRange.setEndDate(labKey[i]+" 23:59:00");
            iocParam1.setTimeRange(iocTimeRange);
            Double totalPrice = cuisineOrderMapper.getTotalPriceByCompanyIdAndDeptId(iocParam1,null);
            totalPrice = totalPrice == null ? 0 : new BigDecimal(totalPrice).divide(new BigDecimal("100"),2,RoundingMode.HALF_UP).doubleValue();
            totalPrice = Double.valueOf(decimalFormat.format(totalPrice));
            Integer totalOrder = cuisineOrderMapper.getTotalOrderByCompanyIdAndDeptId(iocParam1);
            jsonObject.put(param[0],totalPrice);
            jsonObject.put(param[1],totalOrder);

            label.setJsonObject(jsonObject);
            label.setLabel(labKey[i]);
            labels1.add(label);
        }
        return ReturnMsg.ok(labels1);
    }

    @Override
    public ReturnMsg getOrderData() {
        cuisineOrderMapper.delete(null);
        cuisineOderItemMapper.delete(null);
        int pageNum = 1;
        for (int k =0;k<10;k++){
            pageNum = k+1;
            String url =   String.format(CANTEEN_ORDER_URL,"http://"+dataIp)+"?pageNum="+pageNum+"&pageSize=1000";
            Map<String,String> tokenMap = tokenMapper.getNewToken();
            String token ="Bearer eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VyX2tleSI6IjUwZTU1NTRkLWJjYzYtNGRhMS1iZDUxLWFhNTc3YzU4YTFiNCIsInVzZXJuYW1lIjoiYWRtaW4ifQ.X10VPYJfeeRTka7OtqNPOGMpL4QkW3fR_TfCKXCmO-yXbIIrr_40fcwiVnpXfYVENo_BvXWEACRd-Y6nXsbkog";
            if(tokenMap!=null){
                token = "Bearer "+tokenMap.get("token");
            }
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.set("authorization", token);
            HttpEntity<String> httpEntity = new HttpEntity(httpHeaders);
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<Map> responseEntity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, Map.class);
            Map<String, Object> body = responseEntity.getBody();
            Integer code = (Integer)body.get("code");
            String message = (String)body.get("msg");
            if(code==200){
                ArrayList list = (ArrayList) body.get("rows");
                if(list!=null&&list.size()>0){
                    for (int i=0;i<list.size();i++){
                        LinkedHashMap json = (LinkedHashMap) list.get(i);
                        Order order = new Order();
                        order.setId((Integer) json.get("id"));
                        order.setOrderId(String.valueOf(json.get("oriId")));
                        order.setOrderPrice(Double.parseDouble(String.valueOf(json.get("totalFee"))));
                        order.setOrderTime(String.valueOf(json.get("orderTime")));
                        order.setPaytype(Integer.parseInt(String.valueOf(json.get("oSource"))));
                        ArrayList products = (ArrayList) json.get("products");
                        for(int j=0;j<products.size();j++){
                            LinkedHashMap product = (LinkedHashMap) products.get(j);
                            String name = String.valueOf(product.get("name"));
                            CuisineOrderItem oderItem = new CuisineOrderItem();
                            Cuisine cuisine = cuisineMapper.getByName(name);
                            //.selectOne(new LambdaQueryWrapper<Cuisine>().eq(Cuisine::getCuisineName,name));
                            if(cuisine!=null){
                                oderItem.setPId(cuisine.getId());
                                oderItem.setOrderNum(order.getOrderId());
                                oderItem.setPName(name);
                                oderItem.setPPrice(Double.parseDouble(String.valueOf(product.get("price"))));
                                cuisineOderItemMapper.insert(oderItem);

                            }
                        }
                        cuisineOrderMapper.insert(order);
                    }
                }

            }else{
                log.info("获取餐厅订单记录数据："+message);
                return  ReturnMsg.fail(message);
            }
        }
        return ReturnMsg.ok();

    }
}
