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

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.framework.tenant.core.db.TenantBaseDO;
import cn.iocoder.yudao.module.config.service.IInspSysConfigService;
import cn.iocoder.yudao.module.label.vo.LabelRespVO;
import cn.iocoder.yudao.module.partner.entity.PartnerBalance;
import cn.iocoder.yudao.module.partner.entity.PartnerBalanceDetail;
import cn.iocoder.yudao.module.partner.entity.PartnerCustomerInfo;
import cn.iocoder.yudao.module.partner.entity.PartnerWorker;
import cn.iocoder.yudao.module.partner.service.IPartnerBalanceDetailService;
import cn.iocoder.yudao.module.partner.service.IPartnerBalanceService;
import cn.iocoder.yudao.module.partner.service.IPartnerCustomerInfoService;
import cn.iocoder.yudao.module.partner.service.IPartnerWorkerService;
import cn.iocoder.yudao.module.payment.entity.OrderInfo;
import cn.iocoder.yudao.module.payment.entity.OrderInfoDetail;
import cn.iocoder.yudao.module.payment.service.IOrderInfoDetailService;
import cn.iocoder.yudao.module.system.controller.admin.dept.vo.post.PostPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.user.UserSaveReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.dept.PostDO;
import cn.iocoder.yudao.module.system.dal.dataobject.dept.UserPostDO;
import cn.iocoder.yudao.module.system.dal.dataobject.dict.DictDataDO;
import cn.iocoder.yudao.module.system.dal.dataobject.permission.RoleDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.dal.mysql.dept.UserPostMapper;
import cn.iocoder.yudao.module.system.service.dept.PostService;
import cn.iocoder.yudao.module.system.service.dict.DictDataService;
import cn.iocoder.yudao.module.system.service.permission.PermissionService;
import cn.iocoder.yudao.module.system.service.permission.RoleService;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import cn.iocoder.yudao.util.AddressSplitter;
import cn.iocoder.yudao.util.SendSmsUtil;
import cn.iocoder.yudao.util.VehicleLicenseOCR;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import cn.iocoder.yudao.util.StringUtils;
import cn.iocoder.yudao.module.inspection.entity.*;
import cn.iocoder.yudao.module.inspection.mapper.AppInspectionPartnerMapper;
import cn.iocoder.yudao.module.inspection.query.PartnerListQuery;
import cn.iocoder.yudao.module.inspection.service.*;
import cn.iocoder.yudao.module.inspection.utils.PhoneValidator;
import cn.iocoder.yudao.module.inspection.vo.*;
import cn.iocoder.yudao.module.shop.entity.ShopCouponTemplate;
import cn.iocoder.yudao.module.shop.entity.ShopMallPartners;
import cn.iocoder.yudao.module.shop.entity.ShopUserCar;
import cn.iocoder.yudao.module.shop.service.IShopCouponTemplateService;
import cn.iocoder.yudao.module.shop.service.IShopUserCarService;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.stream.Collectors;

@Service("appInspectionPartnerService")
public class AppInspectionPartnerServiceImpl extends ServiceImpl<AppInspectionPartnerMapper,ShopMallPartners> implements AppInspectionPartnerService {
    @Autowired
    private AppInspectionOrderService orderService;
    @Autowired
    private AppInspectionGoodsService goodsService;
    @Autowired
    private InspectionGoodsSkuService skuService;
    @Autowired
    private IPartnerBalanceService partnerBalanceService;
    @Autowired
    private IPartnerBalanceDetailService detailService;
    @Autowired
    private ShopInspectionCategoryService categoryService;
    @Autowired
    private IInspectionInfoService inspectionInfoService;
    @Autowired
    private AdminUserService userService;
    @Autowired
    private IPartnerWorkerService partnerWorkerService;
    @Autowired
    private InspectionStepInfoService stepInfoService;
    @Autowired
    private IInspectionAppointmentService appointmentService;
    @Autowired
    private IShopCouponTemplateService templateService;
    @Autowired
    private IInspectionPickCarService pickCarService;
    @Autowired
    private IInspectionCategoryTemplateService  categoryTemplateService;
    @Autowired
    private IPartnerCustomerInfoService customerInfoService;
    @Autowired
    private IOrderInfoDetailService orderInfoDetailService;
    @Autowired
    private IInspSysConfigService configService;
    @Autowired
    private DictDataService dictDataService;
    @Autowired
    private PostService postService;
    @Autowired
    private UserPostMapper userPostMapper;
    @Autowired
    private IShopUserCarService userCarService;
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private RoleService roleService;

    @Override
    public IPage<PartnerListVo> partnerList(Page<PartnerListVo> page, PartnerListQuery partnerListQuery) {
        if (null!=partnerListQuery.getDistance()){
            partnerListQuery.setDistance(partnerListQuery.getDistance()*1000);
        }
        IPage<PartnerListVo> partnerListVos = baseMapper.partnerList(page,partnerListQuery);
        return partnerListVos;
    }

    @Override
    public List<ShopInspectionCategory> categoryList(Long partnerId) {
        LoginUser user = SecurityFrameworkUtils.getLoginUser();
        ShopMallPartners partners = baseMapper.selectById(partnerId);
        if (!partners.getUserId().equals(user.getId())){
            return null;
        }
        List<ShopInspectionCategory> shopInspectionCategories = baseMapper.partnerCategoryList(partnerId);
        for (ShopInspectionCategory shopInspectionCategory : shopInspectionCategories) {
            LambdaQueryWrapper<InspectionCategoryTemplate> templateLambdaQueryWrapper =new LambdaQueryWrapper<>();
            templateLambdaQueryWrapper.eq(InspectionCategoryTemplate::getCategoryId,shopInspectionCategory.getId()).orderByAsc(InspectionCategoryTemplate::getSkuPrice);
            List<InspectionCategoryTemplate> list = categoryTemplateService.list(templateLambdaQueryWrapper);
            shopInspectionCategory.setTemplates(list);
        }
        return shopInspectionCategories;
    }

    @Override
    public PartnerListVo shopDetail(PartnerListQuery partnerListQuery) {
        PartnerListVo partnerListVo = baseMapper.shopDetail(partnerListQuery);
        if (!StringUtils.isEmpty(partnerListVo.getShopImages())){
            String[] shopImages = partnerListVo.getShopImages().split(",");
            partnerListVo.setImageList(Arrays.asList(shopImages));
        }else {
            partnerListVo.setImageList(new ArrayList<>());
        }
        return partnerListVo;
    }

    @Override
    public void addSalesNum(Long partnerId) {
        baseMapper.addSalesNum(partnerId);
    }

    @Override
    @TenantIgnore
    public ShopMallPartners shopInfo() throws Exception {
        LoginUser user = SecurityFrameworkUtils.getLoginUser();
        Set<Long> userRoleIdListByUserId = permissionService.getUserRoleIdListByUserId(user.getId());
        List<RoleDO> roleList = roleService.getRoleList(userRoleIdListByUserId);

        List<String> roles = roleList.stream().map(RoleDO::getCode).collect(Collectors.toList());
        ShopMallPartners partner  = new ShopMallPartners();
        if (roles.contains("jcshop")){
            LambdaQueryWrapper<ShopMallPartners> queryWrapper =new LambdaQueryWrapper<>();
            queryWrapper.eq(ShopMallPartners::getUserId,user.getId()).eq(ShopMallPartners::getType,"jc").eq(ShopMallPartners::getIsBanned,"0");
            partner = this.getOne(queryWrapper);
            if (ObjectUtil.isEmpty(partner)){
                throw new Exception("信息有误");
            }
        }else if (roles.contains("jcworker")){
            LambdaQueryWrapper<PartnerWorker> queryWrapperWork =new LambdaQueryWrapper<>();
            queryWrapperWork.eq(PartnerWorker::getUserId,user.getId());
            PartnerWorker worker = partnerWorkerService.getOne(queryWrapperWork);
            if (ObjectUtil.isEmpty(worker)){
                throw new Exception("信息有误");
            }
            partner.setPartnerId(worker.getPartnerId());
        }
        return partner;
    }

    /**
     * 对shopInfo方法的重写，只根据user_id进行查询
     *
     */
    @Override
    public ShopMallPartners shopInfoByUserId() throws Exception {
        LambdaQueryWrapper<ShopMallPartners> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(ShopMallPartners::getPartnerId).last("limit 1");
        ShopMallPartners partner = this.getOne(queryWrapper);
        if (ObjectUtil.isEmpty(partner)){
            throw new Exception("未查询到信息");
        }
        return partner;
    }



    @Override
    public JSONObject getAppointAndPickNum() throws Exception {
        ShopMallPartners shopMallPartners = this.shopInfo();
        String formDate =  DateUtil.format(new Date(),"yyyy-MM-dd");
        Long appointNum = baseMapper.getAppointNum(shopMallPartners.getPartnerId(),formDate);
        Long pickNum = baseMapper.getPickNum(shopMallPartners.getPartnerId(),formDate);
        JSONObject res =new JSONObject();
        res.put("appointNum",appointNum);
        res.put("pickNum",pickNum);
        return res;
    }

