package cn.iocoder.yudao.module.inspection.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.partner.entity.PartnerWorker;
import cn.iocoder.yudao.module.partner.service.IPartnerWorkerService;
import cn.iocoder.yudao.module.payment.entity.OrderInfo;
import cn.iocoder.yudao.module.payment.mapper.OrderInfoMapper;
import cn.iocoder.yudao.module.payment.service.OrderInfoService;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import cn.iocoder.yudao.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import cn.iocoder.yudao.module.inspection.entity.InspectionInfo;
import cn.iocoder.yudao.module.inspection.entity.ShopInspectionCategory;
import cn.iocoder.yudao.module.inspection.entity.ShopInspectionGoods;
import cn.iocoder.yudao.module.inspection.service.*;
import cn.iocoder.yudao.module.inspection.vo.InspectionInfoVo;
import cn.iocoder.yudao.module.inspection.vo.OrderAppDetail;
import cn.iocoder.yudao.module.shop.entity.ShopMallPartners;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class AppInspectionOrderServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements AppInspectionOrderService {
    @Autowired
    IInspectionInfoService  infoService;
    @Autowired
    InspectionStepInfoService stepInfoService;
    @Autowired
    private AppInspectionPartnerService partnerService;
    @Autowired
    private AdminUserApi userService;
    @Autowired
    private OrderInfoService orderInfoService;
    @Autowired
    private IPartnerWorkerService workerService;
    @Autowired
    private IShopInspectionGoodsService goodsService;
    @Autowired
    private ShopInspectionCategoryService categoryService;

    //app的订单详情
    @Override
    public OrderAppDetail orderDetailApp(Long orderId) {
        LoginUser user = SecurityFrameworkUtils.getLoginUser();
        OrderInfo orderInfo = this.getById(orderId);
        if (!user.getId().equals(orderInfo.getUserId())){
            return null;
        }
        OrderAppDetail  orderDetail =new OrderAppDetail();
        orderDetail.setOrderStatus(orderInfo.getOrderStatus());
        orderDetail.setGoodsId(orderInfo.getGoodsId());
        orderDetail.setGoodsTitle(orderInfo.getGoodsTitle()+ (StringUtils.isNotEmpty(orderInfo.getSkuName())?"-"+orderInfo.getSkuName():""));
        orderDetail.setGoodsImage(orderDetail.getGoodsImage());
        orderDetail.setGoodsPrice(orderInfo.getGoodsPrice());
        orderDetail.setPayMoney(orderInfo.getPayMoney());
        orderDetail.setBalance(orderInfo.getBalance());
        orderDetail.setPayTime(orderInfo.getPayTime());
        orderDetail.setOrderNo(orderInfo.getOrderNo());
        orderDetail.setCouponDiscount(orderInfo.getCouponDiscount());
        orderDetail.setPatnerId(orderInfo.getPartnerId());
        orderDetail.setPartnerName(orderInfo.getPartnerName());
        orderDetail.setReduceMoney(orderInfo.getReduceMoney());
        orderDetail.setValidationTime(orderInfo.getValidationTime());
        ShopMallPartners partners = partnerService.getById(orderInfo.getPartnerId());
        orderDetail.setAccessCode(orderInfo.getAccessCode());
        orderDetail.setPartnerAddress(Optional.ofNullable(partners.getAddress()).orElse(""));
        orderDetail.setContactNumber(partners.getContactNumber());
        orderDetail.setLatitude(partners.getLatitude());
        orderDetail.setLongitude(partners.getLongitude());
        orderDetail.setWorkTimeStr(partners.getWorkTime());
        orderDetail.setCommentStar(orderInfo.getCommentStar());
        orderDetail.setCommentDesc(orderInfo.getCommentDesc());
        return orderDetail;
    }

    @Override
    public IPage<InspectionInfo> inspectionList(Page<InspectionInfo> page, String status) {
        LoginUser user = SecurityFrameworkUtils.getLoginUser();
        return baseMapper.inspectionList(page,status,user.getId());
    }

    @Override
    public InspectionInfoVo inspectionDetail(Long inspectionInfoId) {
        InspectionInfo info = infoService.getById(inspectionInfoId);
        AdminUserRespDTO buyUser = userService.getUser(info.getUserId());
        PartnerWorker workerTmp = workerService.getById(info.getWorkId());
        AdminUserRespDTO worker = userService.getUser(workerTmp.getUserId());
        OrderInfo orderInfo = orderInfoService.getById(info.getInspectionOrderId());
        ShopInspectionGoods goods = goodsService.getById(orderInfo.getGoodsId());
        ShopInspectionCategory category = categoryService.getById(goods.getGoodsCategoryId());
        InspectionInfoVo res =new  InspectionInfoVo();
        res.setGoodsName(orderInfo.getGoodsTitle());
        res.setGoodsImage(ObjectUtil.isEmpty(goods)?"":goods.getImage());
        res.setStatus(info.getStatus());
        res.setIsPass(info.getIsPass());
        res.setWorkerAvatar(Optional.ofNullable(worker.getAvatar()).orElse(null));
        res.setWorkerName(worker.getNickname());
        res.setWorkerPhone(worker.getMobile());
        res.setBuyUserName(Optional.ofNullable(buyUser.getNickname()).orElse(""));
        res.setBuyUserPhone(buyUser.getMobile());
        res.setCarNum(info.getCarNum());
        res.setCategoryId(info.getCategoryId());
        res.setStartTime(info.getStartTime());
        res.setEndTime(info.getEndTime());
        res.setRemark(info.getRemark());
        res.setCarType(category.getCategoryName());
        return res;
    }

    @Override
    public JSONObject statisticsTop() {
        JSONObject res =new JSONObject();
        long countSum = infoService.count();
        LambdaQueryWrapper<InspectionInfo> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(InspectionInfo::getIsPass,"1");
        long countPassTmp = infoService.count(queryWrapper);

        queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(InspectionInfo::getIsPass,"0");
        long countNoPassTmp = infoService.count(queryWrapper);
        Double countPass = (double) countPassTmp;
        Double countNoPass = (double) countNoPassTmp;
        double passRatio = 100;
        if (countPass + countNoPass!=0){
            passRatio = BigDecimal.valueOf(countPass / (countPass + countNoPass)).setScale(4,BigDecimal.ROUND_HALF_UP).doubleValue()*100d;
        }
        double noPassRatio = 100d-passRatio;
        res.put("sum",countSum);
        res.put("countPass",countPassTmp);
        res.put("countNoPass",countNoPassTmp);
        List<JSONObject> resList =new ArrayList<>();
        JSONObject tmp =new JSONObject();
        tmp.put("name","合格");
        tmp.put("value",passRatio);
        resList.add(tmp);
        JSONObject tmp2 =new JSONObject();
        tmp2.put("name","不合格");
        tmp2.put("value",noPassRatio);
        resList.add(tmp2);
        res.put("list",resList);
        return res;
    }

    @Override
    public List<JSONObject>  statisticsMid() {
        List<JSONObject> jsonObject = baseMapper.statisticsMid();
        return jsonObject;
    }

    @Override
    public JSONObject statisticsZXT(Long partnerId, String type) {
        JSONObject res =new JSONObject();
        String startTime ="";
        String endTime ="";
        List<JSONObject> tmpList =new ArrayList<>();
        if (type.equals("week")){
            // 获取当前日期
            LocalDate currentDate = LocalDate.now();

            // 获取当前周的开始日期
            LocalDate startOfWeek = currentDate.with(TemporalAdjusters.previousOrSame(java.time.DayOfWeek.MONDAY));

            // 创建日期时间格式化器
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

            // 将日期格式化为字符串
            startTime = startOfWeek.atStartOfDay().format(formatter);
            endTime = DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss");
            tmpList=  baseMapper.statisticsZXTDay(partnerId,startTime,endTime);

        }else if (type.equals("month")){
            // 获取当前日期
            LocalDate currentDate = LocalDate.now();

            // 获取当前月的第一天
            LocalDate firstDayOfMonth = currentDate.with(TemporalAdjusters.firstDayOfMonth());
            // 创建日期时间格式化器
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            startTime = firstDayOfMonth.atStartOfDay().format(formatter);
            endTime = DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss");
            tmpList=  baseMapper.statisticsZXTDay(partnerId,startTime,endTime);
        }else if (type.equals("year")){
            // 获取当前日期
            LocalDate currentDate = LocalDate.now();

            // 获取当前年的第一天
            LocalDate firstDayOfYear = currentDate.withDayOfYear(1).withMonth(1);
            // 创建日期时间格式化器
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            startTime = firstDayOfYear.atStartOfDay().format(formatter);
            endTime = DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss");
            tmpList=  baseMapper.statisticsZXTMonth(partnerId,startTime,endTime);

        }
        List<String> categories =new ArrayList<>();
        List<JSONObject> series =new ArrayList<>();
        List<Integer> data1 =new ArrayList<>();
        List<Integer> data2 =new ArrayList<>();
        List<Integer> data3 =new ArrayList<>();
        for (JSONObject jsonObject : tmpList) {
            categories.add(jsonObject.getString("timeStr"));
            data1.add(jsonObject.getInteger("total"));
            data2.add(jsonObject.getInteger("pass"));
            data3.add(jsonObject.getInteger("noPass"));
        }

        JSONObject temp1 =new JSONObject();
        temp1.put("name","总数");
        temp1.put("data",data1);
        series.add(temp1);

        JSONObject temp2 =new JSONObject();
        temp2.put("name","合格");
        temp2.put("data",data2);
        series.add(temp2);

        JSONObject temp3 =new JSONObject();
        temp3.put("name","不合格");
        temp3.put("data",data3);
        series.add(temp3);

        res.put("categories",categories);
        res.put("series",series);
        return res;
    }

    @Override
    public List<JSONObject> statisticsOrder() {
        return baseMapper.statisticsOrder();
    }

    @Override
    public List<JSONObject> getPartnerList(String partnerName) {
        return baseMapper.getPartnerList(partnerName);
    }

    @Override
    public IPage<InspectionInfo> governmentInspectionList(Page<InspectionInfo> page,String carNum, String status, String partnerId) {
        return baseMapper.governmentInspectionList(page,carNum,status,partnerId);
    }


}