    @Override
    public void startOrEnd(Long partnerId) {
        ShopMallPartners partners = baseMapper.selectById(partnerId);
        if (StringUtils.isEmpty(partners.getIsWorking())||partners.getIsWorking().equals("0")){
            partners.setIsWorking("1");
        }else {
            partners.setIsWorking("0");
        }
        baseMapper.updateById(partners);
    }

    @Override
    public StatisticsInfo statisticsInfo(Long partnerId) {
        LoginUser user = SecurityFrameworkUtils.getLoginUser();
        StatisticsInfo statisticsInfo2 = baseMapper.orderNum(partnerId, DateUtil.format(new Date(),"yyyy-MM-dd"));
        //合规且合格双燃料
        Integer i = baseMapper.srlNum(partnerId, DateUtil.format(new Date(), "yyyy-MM-dd"));
        Integer hgNum = baseMapper.hgNum(partnerId, DateUtil.format(new Date(), "yyyy-MM-dd"));
        statisticsInfo2.setHgNum(hgNum);
        statisticsInfo2.setSrlNum(i);
        return statisticsInfo2;
    }

    @Override
    public JSONObject chartInfoAmount(Long partnerId,String unit) {
        LoginUser user = SecurityFrameworkUtils.getLoginUser();
        ShopMallPartners partners = baseMapper.selectById(partnerId);
        if (!partners.getUserId().equals(user.getId())){
            return null;
        }
        JSONObject res =new JSONObject();
        List<String> categories =new ArrayList<>();
        List<JSONObject> series =new ArrayList<>();
        JSONObject  seriesObject=new JSONObject();
        seriesObject.put("name","金额");
        List<Double> seriesObjectData =new ArrayList<>();
        //按照单位日期查询数据
        //横坐标获取当前商品上架的商品
        String startTime = null;
        String endTime = null;
        if (unit.equals("day")){
            String format = DateUtil.format(new Date(), "yyyy-MM-dd");
            startTime = format+" 00:00:00";
            endTime = format+" 23:59:59";
        } else if (unit.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");
        } else if (unit.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");
        } else if (unit.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");
        }else {
            // 获取当前日期
            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");
        }
        //获取商家现有商品
        LambdaQueryWrapper<ShopInspectionGoods> queryWrapper1 =new LambdaQueryWrapper<>();
        queryWrapper1.eq(ShopInspectionGoods::getPartnerId,partnerId);
        List<ShopInspectionGoods> list1 = goodsService.list(queryWrapper1);
        List<OrderInfo> list = baseMapper.chartInfoAmount(startTime,endTime,partnerId);
        //统计各个车型的价格 从高到低
        for (OrderInfo orderInfo : list) {
            categories.add(orderInfo.getGoodsTitle().indexOf("(")>0?orderInfo.getGoodsTitle().substring(0,orderInfo.getGoodsTitle().indexOf("(")):orderInfo.getGoodsTitle());
            list1.removeIf(it->{
               return it.getTitle().equals(orderInfo.getGoodsTitle());
            });
            seriesObjectData.add(Double.valueOf(orderInfo.getRealPayMoney())/100);
        }
        categories.addAll(list1.stream().map(it->{
            return it.getTitle().indexOf("(")>0?it.getTitle().substring(0,it.getTitle().indexOf("(")):it.getTitle();
        }).collect(Collectors.toList()));
        seriesObjectData.addAll(list1.stream().map(it->{
            return 0d;
        }).collect(Collectors.toList()));
        seriesObject.put("data",seriesObjectData);
        series.add(seriesObject);
        res.put("categories",categories);
        res.put("series",series);
        return res;
    }
    @Override
    public JSONObject newChartInfoAmount(String unit) {
        JSONObject res =new JSONObject();
        List<String> categories =new ArrayList<>();
        List<JSONObject> series =new ArrayList<>();
        JSONObject  seriesObject=new JSONObject();
        seriesObject.put("name","金额");
        List<Double> seriesObjectData =new ArrayList<>();
        //按照单位日期查询数据
        //横坐标获取当前商品上架的商品
        String startTime = null;
        String endTime = null;
        if (unit.equals("day")){
            String format = DateUtil.format(new Date(), "yyyy-MM-dd");
            startTime = format+" 00:00:00";
            endTime = format+" 23:59:59";
        } else if (unit.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");
        } else if (unit.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");
        } else if (unit.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");
        }else {
            // 获取当前日期
            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");
        }
        //获取商家现有商品
        LambdaQueryWrapper<ShopInspectionGoods> queryWrapper1 =new LambdaQueryWrapper<>();
//        queryWrapper1.eq(ShopInspectionGoods::getPartnerId,partnerId);
        List<ShopInspectionGoods> list1 = goodsService.list(queryWrapper1);
        List<OrderInfo> list = baseMapper.newChartInfoAmount(startTime,endTime);
        //统计各个车型的价格 从高到低
        for (OrderInfo orderInfo : list) {
            categories.add(orderInfo.getGoodsTitle().indexOf("(")>0?orderInfo.getGoodsTitle().substring(0,orderInfo.getGoodsTitle().indexOf("(")):orderInfo.getGoodsTitle());
            list1.removeIf(it->{
               return it.getTitle().equals(orderInfo.getGoodsTitle());
            });
            seriesObjectData.add(Double.valueOf(orderInfo.getRealPayMoney())/100);
        }
        categories.addAll(list1.stream().map(it->{
            return it.getTitle().indexOf("(")>0?it.getTitle().substring(0,it.getTitle().indexOf("(")):it.getTitle();
        }).collect(Collectors.toList()));
        seriesObjectData.addAll(list1.stream().map(it->{
            return 0d;
        }).collect(Collectors.toList()));
        seriesObject.put("data",seriesObjectData);
        series.add(seriesObject);
        res.put("categories",categories);
        res.put("series",series);
        return res;
    }

    @Override
    public JSONObject chartLineInspectionNum(Long partnerId, String unit) {
        LoginUser user = SecurityFrameworkUtils.getLoginUser();
        ShopMallPartners partners = baseMapper.selectById(partnerId);
        if (!partners.getUserId().equals(user.getId())){
            return null;
        }
        JSONObject res = new JSONObject();
        List<String> categories =new ArrayList<>();
        List<JSONObject> series =new ArrayList<>();
        JSONObject seriesData1 =new JSONObject();
        seriesData1.put("name","总数量");
        List<Long> seriesData1List =new ArrayList<>();
        JSONObject seriesData2 =new JSONObject();
        List<Long> seriesData2List =new ArrayList<>();
        seriesData2.put("name","合格数");
//        JSONObject seriesData3 =new JSONObject();
//        List<Long> seriesData3List =new ArrayList<>();
//        seriesData3.put("name","环检次数");
        List<String> dateList = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (int i = 0; i < 7; i++) {
            //先获取最近七天的日期
            Date date = DateUtils.addDays(new Date(), -i);
            String formatDate = sdf.format(date);
            dateList.add(formatDate);
        }
        for (String date : dateList) {
            categories.add(date);
            LambdaQueryWrapper<InspectionInfo> queryWrapper1 =new LambdaQueryWrapper<>();
            queryWrapper1.eq(InspectionInfo::getPartnerId,partnerId).like(InspectionInfo::getStartTime,date);
            Long sum = inspectionInfoService.count(queryWrapper1);
            LambdaQueryWrapper<InspectionInfo> queryWrapper2 =new LambdaQueryWrapper<>();
            queryWrapper2.eq(InspectionInfo::getPartnerId,partnerId).like(InspectionInfo::getStartTime,date).eq(InspectionInfo::getIsPass,"1");
            Long passNum = inspectionInfoService.count(queryWrapper2);

           // Long noPassNum = baseMapper.dhjNum(partnerId,date);
            seriesData1List.add(sum);
            seriesData2List.add(passNum);
//            seriesData3List.add(noPassNum);
        }
        seriesData1.put("data",seriesData1List);
        seriesData2.put("data",seriesData2List);
       // seriesData3.put("data",seriesData3List);
        series.add(seriesData1);
        series.add(seriesData2);
        //series.add(seriesData3);
        res.put("categories",categories);
        res.put("series",series);
        return res;
    }
    @Override
    public JSONObject newChartLineInspectionNum(String unit) {
        JSONObject res = new JSONObject();
        List<String> categories =new ArrayList<>();
        List<JSONObject> series =new ArrayList<>();
        JSONObject seriesData1 =new JSONObject();
        seriesData1.put("name","总数量");
        List<Long> seriesData1List =new ArrayList<>();
        JSONObject seriesData2 =new JSONObject();
        List<Long> seriesData2List =new ArrayList<>();
        seriesData2.put("name","合格数");
//        JSONObject seriesData3 =new JSONObject();
//        List<Long> seriesData3List =new ArrayList<>();
//        seriesData3.put("name","环检次数");
        List<String> dateList = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (int i = 0; i < 7; i++) {
            //先获取最近七天的日期
            Date date = DateUtils.addDays(new Date(), -i);
            String formatDate = sdf.format(date);
            dateList.add(formatDate);
        }
        for (String date : dateList) {
            categories.add(date);
            LambdaQueryWrapper<InspectionInfo> queryWrapper1 =new LambdaQueryWrapper<>();
            queryWrapper1.like(InspectionInfo::getStartTime,date);
            Long sum = inspectionInfoService.count(queryWrapper1);
            LambdaQueryWrapper<InspectionInfo> queryWrapper2 =new LambdaQueryWrapper<>();
            queryWrapper2.like(InspectionInfo::getStartTime,date).eq(InspectionInfo::getIsPass,"1");
            Long passNum = inspectionInfoService.count(queryWrapper2);

           // Long noPassNum = baseMapper.dhjNum(partnerId,date);
            seriesData1List.add(sum);
            seriesData2List.add(passNum);
//            seriesData3List.add(noPassNum);
        }
        seriesData1.put("data",seriesData1List);
        seriesData2.put("data",seriesData2List);
       // seriesData3.put("data",seriesData3List);
        series.add(seriesData1);
        series.add(seriesData2);
        //series.add(seriesData3);
        res.put("categories",categories);
        res.put("series",series);
        return res;
    }

    @Override
    public JSONObject chartLineInspectionAmount(Long partnerId, String unit) {
        LoginUser user = SecurityFrameworkUtils.getLoginUser();
        ShopMallPartners partners = baseMapper.selectById(partnerId);
        if (!partners.getUserId().equals(user.getId())){
            return null;
        }
        JSONObject res = new JSONObject();
        List<String> categories =new ArrayList<>();
        List<JSONObject> series =new ArrayList<>();
        JSONObject seriesData1 =new JSONObject();
        seriesData1.put("name","成交金额");
        List<Long> seriesData1List =new ArrayList<>();
        List<String> dateList = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (int i = 0; i < 7; i++) {
            //先获取最近七天的日期
            Date date = DateUtils.addDays(new Date(), -i);
            String formatDate = sdf.format(date);
            dateList.add(formatDate);
        }
        for (String date : dateList) {
            categories.add(date);
            OrderInfo one = baseMapper.chartLineInspectionAmount(partnerId,date);
            Integer amount = Optional.ofNullable(one.getRealPayMoney()).orElse(0);
            seriesData1List.add(amount/100L);
        }
        seriesData1.put("data",seriesData1List);
        series.add(seriesData1);
        res.put("categories",categories);
        res.put("series",series);
        return res;
    }

    @Override
    public JSONObject newChartLineInspectionAmount(String unit) {
//        LoginUser user = SecurityFrameworkUtils.getLoginUser();
        JSONObject res = new JSONObject();
        List<String> categories =new ArrayList<>();
        List<JSONObject> series =new ArrayList<>();
        JSONObject seriesData1 =new JSONObject();
        seriesData1.put("name","成交金额");
        List<Long> seriesData1List =new ArrayList<>();
        List<String> dateList = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (int i = 0; i < 7; i++) {
            //先获取最近七天的日期
            Date date = DateUtils.addDays(new Date(), -i);
            String formatDate = sdf.format(date);
            dateList.add(formatDate);
        }
        for (String date : dateList) {
            categories.add(date);
            OrderInfo one = baseMapper.newChartLineInspectionAmount(date);
            Integer amount = Optional.ofNullable(one.getRealPayMoney()).orElse(0);
            seriesData1List.add(amount/100L);
        }
        seriesData1.put("data",seriesData1List);
        series.add(seriesData1);
        res.put("categories",categories);
        res.put("series",series);
        return res;
    }


    @Override
    public JSONObject chartInfoNum(Long partnerId,String unit) {
        LoginUser user = SecurityFrameworkUtils.getLoginUser();
        ShopMallPartners partners = baseMapper.selectById(partnerId);
        if (!partners.getUserId().equals(user.getId())){
            return null;
        }
        JSONObject res =new JSONObject();
        List<String> categories =new ArrayList<>();
        List<JSONObject> series =new ArrayList<>();
        JSONObject  seriesObject=new JSONObject();
        seriesObject.put("name","数量");
        List<Integer> seriesObjectData =new ArrayList<>();
        //按照单位日期查询数据
        //横坐标获取当前商品上架的商品
        String startTime ;
        String endTime ;
        if (unit.equals("day")){
            String format = DateUtil.format(new Date(), "yyyy-MM-dd");
            startTime = format+" 00:00:00";
            endTime = format+" 23:59:59";
        } else if (unit.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");
        } else if (unit.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");
        } else if (unit.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");
        }else {
            // 获取当前日期
            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");
        }
        //获取商家现有商品
        LambdaQueryWrapper<ShopInspectionGoods> queryWrapper1 =new LambdaQueryWrapper<>();
        queryWrapper1.eq(ShopInspectionGoods::getPartnerId,partnerId);
        List<ShopInspectionGoods> list1 = goodsService.list(queryWrapper1);
        List<OrderInfo> list = baseMapper.chartInfoNum(startTime,endTime,partnerId);
        //统计各个车型的价格 从高到低
        for (OrderInfo orderInfo : list) {
            categories.add(orderInfo.getGoodsTitle().indexOf("(")>0?orderInfo.getGoodsTitle().substring(0,orderInfo.getGoodsTitle().indexOf("(")):orderInfo.getGoodsTitle());
            list1.removeIf(it->{
                return it.getTitle().equals(orderInfo.getGoodsTitle());
            });
            seriesObjectData.add(orderInfo.getRealPayNum());
        }
        categories.addAll(list1.stream().map(it->{
            return it.getTitle().indexOf("(")>0?it.getTitle().substring(0,it.getTitle().indexOf("(")):it.getTitle();
        }).collect(Collectors.toList()));
        seriesObjectData.addAll(list1.stream().map(it->{
            return 0;
        }).collect(Collectors.toList()));
        seriesObject.put("data",seriesObjectData);
        series.add(seriesObject);
        res.put("categories",categories);
        res.put("series",series);
        return res;
    }
    @Override
    public JSONObject newChartInfoNum(String unit) {
        JSONObject res =new JSONObject();
        List<String> categories =new ArrayList<>();
        List<JSONObject> series =new ArrayList<>();
        JSONObject  seriesObject=new JSONObject();
        seriesObject.put("name","数量");
        List<Integer> seriesObjectData =new ArrayList<>();
        //按照单位日期查询数据
        //横坐标获取当前商品上架的商品
        String startTime ;
        String endTime ;
        if (unit.equals("day")){
            String format = DateUtil.format(new Date(), "yyyy-MM-dd");
            startTime = format+" 00:00:00";
            endTime = format+" 23:59:59";
        } else if (unit.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");
        } else if (unit.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");
        } else if (unit.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");
        }else {
            // 获取当前日期
            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");
        }
        //获取商家现有商品
        LambdaQueryWrapper<ShopInspectionGoods> queryWrapper1 =new LambdaQueryWrapper<>();
        List<ShopInspectionGoods> list1 = goodsService.list(queryWrapper1);
        List<OrderInfo> list = baseMapper.newChartInfoNum(startTime,endTime);
        //统计各个车型的价格 从高到低
        for (OrderInfo orderInfo : list) {
            categories.add(orderInfo.getGoodsTitle().indexOf("(")>0?orderInfo.getGoodsTitle().substring(0,orderInfo.getGoodsTitle().indexOf("(")):orderInfo.getGoodsTitle());
            list1.removeIf(it->{
                return it.getTitle().equals(orderInfo.getGoodsTitle());
            });
            seriesObjectData.add(orderInfo.getRealPayNum());
        }
        categories.addAll(list1.stream().map(it->{
            return it.getTitle().indexOf("(")>0?it.getTitle().substring(0,it.getTitle().indexOf("(")):it.getTitle();
        }).collect(Collectors.toList()));
        seriesObjectData.addAll(list1.stream().map(it->{
            return 0;
        }).collect(Collectors.toList()));
        seriesObject.put("data",seriesObjectData);
        series.add(seriesObject);
        res.put("categories",categories);
        res.put("series",series);
        return res;
    }

    @Override
    public JSONObject chartInfoRatio(Long partnerId, String unit) {
        LoginUser user = SecurityFrameworkUtils.getLoginUser();
        ShopMallPartners partners = baseMapper.selectById(partnerId);
        if (!partners.getUserId().equals(user.getId())){
            return null;
        }
        JSONObject res =new JSONObject();
        List<String> categories =new ArrayList<>();
        List<JSONObject> series =new ArrayList<>();
        JSONObject  seriesObject=new JSONObject();
        seriesObject.put("name","合格率");
        List<Double> seriesObjectData =new ArrayList<>();
        //按照单位日期查询数据
        //横坐标获取当前商品上架的商品
        String startTime ;
        String endTime ;
        if (unit.equals("day")){
            String format = DateUtil.format(new Date(), "yyyy-MM-dd");
            startTime = format+" 00:00:00";
            endTime = format+" 23:59:59";
        } else if (unit.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");
        } else if (unit.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");
        } else if (unit.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");
        }else {
            // 获取当前日期
            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");
        }
        //获取商家现有商品
        LambdaQueryWrapper<ShopInspectionGoods> queryWrapper1 =new LambdaQueryWrapper<>();
        queryWrapper1.eq(ShopInspectionGoods::getPartnerId,partnerId);
        List<ShopInspectionGoods> list1 = goodsService.list(queryWrapper1);
        List<Map<String,String>> list = baseMapper.chartInfoRatio(startTime,endTime,partnerId);
        //统计各个车型的价格 从高到低
        for (Map<String,String> orderInfo : list) {
            categories.add(orderInfo.get("goodsTitle").indexOf("(")>0?orderInfo.get("goodsTitle").substring(0,orderInfo.get("goodsTitle").indexOf("(")):orderInfo.get("goodsTitle"));
            list1.removeIf(it->{
                return it.getTitle().equals(orderInfo.get("goodsTitle"));
            });
            if (ObjectUtil.isEmpty(orderInfo.get("passRatio"))){
                seriesObjectData.add(0d);
            }else {
                seriesObjectData.add(Double.valueOf(String.valueOf(orderInfo.get("passRatio"))));
            }

        }
        categories.addAll(list1.stream().map(it->{
            return it.getTitle().indexOf("(")>0?it.getTitle().substring(0,it.getTitle().indexOf("(")):it.getTitle();
        }).collect(Collectors.toList()));
        seriesObjectData.addAll(list1.stream().map(it->{
            return 0d;
        }).collect(Collectors.toList()));
        seriesObject.put("data",seriesObjectData);
        series.add(seriesObject);
        res.put("categories",categories);
        res.put("series",series);
        return res;
    }
    @Override
    public JSONObject newChartInfoRatio(String unit) {
        JSONObject res =new JSONObject();
        List<String> categories =new ArrayList<>();
        List<JSONObject> series =new ArrayList<>();
        JSONObject  seriesObject=new JSONObject();
        seriesObject.put("name","合格率");
        List<Double> seriesObjectData =new ArrayList<>();
        //按照单位日期查询数据
        //横坐标获取当前商品上架的商品
        String startTime ;
        String endTime ;
        if (unit.equals("day")){
            String format = DateUtil.format(new Date(), "yyyy-MM-dd");
            startTime = format+" 00:00:00";
            endTime = format+" 23:59:59";
        } else if (unit.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");
        } else if (unit.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");
        } else if (unit.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");
        }else {
            // 获取当前日期
            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");
        }
        //获取商家现有商品
        LambdaQueryWrapper<ShopInspectionGoods> queryWrapper1 =new LambdaQueryWrapper<>();
        List<ShopInspectionGoods> list1 = goodsService.list(queryWrapper1);
        List<Map<String,String>> list = baseMapper.newChartInfoRatio(startTime,endTime);
        //统计各个车型的价格 从高到低
        for (Map<String,String> orderInfo : list) {
            categories.add(orderInfo.get("goodsTitle").indexOf("(")>0?orderInfo.get("goodsTitle").substring(0,orderInfo.get("goodsTitle").indexOf("(")):orderInfo.get("goodsTitle"));
            list1.removeIf(it->{
                return it.getTitle().equals(orderInfo.get("goodsTitle"));
            });
            if (ObjectUtil.isEmpty(orderInfo.get("passRatio"))){
                seriesObjectData.add(0d);
            }else {
                seriesObjectData.add(Double.valueOf(String.valueOf(orderInfo.get("passRatio"))));
            }

        }
        categories.addAll(list1.stream().map(it->{
            return it.getTitle().indexOf("(")>0?it.getTitle().substring(0,it.getTitle().indexOf("(")):it.getTitle();
        }).collect(Collectors.toList()));
        seriesObjectData.addAll(list1.stream().map(it->{
            return 0d;
        }).collect(Collectors.toList()));
        seriesObject.put("data",seriesObjectData);
        series.add(seriesObject);
        res.put("categories",categories);
        res.put("series",series);
        return res;
    }

    @Override
    public List<OrderInfo> orderInfo(Long partnerId) {
        LoginUser user = SecurityFrameworkUtils.getLoginUser();
        ShopMallPartners partners = baseMapper.selectById(partnerId);
        if (!partners.getUserId().equals(user.getId())){
            return null;
        }
        LambdaQueryWrapper<OrderInfo> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderInfo::getPartnerId,partnerId).isNotNull(OrderInfo::getValidationTime).orderByDesc(OrderInfo::getValidationTime).last("limit 8");
        List<OrderInfo> list = orderService.list(queryWrapper);
        return list;
    }

    @Override
    public List<HotGoodsVo> hotGoodsList(Long partnerId) {
        LoginUser user = SecurityFrameworkUtils.getLoginUser();
        ShopMallPartners partners = baseMapper.selectById(partnerId);
        if (!partners.getUserId().equals(user.getId())){
            return null;
        }
        String dateStr = DateUtil.format(new Date(), "yyyy-MM-dd");
        return baseMapper.hotGoodsList(partnerId,dateStr);
    }
    @Override
    public List<HotGoodsVo> newHotGoodsList() {
        String dateStr = DateUtil.format(new Date(), "yyyy-MM-dd");
        return baseMapper.newHotGoodsList(dateStr);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addGoods(ShopInspectionGoods goods) throws Exception {
        LoginUser user = SecurityFrameworkUtils.getLoginUser();
        ShopMallPartners partners = baseMapper.selectById(goods.getPartnerId());
        if (!partners.getUserId().equals(user.getId())){
            return;
        }
        //判断当前分类 是否已经存在商品
        LambdaQueryWrapper<ShopInspectionGoods> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(ShopInspectionGoods::getGoodsCategoryId,goods.getGoodsCategoryId()).eq(ShopInspectionGoods::getPartnerId,goods.getPartnerId());
        List<ShopInspectionGoods> list = goodsService.list(queryWrapper);
        if (CollectionUtil.isNotEmpty(list)){
            throw new Exception("当前分类已存在商品");
        }
        ShopInspectionCategory category = categoryService.getById(goods.getGoodsCategoryId());
        goods.setTitle(category.getCategoryName());
        LambdaQueryWrapper<InspectionCategoryTemplate> categoryTemplateLambdaQueryWrapper =new LambdaQueryWrapper<>();
        categoryTemplateLambdaQueryWrapper.eq(InspectionCategoryTemplate::getCategoryId,category.getId());
        List<InspectionCategoryTemplate> categoryTemplates = categoryTemplateService.list(categoryTemplateLambdaQueryWrapper);
        List<InspectionGoodsSku> skuList = categoryTemplates.stream().sorted((o1,o2)->{
            if(o1.getSkuPrice()<o2.getSkuPrice()){
                return 1;
            }else if(o1.getSkuPrice().equals(o2.getSkuPrice())){
               if (o1.getSkuName().length()<o2.getSkuName().length()){
                   return 1;
               }else {
                   return 0;
               }
            } else {
                return 0;
            }
        }).map(it->{
            InspectionGoodsSku sku =new InspectionGoodsSku();
            sku.setSkuName(it.getSkuName());
            sku.setPrice(it.getSkuPrice());
            sku.setDbPrice(it.getSkuPrice());
            sku.setDwPrice(it.getSkuPrice());
            sku.setYgPrice(it.getSkuPrice());
            return sku;
        }).collect(Collectors.toList());
        goods.setIsListing("0");
        goods.setListingStatus("0");
        goods.setRejectReason("");
        goods.setPrice(skuList.get(skuList.size()-1).getPrice());
        goodsService.save(goods);
        Integer orderNum = 1;
        for (InspectionGoodsSku it : skuList) {
            it.setGoodsId(goods.getId());
            it.setOrderNum(orderNum);
            orderNum++;
        };
        skuService.saveBatch(skuList);

    }

    @Override
    public IPage<GoodsVo> goodsList(Page<GoodsVo> page,Long partnerId, String isListing, String goodsTitle) {
       return baseMapper.manageGoodsList(page,partnerId,isListing,goodsTitle);
    }

    @Override
    public List<JSONObject> canUseGoods(Long partnerId) {
        List<JSONObject> listGoods = new ArrayList<>();
        LambdaQueryWrapper<ShopInspectionGoods> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(ShopInspectionGoods::getPartnerId,partnerId).eq(ShopInspectionGoods::getIsListing,"1").orderByAsc(ShopInspectionGoods::getOrderNum);
        List<ShopInspectionGoods> list = goodsService.list(queryWrapper);
        if (CollectionUtil.isNotEmpty(list)){
            listGoods = list.stream().map(it -> {
                JSONObject item = new JSONObject();
                item.put("label", it.getTitle());
                item.put("value", it.getId());
                return item;
            }).collect(Collectors.toList());
        }
      return   listGoods;
    }

    @Override
    public ShopInspectionGoods goodsDetail(Long goodsId) {
        ShopInspectionGoods goods = goodsService.getById(goodsId);
        LoginUser user = SecurityFrameworkUtils.getLoginUser();
        ShopMallPartners partners = baseMapper.selectById(goods.getPartnerId());
        if (!partners.getUserId().equals(user.getId())){
            return null;
        }
        LambdaQueryWrapper<InspectionGoodsSku> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(InspectionGoodsSku::getGoodsId,goodsId);
        List<InspectionGoodsSku> list = skuService.list(queryWrapper);
        goods.setSkuList(list);
        if (StringUtils.isNotEmpty(goods.getImages())){
            goods.setImageList(goods.getImages().split(","));
        }
        ShopInspectionCategory category = categoryService.getById(goods.getGoodsCategoryId());
        goods.setCategoryName(category.getCategoryName());
        return  goods;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editGoods(ShopInspectionGoods goods) throws Exception {
        LoginUser user = SecurityFrameworkUtils.getLoginUser();
        ShopMallPartners partners = baseMapper.selectById(goods.getPartnerId());
        if (!partners.getUserId().equals(user.getId())){
            return;
        }
        ShopInspectionGoods goods1 = goodsService.getById(goods.getId());
        if (goods1.getIsListing().equals("1")){
            //如果是上架状态不可编辑
            throw new Exception("请先下架");
        }
        //判断当前分类 是否已经存在商品
        LambdaQueryWrapper<ShopInspectionGoods> queryWrapper1 =new LambdaQueryWrapper<>();
        queryWrapper1.eq(ShopInspectionGoods::getGoodsCategoryId,goods.getGoodsCategoryId())
                .eq(ShopInspectionGoods::getPartnerId,goods.getPartnerId())
                .ne(ShopInspectionGoods::getId,goods.getId());
        List<ShopInspectionGoods> list = goodsService.list(queryWrapper1);
        if (CollectionUtil.isNotEmpty(list)){
            throw new Exception("当前分类已存在商品");
        }
        ShopInspectionCategory category = categoryService.getById(goods.getGoodsCategoryId());
        goods.setTitle(category.getCategoryName());
        goods.setIsListing(goods1.getIsListing());
        goods.setListingStatus(goods1.getListingStatus());
        goods.setRejectReason(goods1.getRejectReason());
        goodsService.updateById(goods);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editSkuPrice(ShopInspectionGoods goods) throws Exception {
        LoginUser user = SecurityFrameworkUtils.getLoginUser();
        ShopMallPartners partners = baseMapper.selectById(goods.getPartnerId());
        if (!partners.getUserId().equals(user.getId())){
            return;
        }
        skuService.updateBatchById(goods.getSkuList());


    }
    @Override
    public void changeListing(Long goodsId) throws Exception {
        ShopInspectionGoods goods = goodsService.getById(goodsId);
        if (goods.getIsListing().equals("0")&&(goods.getListingStatus().equals("1")||goods.getListingStatus().equals("2"))){
            throw new Exception("不可重复上架！");
        }
        LoginUser user = SecurityFrameworkUtils.getLoginUser();
        ShopMallPartners partners = baseMapper.selectById(goods.getPartnerId());
        if (!partners.getUserId().equals(user.getId())){
            return;
        }
       goods.setIsListing(goods.getIsListing().equals("0")?"1":"0");
        if (goods.getIsListing().equals("1")){

            //代表上架
            goods.setIsListing("0");
            //上架待审核
            goods.setListingStatus("1");
            goods.setRejectReason("");
        }else {
            //代表下架
            goods.setListingStatus("0");
            goods.setRejectReason("");
        }
        goodsService.updateById(goods);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delGoods(Long goodsId) throws Exception {
        ShopInspectionGoods goods = goodsService.getById(goodsId);
        if (goods.getIsListing().equals("1")){
            throw new Exception("删除请先下架！");
        }
        LoginUser user = SecurityFrameworkUtils.getLoginUser();
        ShopMallPartners partners = baseMapper.selectById(goods.getPartnerId());
        if (!partners.getUserId().equals(user.getId())){
            return;
        }
        goodsService.removeById(goodsId);
        LambdaQueryWrapper<InspectionGoodsSku> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(InspectionGoodsSku::getGoodsId,goodsId);
        skuService.remove(queryWrapper);
    }

    @Override
    public void editPartnerInfo(ShopMallPartners partners) {
        LoginUser user = SecurityFrameworkUtils.getLoginUser();
        ShopMallPartners partnersTmp = baseMapper.selectById(partners.getPartnerId());
        if (!partnersTmp.getUserId().equals(user.getId())){
            return;
        }
        List<String> addressList = AddressSplitter.splitAddress(partners.getAddress());
        partners.setProvince(addressList.get(0));
        partners.setCity(addressList.get(1));
        partners.setArea(addressList.get(2));
        this.updateById(partners);
    }

    @Override
    public PartnerVo getPartnerInfo(Long partnerId) {
        LoginUser user = SecurityFrameworkUtils.getLoginUser();
        ShopMallPartners partnersTmp = baseMapper.selectById(partnerId);
        if (!partnersTmp.getUserId().equals(user.getId())){
            return null;
        }
        ShopMallPartners partners = this.getById(partnerId);
        PartnerVo partnerVo =new PartnerVo();
        BeanUtils.copyProperties(partners,partnerVo);
        if (StringUtils.isNotEmpty(partnerVo.getShopImages())){
            partnerVo.setShopImageList(partnerVo.getShopImages().split(","));
        }
        return partnerVo;

    }

    @Override
    public PartnerBalance accountInfo(Long partnerId) {
        LoginUser user = SecurityFrameworkUtils.getLoginUser();
        ShopMallPartners partnersTmp = baseMapper.selectById(partnerId);
        if (!partnersTmp.getUserId().equals(user.getId())){
            return null;
        }
        LambdaQueryWrapper<PartnerBalance> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(PartnerBalance::getPartnerId,partnerId);
        return  partnerBalanceService.getOne(queryWrapper);
    }

    @Override
    public IPage<PartnerBalanceDetail> accountDetail(Page<PartnerBalanceDetail> page,Long partnerId, Integer pageNum, Integer pageSize) {
        LoginUser user = SecurityFrameworkUtils.getLoginUser();
        ShopMallPartners partnersTmp = baseMapper.selectById(partnerId);
        if (!partnersTmp.getUserId().equals(user.getId())){
            return null;
        }
        LambdaQueryWrapper<PartnerBalance> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(PartnerBalance::getPartnerId,partnerId);
        PartnerBalance one = partnerBalanceService.getOne(queryWrapper);

        LambdaQueryWrapper<PartnerBalanceDetail> queryWrapper1 =new LambdaQueryWrapper<>();
        queryWrapper1.eq(PartnerBalanceDetail::getPartnerBalanceId,one.getId()).orderByDesc(PartnerBalanceDetail::getChangeTime);
        return  detailService.page(page,queryWrapper1);
    }

    @Override
    public IPage<OrderAppDetail> orderList(Page<OrderAppDetail> page,Long partnerId,String phoneNum, String title) {
        return baseMapper.orderList(page,partnerId,phoneNum,title);
    }

    @Override
    public OrderAppDetail orderDetail(Long partnerId, Long orderId) {
        LoginUser user = SecurityFrameworkUtils.getLoginUser();
        ShopMallPartners partnersTmp = baseMapper.selectById(partnerId);
        if (!partnersTmp.getUserId().equals(user.getId())){
            return null;
        }
        OrderInfo orderInfo = orderService.getById(orderId);
        if (!orderInfo.getPartnerId().equals(partnerId)){
            return null;
        }
        ShopInspectionGoods goods = goodsService.getById(orderInfo.getGoodsId());
        OrderAppDetail  orderDetail =new OrderAppDetail();
        orderDetail.setGoodsId(orderInfo.getGoodsId());
        orderDetail.setGoodsTitle(orderInfo.getGoodsTitle()+ (StringUtils.isNotEmpty(orderInfo.getSkuName())?"-"+orderInfo.getSkuName():""));
        orderDetail.setGoodsImage(goods.getImage());
        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.setReduceMoney(orderInfo.getReduceMoney());
        orderDetail.setValidationTime(orderInfo.getValidationTime());
        AdminUserDO buyUser = userService.getUser(orderInfo.getUserId());
        orderDetail.setBuyUserName(buyUser.getNickname());
        orderDetail.setBuyUserPhone(buyUser.getMobile());
        if(ObjectUtil.isNotEmpty(orderInfo.getUserCarId())){
            ShopUserCar userCar = userCarService.getById(orderInfo.getUserCarId());
            orderDetail.setCarNum(userCar.getCarNo());
        }
        return orderDetail;
    }

    @Override
    public Long   orderDetailByCode(Long partnerId, String code) throws Exception {
        LambdaQueryWrapper<OrderInfo> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderInfo::getAccessCode,code);
        OrderInfo one = orderService.getOne(queryWrapper);
        if (ObjectUtil.isEmpty(one)){
            throw new Exception("核销码不存在");
        }
        return  one.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void takeOut(Long partnerId, Long orderId,Long workId,String carNum) throws Exception {
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        AdminUserDO user = userService.getUser(loginUser.getId());
        ShopMallPartners partnersTmp = baseMapper.selectById(partnerId);
        if (!partnersTmp.getUserId().equals(user.getId())){
            return;
        }
        OrderInfo orderInfo = orderService.getById(orderId);
        if (!orderInfo.getPartnerId().equals(partnerId)){
            throw new Exception("您无核销权限");
        }
        if (!orderInfo.getOrderStatus().equals("1")&&!ObjectUtil.isEmpty(orderInfo.getValidationTime())){
            throw new Exception("已核销请不要重复核销");
        }
        //处理订单信息
        orderInfo.setOrderStatus("2");
        orderInfo.setValidationTime(new Date());
        orderInfo.setValidationUserId(user.getId());
        orderInfo.setValidationRealName(user.getNickname());
        orderService.updateById(orderInfo);
        //追加订单明细记录
        orderInfoDetailService.save(new OrderInfoDetail(orderInfo.getId(),"核销成功",new Date(),orderInfo.getPayMoney(),"1"));
        //处理商家收益
        partnerBalanceService.addSellBalance(orderInfo.getPartnerId(),orderInfo.getPayMoney()+orderInfo.getBalance(),orderInfo.getGoodsTitle());
        ShopInspectionGoods goods = goodsService.getById(orderInfo.getGoodsId());
        //开始检测信息
        InspectionInfo info =new InspectionInfo();
        info.setUserId(orderInfo.getUserId());
        info.setPartnerId(orderInfo.getPartnerId());
        info.setInspectionOrderId(orderInfo.getId());
        info.setCarNum(carNum);
        info.setCategoryId(goods.getGoodsCategoryId());
        info.setYear(DateUtil.format(new Date(),"yyyy"));
        info.setMonth(DateUtil.format(new Date(),"yyyy-MM"));
        info.setDay(DateUtil.format(new Date(),"yyyy-MM-dd"));
        info.setStartTime(new Date());
        info.setStatus("0");
        //获取修理工信息
        PartnerWorker worker = partnerWorkerService.getById(workId);
        AdminUserDO sysUser = userService.getUser(worker.getUserId());
        info.setWorkerName(sysUser.getNickname());
        info.setWorkerPhone(sysUser.getMobile());
        info.setWorkerAvatar(sysUser.getAvatar());
        info.setWorkId(workId);
        info.setCustomerSource("线上客户");
        //20240327 追加字段
        info.setOtherPhone(orderInfo.getOtherPhone());
        info.setDriverLicenesImg(orderInfo.getDriverLicenesImg());
        info.setIsPayOnline(orderInfo.getIsPayOnline());
        info.setIsPickCar(orderInfo.getIsPickCar());
        info.setRemark(orderInfo.getRemark());
        info.setCarNum(orderInfo.getCarNo());
        inspectionInfoService.save(info);
        //增加客户信息
        LambdaQueryWrapper<PartnerCustomerInfo> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(PartnerCustomerInfo::getPartnerId,partnerId).eq(PartnerCustomerInfo::getUserId,orderInfo.getUserId());
        PartnerCustomerInfo customerInfo = customerInfoService.getOne(queryWrapper);
        if (ObjectUtil.isEmpty(customerInfo)){
            AdminUserDO buyUser = userService.getUser(orderInfo.getUserId());
            customerInfo =new PartnerCustomerInfo();
            customerInfo.setPartnerId(partnerId);
            customerInfo.setUserId(buyUser.getId());
            customerInfo.setCustomerPhone(buyUser.getMobile());
            customerInfo.setCustomerName(buyUser.getNickname());
            customerInfo.setSex(String.valueOf(buyUser.getSex()));
            customerInfo.setUserAge(18);
            customerInfoService.save(customerInfo);

        }
        InspectionStepInfo stepInfo =new InspectionStepInfo();
        stepInfo.setInspectionInfoId(info.getId().intValue());
        stepInfo.setContent("检测开始");
        stepInfo.setTitle("检测开始");
        this.addStepInfo(stepInfo);
        //开始检测短信发送
        // 获取当前日期和时间
        LocalDateTime currentTime = LocalDateTime.now();

        // 定义指定格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年M月d日H:mm分");

        // 将当前时间转换为指定格式
        String formattedTime = currentTime.format(formatter);
        try {
            SendSmsUtil.sendMsgCommon(new String[]{formattedTime},orderInfo.getPhonenumber(),"1400852709","机动车管家小程序","1961713");
        }catch (Exception ignored){
            log.error(ignored.getMessage());
        }

    }

    @Override
    public void addWorker(Long partnerId, String realName, String phoneNum,Long postId) throws Exception {
        try {
            LoginUser user = SecurityFrameworkUtils.getLoginUser();
            ShopMallPartners partnersTmp = baseMapper.selectById(partnerId);
            if (!partnersTmp.getUserId().equals(user.getId())){
                return;
            }

            AdminUserDO workUser = userService.getUserByMobile(phoneNum);
            if (workUser.getMobile().equals(phoneNum)){
                LambdaQueryWrapper<PartnerWorker> queryWrapper1 =new LambdaQueryWrapper<>();
                queryWrapper1.eq(PartnerWorker::getUserId,workUser.getId());
                PartnerWorker one = partnerWorkerService.getOne(queryWrapper1);
                if (ObjectUtil.isNotEmpty(one)) {
                    return;
                }
                PartnerWorker partnerWorker =new PartnerWorker();
                partnerWorker.setPartnerId(partnerId);
                partnerWorker.setUserId(workUser.getId());
                partnerWorker.setWorkPhone(workUser.getMobile());
                partnerWorkerService.save(partnerWorker);

                // 删除用户与岗位关联
                userPostMapper.deleteByUserId(workUser.getId());
                UserPostDO userPostDO = new UserPostDO();
                userPostDO.setUserId(workUser.getId());
                userPostDO.setPostId(postId);
                userPostMapper.insert(userPostDO);

                //更新员工真实姓名
                UserSaveReqVO userSaveReqVO = new UserSaveReqVO();
                userSaveReqVO.setId(workUser.getId());
                userSaveReqVO.setNickname(realName);

                userService.updateUser(userSaveReqVO);
            }else {
                throw new Exception("");
            }

        }catch (Exception e){
            throw new Exception("输入信息有误，添加失败");
        }

    }

    @Override
    public List<PartnerWorker> getWorkList(Long partnerId,Long postId,String workName,String phoneNum) {
        return baseMapper.getWorkList(partnerId,postId,workName,phoneNum);
    }

    @Override
    public IPage<PartnerWorker> pageWorkList(Long partnerId, Long postId, String workName, String phoneNum, Page<LabelRespVO> page) {
        return baseMapper.pageWorkList(partnerId,postId,workName,phoneNum,page);
    }

    @Override
    public void delWorker(Long partnerId, Long workId) {
        LoginUser user = SecurityFrameworkUtils.getLoginUser();
        ShopMallPartners partnersTmp = baseMapper.selectById(partnerId);
        if (!partnersTmp.getUserId().equals(user.getId())){
            return;
        }
        partnerWorkerService.removeById(workId);
    }

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

    @Override
    public InspectionInfoVo inspectionDetail(Long inspectionInfoId) {
        InspectionInfo info = inspectionInfoService.getById(inspectionInfoId);
        OrderInfo order = orderService.getById(info.getInspectionOrderId());
        AdminUserDO buyUser = userService.getUser(info.getUserId());
        AdminUserDO worker = userService.getUser(info.getWorkId());
        InspectionInfoVo res =new  InspectionInfoVo();
        BeanUtils.copyProperties(order,res);
        res.setInspectionId(info.getId());
        res.setWorkerAvatar(Optional.ofNullable(worker.getAvatar()).orElse(null));
        res.setWorkerName(Optional.ofNullable(worker.getNickname()).orElse(null));
        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.setStatus(info.getStatus());
        res.setGoodsId(order.getGoodsId());
        res.setGoodsPrice(order.getGoodsPrice());
        res.setGoodsName(order.getGoodsTitle());
        res.setIsOnline(order.getIsOnline());
        res.setIsRetrial(info.getIsRetrial());
        res.setIsPass(info.getIsPass());
        res.setRemark(info.getRemark());
        res.setMakeCert(info.getMakeCert());
        res.setOrderStatus(order.getOrderStatus());
        ShopInspectionGoods goods = goodsService.getById(order.getGoodsId());
        res.setGoodsImage(goods.getImage());
        LambdaQueryWrapper<InspectionStepInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(InspectionStepInfo::getInspectionInfoId,inspectionInfoId).orderByAsc(InspectionStepInfo::getStepNum);
        List<InspectionStepInfo> list = stepInfoService.list(queryWrapper);
        if (CollectionUtil.isNotEmpty(list)){
            res.setStepInfos(list);
        }
        ShopInspectionCategory category = categoryService.getById(info.getCategoryId());
        res.setCarType(category.getCategoryName());
        return res;
    }

    @Override
    public List<InspectionInfo> workerInspectionList(Long workerId, String status, String searchValue) {
        return baseMapper.workerInspectionList(workerId,status,searchValue);
    }

    @Override
    public void addStepInfo(InspectionStepInfo stepInfo) {

        LambdaQueryWrapper<InspectionStepInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(InspectionStepInfo::getInspectionInfoId,stepInfo.getInspectionInfoId()).orderByDesc(InspectionStepInfo::getStepNum).last("limit 1");
        InspectionStepInfo list = stepInfoService.getOne(queryWrapper);
        if (ObjectUtil.isNotEmpty(list)){
            stepInfo.setStepNum(list.getStepNum()+1);
        }else {
            stepInfo.setStepNum(1);
        }
        stepInfoService.save(stepInfo);
    }

    @Override
    public void stopInspection(InspectionInfo info) throws Exception {
        InspectionInfo infoOld = inspectionInfoService.getById(info.getId());
        if (infoOld.getStatus().equals("1")){
            throw new Exception("已结束");
        }
        if (info.getIsPass().equals("0")&&StringUtils.isNotEmpty(info.getIsRetrial())&&info.getIsRetrial().equals("1")){
            //重审
            infoOld.setStatus("0");
            infoOld.setIsPass(info.getIsPass());
            infoOld.setRemark(info.getRemark());
            infoOld.setIsRetrial("1");
            inspectionInfoService.updateById(infoOld);
            InspectionStepInfo stepInfo =new InspectionStepInfo();
            stepInfo.setInspectionInfoId(info.getId().intValue());
            stepInfo.setContent(info.getRemark());
            stepInfo.setTitle("检测重审");
            this.addStepInfo(stepInfo);
        }else {
            infoOld.setStatus("1");
            infoOld.setIsPass(info.getIsPass());
            infoOld.setRemark(info.getRemark());
            infoOld.setEndTime(new Date());
            inspectionInfoService.updateById(infoOld);
            InspectionStepInfo stepInfo =new InspectionStepInfo();
            stepInfo.setContent(info.getRemark());
            if (StringUtils.isNotEmpty(infoOld.getIsPass())&&infoOld.getIsPass().equals("1")){
                stepInfo.setTitle("检测结束-检测通过");

            }else {
                stepInfo.setTitle("检测结束-检测不合格");

            }
            stepInfo.setInspectionInfoId(info.getId().intValue());
            this.addStepInfo(stepInfo);


            try {
                OrderInfo orderInfo = orderService.getById(infoOld.getInspectionOrderId());
                //开始检测短信发送
                // 获取当前日期和时间
                LocalDateTime currentTime = LocalDateTime.now();

                // 定义指定格式
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年M月d日H:mm分");

                // 将当前时间转换为指定格式
                String formattedTime = currentTime.format(formatter);
                if (PhoneValidator.isValid(orderInfo.getPhonenumber())){
                    if (StringUtils.isNotEmpty(infoOld.getIsPass())&&infoOld.getIsPass().equals("1")){
                        SendSmsUtil.sendMsgCommon(new String[]{Optional.ofNullable(orderInfo.getCarNo()).orElse(" "),infoOld.getWorkerName(),infoOld.getWorkerPhone()},orderInfo.getPhonenumber(),"1400852709","机动车管家小程序","2112788");

                    }else {
                        SendSmsUtil.sendMsgCommon(new String[]{Optional.ofNullable(orderInfo.getCarNo()).orElse(" "),formattedTime,infoOld.getWorkerName()+""+infoOld.getWorkerPhone()},orderInfo.getPhonenumber(),"1400852709","机动车管家小程序","2112806");

                    }

                }
            }catch (Exception ignored){
                log.error(ignored.getMessage());
            }
        }
    }

    @Override
    public void makeCertOk(Long inspectionId) {
        InspectionInfo infoOld = inspectionInfoService.getById(inspectionId);
        infoOld.setMakeCert("1");
        inspectionInfoService.updateById(infoOld);
        inspectionInfoService.updateById(infoOld);
        InspectionStepInfo stepInfo =new InspectionStepInfo();
        stepInfo.setContent("制证完成");
        stepInfo.setTitle("制证完成");
        stepInfo.setInspectionInfoId(infoOld.getId().intValue());
        this.addStepInfo(stepInfo);
    }

    @Override
    public IPage<InspectionAppointment> getAppointmentList(Page<InspectionAppointment> page,Long partnerId,String phoneNum) {
        return  appointmentService.getAppointmentList(page,partnerId,phoneNum);
    }

    @Override
    public IPage<OrderInfo> validationList(Page<OrderInfo> page, Long partnerId,String searchValue) {

        return baseMapper.validationList(page,partnerId,searchValue);
    }

    @Override
    public void sendCoupon(ShopCouponTemplate template) throws Exception {
        LoginUser user = SecurityFrameworkUtils.getLoginUser();
        ShopMallPartners partnersTmp = baseMapper.selectById(template.getPartnerId());
        if (!partnersTmp.getUserId().equals(user.getId())){
            return;
        }
        if (StringUtils.isEmpty(template.getRoleKey())){
            throw new Exception("请选择角色信息");
        }
        if(template.getEventsStartTime().after(template.getExpirationTime())){
            throw new Exception("活动开始时间需要在生效时间之前");
        }
        if(template.getEventsEndTime().before(template.getStartTime())){
            throw new Exception("活动结束时间需要在开始时间之前");
        }
        if(template.getEventsStartTime().after(template.getEventsEndTime())){
            throw new Exception("结束时间要在开始时间之后");
        }
        if(template.getStartTime().after(template.getExpirationTime())){
            throw new Exception("结束时间要在开始时间之后");
        }
        template.setBindMoudle("检测项目现金券");
        template.setCouponType("cash");
        template.setBindPartnerId(template.getPartnerId());
        if (ObjectUtil.isEmpty(template.getEventsEndTime())){
            template.setStartTime(new Date());
            template.setEventsEndTime(DateUtil.parse("2888-08-08"));
        }
        templateService.save(template);
    }

    @Override
    public IPage<ShopCouponTemplate> listCoupon(Page<ShopCouponTemplate> page,Long partnerId, String searchValue) {
        LambdaQueryWrapper<ShopCouponTemplate> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(ShopCouponTemplate::getPartnerId,partnerId).eq(ShopCouponTemplate::getBindMoudle,"检测项目现金券")
                .eq(StringUtils.isNotEmpty(searchValue),ShopCouponTemplate::getTitle,searchValue).orderByDesc(TenantBaseDO::getCreateTime);

        return templateService.listCoupon(page,partnerId,searchValue);
    }

    @Override
    public void delCoupon(Long partnerId,Long id) {
        LoginUser user = SecurityFrameworkUtils.getLoginUser();
        ShopMallPartners partnersTmp = baseMapper.selectById(partnerId);
        if (!partnersTmp.getUserId().equals(user.getId())){
            return;
        }
        templateService.deleteShopCouponTemplateById(id);
    }
    @Override
    public void designatePickCarWorker(Long pickCarId,Long workerId){
        InspectionPickCar pickCar = pickCarService.getById(pickCarId);
        pickCar.setWorkerId(workerId);
        pickCarService.updateById(pickCar);
    }

    @Override
    public IPage<InspectionPickCar> getPickCarList(Page page,Long partnerId, String phoneNum,String pickStatus) {

        return  baseMapper.getPickCarList(page,partnerId,phoneNum,pickStatus);
    }

    @Override
    public InspectionPickCar getPickCarDetail(Long dataId) {
        InspectionPickCar pickCar = pickCarService.getById(dataId);
        //获取已经指派了的修理工
        if (null!=pickCar.getWorkerId()){
            PartnerWorker worker = partnerWorkerService.getById(pickCar.getWorkerId());
            AdminUserDO user = userService.getUser(worker.getUserId());
            pickCar.setWorkerName(user.getNickname());
            pickCar.setWorkerPhone(user.getMobile());
            pickCar.setWorkerAvatar(user.getAvatar());
        }
        return pickCar;
    }

    @Override
    public IPage<InspectionPickCar> getPickCarListOfWorker(Page<InspectionPickCar> page,Long workerId, String phoneNum) {
        return  baseMapper.getPickCarListOfWorker(page,workerId,phoneNum);
    }

    @Override
    public JSONObject vehicleLicenseOCR(String imagePath) throws Exception {
        try {
            imagePath = imagePath.replace("undefined","");
            String s = VehicleLicenseOCR.dealFunction(imagePath);
            return JSONObject.parseObject(s);
        }catch (Exception e){
            throw new Exception("识别失败,请对准拍摄");
        }

    }

    @Override
    public void offlineCharging(InspectionInfoVo infoVo) {
        //当前登录用户
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        AdminUserDO user = userService.getUser(loginUser.getId());
        InspectionInfo info = inspectionInfoService.getById(infoVo.getInspectionId());
        OrderInfo orderInfo = orderService.getById(info.getInspectionOrderId());
        orderInfo.setPayType(infoVo.getPayType());
        if (infoVo.getPayType().equals("sz")){
            //赊账
            orderInfo.setOrderStatus("0");
            orderInfo.setReceivablesAccount(infoVo.getReceivablesAccount());
            orderInfo.setPayMoney(infoVo.getPayMoney());
            orderInfo.setReduceMoney(infoVo.getReduceMoney());
            orderInfo.setPayRemark(infoVo.getPayRemark());
            orderService.updateById(orderInfo);
            //追加订单明细记录
            orderInfoDetailService.save(new OrderInfoDetail(orderInfo.getId(),"线下订单赊账",new Date(),0L,"1"));
        }else{
            orderInfo.setOrderStatus("2");
            orderInfo.setReceivablesAccount(infoVo.getReceivablesAccount());
            orderInfo.setPayMoney(infoVo.getPayMoney());
            orderInfo.setPayTime(new Date());
            orderInfo.setReduceMoney(infoVo.getReduceMoney());
            orderInfo.setPayRemark(infoVo.getPayRemark());
            orderInfo.setValidationTime(new Date());
            orderInfo.setValidationUserId(user.getId());
            orderInfo.setValidationRealName(user.getNickname());
            orderService.updateById(orderInfo);
            //追加订单明细记录
            orderInfoDetailService.save(new OrderInfoDetail(orderInfo.getId(),"线下订单支付并核销",new Date(),orderInfo.getPayMoney(),"1"));
        }

    }

    @Override
    public String workOrderView(Long inspectionId) {
        InspectionInfo inspectionInfo = inspectionInfoService.getById(inspectionId);
        OrderInfo orderInfo = orderService.getById(inspectionInfo.getInspectionOrderId());
        AdminUserDO buyUser = userService.getUser(inspectionInfo.getUserId());
        PartnerWorker worker = partnerWorkerService.getById(inspectionInfo.getWorkId());
        ShopMallPartners partner = this.getById(orderInfo.getPartnerId());
        AdminUserDO workerUser = userService.getUser(worker.getUserId());
        String inspection_work_order = configService.selectConfigByKey("inspection_work_order");
        String payType = "未知";
        if (StringUtils.isNotEmpty(orderInfo.getPayType())){
            DictDataDO payType1 = dictDataService.getDictData("pay_type", orderInfo.getPayType());
            payType = payType1.getLabel();
        }
        inspection_work_order = inspection_work_order.replaceAll("title",Optional.ofNullable(partner.getPartnerName()).orElse(""));
        inspection_work_order = inspection_work_order.replaceAll("buyAdress",Optional.ofNullable(inspectionInfo.getUserAddress()).orElse(""));
        inspection_work_order= inspection_work_order.replaceAll("buyName",Optional.ofNullable(buyUser.getNickname()).orElse("未知"));
        inspection_work_order= inspection_work_order.replaceAll("buyPhone",Optional.ofNullable(buyUser.getMobile()).orElse("未知"));
        inspection_work_order=inspection_work_order.replaceAll("timeStr",null!=inspectionInfo.getEndTime()?DateUtil.format(inspectionInfo.getEndTime(),"yyyy-MM-dd"):"未结束");
        inspection_work_order=inspection_work_order.replaceAll("carNum",Optional.ofNullable(inspectionInfo.getCarNum()).orElse(""));
        inspection_work_order=inspection_work_order.replaceAll("carIdNo",Optional.ofNullable(inspectionInfo.getCarIdNo()).orElse(""));
        inspection_work_order= inspection_work_order.replaceAll("goodsTitle",orderInfo.getGoodsTitle());
        inspection_work_order=inspection_work_order.replaceAll("skuName",orderInfo.getSkuName());
        inspection_work_order=inspection_work_order.replaceAll("goodsPrice",String.valueOf(orderInfo.getGoodsPrice()/100));
        inspection_work_order=inspection_work_order.replaceAll("reduceMoney",String.valueOf(null!=orderInfo.getReduceMoney()?orderInfo.getReduceMoney()/100:0));
        inspection_work_order= inspection_work_order.replaceAll("realPayMoney",String.valueOf(null!=orderInfo.getRealPayMoney()?orderInfo.getRealPayMoney()/100:0));
        inspection_work_order=inspection_work_order.replaceAll("payType",payType);
        inspection_work_order=inspection_work_order.replaceAll("workName",StringUtils.isNotEmpty(workerUser.getNickname())?workerUser.getNickname():workerUser.getMobile());
        inspection_work_order=inspection_work_order.replaceAll("payRemark",Optional.ofNullable(orderInfo.getPayRemark()).orElse(""));
        inspection_work_order= inspection_work_order.replaceAll("buyName",Optional.ofNullable(buyUser.getNickname()).orElse("未知"));
        return inspection_work_order;
    }

    @Override
    public List<PostDO> inspectionPostInfo() {
        PostPageReqVO post =new PostPageReqVO();
        post.setCode("inspection");

        List<PostDO>  postPage = postService.listPostPage(post);

//        List<PostDO> sysPosts = postPage.getList();
//        PostDO sysPost = new PostDO();
//        sysPost.setId(null);
//        sysPost.setName("全部");
//        sysPosts.add(sysPost);
        return postPage;
    }

    @Override
    public Map<String,Double> staticsTable1(Long partnerId,String startTime,String endTime) {
        if (StringUtils.isEmpty(startTime)){
            startTime = DateUtil.format(new Date(), "yyyy-MM-dd");
            endTime = DateUtil.format(new Date(), "yyyy-MM-dd");
        }
        startTime = startTime + " 00:00:00";
        endTime = endTime + " 23:59:59";
        Map<String, Double> map = baseMapper.staticsTable1(partnerId, startTime, endTime);
        return map;
    }
    @Override
    public Map<String,Double> newStaticsTable1(String startTime,String endTime) {
        if (StringUtils.isEmpty(startTime)){
            startTime = DateUtil.format(new Date(), "yyyy-MM-dd");
            endTime = DateUtil.format(new Date(), "yyyy-MM-dd");
        }
        startTime = startTime + " 00:00:00";
        endTime = endTime + " 23:59:59";
        Map<String, Double> map = baseMapper.newStaticsTable1(startTime, endTime);
        return map;
    }

    @Override
    public Map<String, Integer> staticsTable2(Long partnerId, String startTime, String endTime) {
        if (StringUtils.isEmpty(startTime)){
            startTime = DateUtil.format(new Date(), "yyyy-MM-dd");
            endTime = DateUtil.format(new Date(), "yyyy-MM-dd");
        }
        startTime = startTime + " 00:00:00";
        endTime = endTime + " 23:59:59";
        Map<String, Integer> map = baseMapper.staticsTable2(partnerId, startTime, endTime);
        return map;
    }
    @Override
    public Map<String, Integer> newStaticsTable2(String startTime, String endTime) {
        if (StringUtils.isEmpty(startTime)){
            startTime = DateUtil.format(new Date(), "yyyy-MM-dd");
            endTime = DateUtil.format(new Date(), "yyyy-MM-dd");
        }
        startTime = startTime + " 00:00:00";
        endTime = endTime + " 23:59:59";
        Map<String, Integer> map = baseMapper.newStaticsTable2( startTime, endTime);
        return map;
    }

    @Override
    public List<Map<String, Object>> staticsTable3(Long partnerId, String startTime, String endTime) {
        if (StringUtils.isEmpty(startTime)){
            startTime = DateUtil.format(new Date(), "yyyy-MM-dd");
            endTime = DateUtil.format(new Date(), "yyyy-MM-dd");
        }
        startTime = startTime + " 00:00:00";
        endTime = endTime + " 23:59:59";
        List<Map<String, Object>> res = baseMapper.staticsTable3(partnerId, startTime, endTime);
        return res;
    }
    @Override
    public List<Map<String, Object>> newStaticsTable3(String startTime, String endTime) {
        if (StringUtils.isEmpty(startTime)){
            startTime = DateUtil.format(new Date(), "yyyy-MM-dd");
            endTime = DateUtil.format(new Date(), "yyyy-MM-dd");
        }
        startTime = startTime + " 00:00:00";
        endTime = endTime + " 23:59:59";
        List<Map<String, Object>> res = baseMapper.newStaticsTable3(startTime, endTime);
        return res;
    }

    @Override
    public List<Map<String, Object>> staticsTable3Detail(Long partnerId, String startTime, String endTime, String remark) {
        if (StringUtils.isEmpty(startTime)){
            startTime = DateUtil.format(new Date(), "yyyy-MM-dd");
            endTime = DateUtil.format(new Date(), "yyyy-MM-dd");
        }
        startTime = startTime + " 00:00:00";
        endTime = endTime + " 23:59:59";
        List<Map<String, Object>> res = baseMapper.staticsTable3Detail(partnerId, startTime, endTime,remark);
        return res;
    }

    @Override
    public List<Map<String, Object>> staticsTable4(Long partnerId, String startTime, String endTime) {
        if (StringUtils.isEmpty(startTime)){
            startTime = DateUtil.format(new Date(), "yyyy-MM-dd");
            endTime = DateUtil.format(new Date(), "yyyy-MM-dd");
        }
        startTime = startTime + " 00:00:00";
        endTime = endTime + " 23:59:59";
        List<Map<String, Object>> res = baseMapper.staticsTable4(partnerId, startTime, endTime);
        return res;
    }

    @Override
    public List<Map<String, Object>> staticsTable5(Long partnerId, String startTime, String endTime) {
        if (StringUtils.isEmpty(startTime)){
            startTime = DateUtil.format(new Date(), "yyyy-MM-dd");
            endTime = DateUtil.format(new Date(), "yyyy-MM-dd");
        }
        startTime = startTime + " 00:00:00";
        endTime = endTime + " 23:59:59";
        List<Map<String, Object>> res = baseMapper.staticsTable5(partnerId, startTime, endTime);
        return res;
    }

}
