package com.sqx.modules.artificer.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.baidu.aip.face.AipFace;
import com.baidu.aip.face.MatchRequest;
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.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.sqx.common.utils.*;
import com.sqx.face.FaceMain;
import com.sqx.map.CommonMapUtils;
import com.sqx.modules.app.entity.UserMoney;
import com.sqx.modules.app.service.UserMoneyService;
import com.sqx.modules.artificer.dao.*;
import com.sqx.modules.artificer.entity.*;
import com.sqx.modules.artificer.service.ArtificerService;
import com.sqx.modules.artificer.service.ArtificerTimeService;
import com.sqx.modules.artificer.service.CollectArtificerService;
import com.sqx.modules.common.dao.CommonInfoDao;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.file.utils.FileUploadUtils;
import com.sqx.modules.message.entity.MessageInfo;
import com.sqx.modules.message.service.MessageService;
import com.sqx.modules.pay.dao.CashOutDao;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static com.sqx.modules.utils.PeriodUtil.*;


@Service
public class ArtificerServiceImpl extends ServiceImpl<ArtificerDao, Artificer> implements ArtificerService {

    @Autowired
    private ArtificerDao artificerDao;

    @Autowired
    private CollectArtificerService collectArtificerService;
    @Autowired
    private OrdersDao ordersDao;
    @Autowired
    private CashOutDao cashOutDao;
    @Autowired
    private UserMoneyService userMoneyService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private ArtificerTimeService artificerTimeService;
    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private UserRechargeDao userRechargeDao;
    @Autowired
    private  CommonInfoDao commonInfoDao;

    @Autowired
    private FaceMain faceMain;

    @Override
    public Result selectArtificerList(Integer page, Integer limit, Long massageTypeId,String artificerName,
                                      String longitude,String latitude,Integer sort,Integer authentication,
                                      Integer by,Integer status,String city,Long classifyId,String phone,Integer user, Integer isStart,Integer technicianType,String isBack){
        Page<Artificer> pages=new Page<>(page,limit);

        if(StringUtils.isEmpty(longitude)){
            longitude = "125.430896";
        }
        if(StringUtils.isEmpty(latitude)){
            latitude = "43.880798";
        }
        if(StringUtils.isEmpty(city)||StringUtils.equals("请选择城市",city)){
            city = "长春市";
        }



        IPage<Artificer> artificerIPage = baseMapper.selectArtificerList(pages, massageTypeId, artificerName,
                longitude, latitude, sort, authentication, by, status, city, classifyId,phone,user,isStart,technicianType,isBack);
        List<Artificer> records = artificerIPage.getRecords();
        String value = commonInfoService.findOne(392).getValue();
        if("30".equals(value)){
            SimpleDateFormat sdfHour=new SimpleDateFormat("HH");
            SimpleDateFormat sdfMinute=new SimpleDateFormat("mm");
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat md = new SimpleDateFormat("MM-dd");
            Date dateTime = new Date();
            Calendar calendar=Calendar.getInstance();
            String hour = sdfHour.format(dateTime);
            String minute = sdfMinute.format(dateTime);
            int minuteInt = Integer.parseInt(minute);
            int hourInt = Integer.parseInt(hour);
            StringBuilder stringBuilders=new StringBuilder();
            if(minuteInt>=30){
                if(hourInt==23){
                    hourInt=0;
                    minuteInt=30;
                }else{
                    minuteInt=30;
                    hourInt=hourInt+1;
                }
            }else{
                hourInt=hourInt+1;
                minuteInt=0;
            }

            if(hourInt<10){
                stringBuilders.append("0").append(hourInt);
            }else{
                stringBuilders.append(hourInt);
            }
            stringBuilders.append(":");
            if(minuteInt<10){
                stringBuilders.append("0").append(minuteInt);
            }else{
                stringBuilders.append(minuteInt);
            }

            for(Artificer artificer:records){
                calendar=Calendar.getInstance();
                String date = simpleDateFormat.format(dateTime);
                String oldDate = simpleDateFormat.format(dateTime);
                hour = sdfHour.format(dateTime);
                minute = sdfMinute.format(dateTime);
                minuteInt = Integer.parseInt(minute);
                hourInt = Integer.parseInt(hour);
                if(minuteInt>=30){
                    if(hourInt==23){
                        hourInt=0;
                        minuteInt=30;
                        calendar.add(Calendar.DAY_OF_MONTH,1);
                        date = simpleDateFormat.format(calendar.getTime());
                    }else{
                        minuteInt=30;
                        hourInt=hourInt+1;
                    }
                }else{
                    hourInt=hourInt+1;
                    minuteInt=0;
                }
                while (true){
                    StringBuilder stringBuilder=new StringBuilder();
                    if(hourInt<10){
                        stringBuilder.append("0").append(hourInt);
                    }else{
                        stringBuilder.append(hourInt);
                    }
                    stringBuilder.append(":");
                    if(minuteInt<10){
                        stringBuilder.append("0").append(minuteInt);
                    }else{
                        stringBuilder.append(minuteInt);
                    }
                    ArtificerTime artificerTime = artificerTimeService.getOne(new QueryWrapper<ArtificerTime>().eq("artificer_id", artificer.getArtificerId()).eq("artificer_date", date).eq("artificer_time", stringBuilder.toString()).last(" limit 1"));
                    if(artificerTime==null){
                        if(oldDate.equals(date)){
                            artificer.setTime(stringBuilder.toString());
                        }else{
                            artificer.setTime(md.format(calendar.getTime())+" "+stringBuilder.toString());
                        }
                        if(artificer.getStatus()!=null && artificer.getStatus()==2){
                            artificer.setState(3);
                        }else{
                            if(stringBuilder.toString().equals(stringBuilders.toString())){
                                artificer.setState(1);
                            }else{
                                artificer.setState(2);
                            }
                        }

                        break;
                    }
                    if(minuteInt==30){
                        if(hourInt==23){
                            hourInt=0;
                            minuteInt=0;
                            calendar.add(Calendar.DAY_OF_MONTH,1);
                            date = simpleDateFormat.format(calendar.getTime());
                        }else{
                            minuteInt=0;
                            hourInt=hourInt+1;
                        }
                    }else{
                        minuteInt=30;
                    }
                }
                //2.服务开始前及结束后预留出行时间
                //精油往后延30 分钟，中医往后延60 分钟
                if(artificer.getClassifyId()==95){
                    String time = artificer.getTime();
                    //在精油的基础上加30 分钟就是中医~~
                    DateTime dateTime1 = DateUtil.offsetMinute(DateUtil.parse(time), 30);
                    artificer.setTime(DateUtil.format(dateTime1,"HH:mm"));
                }
            }
        }else{

            SimpleDateFormat sdf=new SimpleDateFormat("HH");

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat md = new SimpleDateFormat("MM-dd");
            Date dateTime = new Date();
            String date = simpleDateFormat.format(dateTime);
            String oldDate = simpleDateFormat.format(dateTime);
            String time = sdf.format(dateTime);
            String times="";
            if("23".equals(time)){
                time="00";
                times=time+":30";
            }else{
                time=String.valueOf(Integer.parseInt(time)+1);
                times=time+":30";
            }
            String nowTimes=times;

            for(Artificer artificer:records){
                Calendar calendar=Calendar.getInstance();
                date = simpleDateFormat.format(dateTime);
                oldDate = simpleDateFormat.format(dateTime);
                time = sdf.format(dateTime);
                times="";
                if("23".equals(time)){
                    time="00";
                    times=time+":30";
                    calendar.add(Calendar.DAY_OF_MONTH,1);
                    date = simpleDateFormat.format(calendar.getTime());
                }else{
                    time=String.valueOf(Integer.parseInt(time)+1);
                    times=time+":30";
                }
                while (true){
                    ArtificerTime artificerTime = artificerTimeService.getOne(new QueryWrapper<ArtificerTime>().eq("artificer_id", artificer.getArtificerId()).eq("artificer_date", date).eq("artificer_time", times));
                    if(artificerTime==null){
                        if(oldDate.equals(date)){
                            times=time+":00";
                            artificer.setTime(times);
                        }else{
                            times=time+":00";
                            artificer.setTime(md.format(calendar.getTime())+" "+times);
                        }
                        if(artificer.getStatus()!=null && artificer.getStatus()==2){
                            artificer.setState(3);
                        }else{
                            if(times.equals(nowTimes)){
                                artificer.setState(1);
                            }else{
                                artificer.setState(2);
                            }
                        }
                        break;
                    }
                    if("23".equals(time)){
                        time="00";
                        times=time+":30";
                        calendar.add(Calendar.DAY_OF_MONTH,1);
                        date = simpleDateFormat.format(calendar.getTime());
                    }else{
                        time=String.valueOf(Integer.parseInt(time)+1);
                        times=time+":30";
                    }
                }
            }
        }


        return Result.success().put("data",new PageUtils(artificerIPage));
    }

    @Override
    public Artificer selectArtificerById(Long userId,Long artificerId,String longitude,String latitude){
        if(userId!=null){
            CollectArtificer collectArtificer=new CollectArtificer();
            collectArtificer.setClassify(2);
            collectArtificer.setUserId(userId);
            collectArtificer.setArtificerId(artificerId);
            collectArtificerService.insertCollect(collectArtificer);
        }
        Artificer artificer = baseMapper.selectArtificerById(userId,artificerId,longitude,latitude);

        String value = commonInfoService.findOne(392).getValue();
        if("30".equals(value)){
            SimpleDateFormat sdfHour=new SimpleDateFormat("HH");
            SimpleDateFormat sdfMinute=new SimpleDateFormat("mm");
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat md = new SimpleDateFormat("MM-dd");
            Date dateTime = new Date();
            Calendar calendar=Calendar.getInstance();
            String hour = sdfHour.format(dateTime);
            String minute = sdfMinute.format(dateTime);
            int minuteInt = Integer.parseInt(minute);
            int hourInt = Integer.parseInt(hour);
            StringBuilder stringBuilders=new StringBuilder();
            if(minuteInt>=30){
                if(hourInt==23){
                    hourInt=0;
                    minuteInt=30;
                }else{
                    minuteInt=30;
                    hourInt=hourInt+1;
                }
            }else{
                hourInt=hourInt+1;
                minuteInt=0;
            }

            if(hourInt<10){
                stringBuilders.append("0").append(hourInt);
            }else{
                stringBuilders.append(hourInt);
            }
            stringBuilders.append(":");
            if(minuteInt<10){
                stringBuilders.append("0").append(minuteInt);
            }else{
                stringBuilders.append(minuteInt);
            }

            calendar=Calendar.getInstance();
            String date = simpleDateFormat.format(dateTime);
            String oldDate = simpleDateFormat.format(dateTime);
            hour = sdfHour.format(dateTime);
            minute = sdfMinute.format(dateTime);
            minuteInt = Integer.parseInt(minute);
            hourInt = Integer.parseInt(hour);
            if(minuteInt>=30){
                if(hourInt==23){
                    hourInt=0;
                    minuteInt=30;
                    calendar.add(Calendar.DAY_OF_MONTH,1);
                    date = simpleDateFormat.format(calendar.getTime());
                }else{
                    minuteInt=30;
                    hourInt=hourInt+1;
                }
            }else{
                hourInt=hourInt+1;
                minuteInt=0;
            }
            while (true){
                StringBuilder stringBuilder=new StringBuilder();
                if(hourInt<10){
                    stringBuilder.append("0").append(hourInt);
                }else{
                    stringBuilder.append(hourInt);
                }
                stringBuilder.append(":");
                if(minuteInt<10){
                    stringBuilder.append("0").append(minuteInt);
                }else{
                    stringBuilder.append(minuteInt);
                }
                ArtificerTime artificerTime = artificerTimeService.getOne(new QueryWrapper<ArtificerTime>().eq("artificer_id", artificer.getArtificerId()).eq("artificer_date", date).eq("artificer_time", stringBuilder.toString()));
                if(artificerTime==null){
                    if(oldDate.equals(date)){
                        artificer.setTime(stringBuilder.toString());
                    }else{
                        artificer.setTime(md.format(calendar.getTime())+" "+stringBuilder.toString());
                    }
                    if(artificer.getStatus()!=null && artificer.getStatus()==2){
                        artificer.setState(3);
                    }else{
                        if(stringBuilder.toString().equals(stringBuilders.toString())){
                            artificer.setState(1);
                        }else{
                            artificer.setState(2);
                        }
                    }

                    break;
                }
                if(minuteInt==30){
                    if(hourInt==23){
                        hourInt=0;
                        minuteInt=0;
                        calendar.add(Calendar.DAY_OF_MONTH,1);
                        date = simpleDateFormat.format(calendar.getTime());
                    }else{
                        minuteInt=0;
                        hourInt=hourInt+1;
                    }
                }else{
                    minuteInt=30;
                }
            }
            //2.服务开始前及结束后预留出行时间
            //精油往后延30 分钟，中医往后延60 分钟
            if(artificer.getClassifyId()==95){
                String time = artificer.getTime();
                //在精油的基础上加30 分钟就是中医~~
                DateTime dateTime1 = DateUtil.offsetMinute(DateUtil.parse(time), 30);
                artificer.setTime(DateUtil.format(dateTime1,"HH:mm"));
            }
        }else{

            SimpleDateFormat sdf=new SimpleDateFormat("HH");

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat md = new SimpleDateFormat("MM-dd");
            Date dateTime = new Date();
            String date = simpleDateFormat.format(dateTime);
            String oldDate = simpleDateFormat.format(dateTime);
            String time = sdf.format(dateTime);
            String times="";
            if("23".equals(time)){
                time="00";
                times=time+":30";
            }else{
                time=String.valueOf(Integer.parseInt(time)+1);
                times=time+":30";
            }
            String nowTimes=times;
            Calendar calendar=Calendar.getInstance();
            date = simpleDateFormat.format(dateTime);
            oldDate = simpleDateFormat.format(dateTime);
            time = sdf.format(dateTime);
            times="";
            if("23".equals(time)){
                time="00";
                times=time+":30";
                calendar.add(Calendar.DAY_OF_MONTH,1);
                date = simpleDateFormat.format(calendar.getTime());
            }else{
                time=String.valueOf(Integer.parseInt(time)+1);
                times=time+":30";
            }
            while (true){
                ArtificerTime artificerTime = artificerTimeService.getOne(new QueryWrapper<ArtificerTime>().eq("artificer_id", artificer.getArtificerId()).eq("artificer_date", date).eq("artificer_time", times));
                if(artificerTime==null){
                    if(oldDate.equals(date)){
                        times=time+":00";
                        artificer.setTime(times);
                    }else{
                        times=time+":00";
                        artificer.setTime(md.format(calendar.getTime())+" "+times);
                    }
                    if(artificer.getStatus()!=null && artificer.getStatus()==2){
                        artificer.setState(3);
                    }else{
                        if(times.equals(nowTimes)){
                            artificer.setState(1);
                        }else{
                            artificer.setState(2);
                        }
                    }
                    break;
                }
                if("23".equals(time)){
                    time="00";
                    times=time+":30";
                    calendar.add(Calendar.DAY_OF_MONTH,1);
                    date = simpleDateFormat.format(calendar.getTime());
                }else{
                    time=String.valueOf(Integer.parseInt(time)+1);
                    times=time+":30";
                }
            }
        }
        return artificer;
    }

    @Override
    public Artificer selectArtificerByUserId(Long userId){
        return baseMapper.selectArtificerByUserId(userId);
    }

    @Override
    public int selectArtificerByStatus(Long userId, Integer status) {

        return artificerDao.selectArtificerByStatus(userId, status);
    }


    @Override
    public Result selectArtificerMoney(Long userId,Long artificerId){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dayTime = sdf.format(new Date());
        //累计收益
        BigDecimal sumMoney = ordersDao.selectSumOrdersMoney(artificerId, null, null);
        //今日收益
        BigDecimal dayMoney = ordersDao.selectEstimationSumMoneyBy(artificerId, dayTime, 1);
        //本月预估收益
        BigDecimal monthMoney = ordersDao.selectEstimationSumMoneyBy(artificerId, dayTime, 2);
        //本月预估提现
        BigDecimal cashMoney = cashOutDao.sumMoneyByUserId(userId, dayTime, 2);
        UserMoney userMoney = userMoneyService.selectUserMoneyByUserId(userId);
        Map<String,Object> result=new HashMap<>();
        result.put("sumMoney",sumMoney);
        result.put("dayMoney",dayMoney);
        result.put("monthMoney",monthMoney);
        result.put("cashMoney",cashMoney);
        result.put("money",userMoney.getMoney());
        result.put("mysad",userMoney.getSad());//盛安豆
        return Result.success().put("data",result);
    }

    @Override
    public Result signIn(Long userId, String longitude, String latitude, String city,String address){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String time = simpleDateFormat.format(new Date());
        MessageInfo messageInfo = messageService.selectMessageByUserIdAndTime(userId, time);
        if(messageInfo!=null){
            return Result.error("今天已经签过到了！");
        }
        if(StringUtils.isEmpty(longitude) || StringUtils.isEmpty(latitude)){
            return Result.error("请在小程序设置中开启位置信息");
        }
        Artificer artificer = selectArtificerByUserId(userId);
        messageInfo=new MessageInfo();
        messageInfo.setContent(address);
        messageInfo.setUserName(artificer.getArtificerName());
        messageInfo.setUserId(String.valueOf(userId));
        messageInfo.setState("10");
        messageInfo.setTypeId(longitude);
        messageInfo.setTypeName(latitude);
        messageService.saveBody(messageInfo);
        artificer.setLatitude(latitude);
        artificer.setLongitude(longitude);
        if(!StringUtils.isEmpty(latitude) && !StringUtils.isEmpty(longitude)){
            JSONObject adInfo = CommonMapUtils.getLocationToAdInfo(messageInfo.getTypeId(), messageInfo.getTypeName());
            String cityName = adInfo.getString("city");
            artificer.setCity(cityName);
        }
        updateById(artificer);
        return Result.success();
    }

    @Override
    public Result selectArtificerMoneyList(Integer page,Integer limit,String startTime,String endTime,String title,String classifyId){
        IPage<Map<String,Object>> pageList = baseMapper.selectArtificerMoneyList(new Page<>(page,limit),startTime,endTime,title,classifyId);
        for(Map<String,Object> map:pageList.getRecords()){
            Long artificerId = Long.parseLong(map.get("artificerId").toString());
            //当期业绩
//            BigDecimal currentPerformance = ordersDao.selectOrdersArtificerIntegralEarnings(artificerId, endTime, startTime);
            Integer dqyjOld = ordersDao.selectOrdersArtificerIntegralAchievement(artificerId, endTime, startTime);
            BigDecimal currentPerformance = new BigDecimal(dqyjOld);
                    currentPerformance = currentPerformance.setScale(0,BigDecimal.ROUND_DOWN);
            map.put("yj",String.valueOf(currentPerformance));

            //首页
            BigDecimal earnings = ordersDao.selectOrdersArtificerIntegralEarnings(artificerId, endTime, startTime);
            map.put("sy",String.valueOf(earnings));

            //当期订单数：计算订单发生了按摩行为的订单数，订单状态经历了开始服务到订单结束。
            String currentPeriodOrdersSum = ordersDao.selectOrdersArtificerIntegral(artificerId, endTime, startTime);
            BigDecimal currentPeriodOrdersSumBig = new BigDecimal(currentPeriodOrdersSum);

            //当期加钟率：本周期内，加钟数/本单数
            String v = ordersDao.selectOrdersArtificerIntegraladdNum(artificerId, endTime, startTime);
            //加钟数
            BigDecimal currentPeriodAddBellsSumBig = new BigDecimal(v);
            //加钟率
            BigDecimal clockRate = BigDecimal.ZERO;
            //充值率
            BigDecimal divide1 = BigDecimal.ZERO;
            if (currentPeriodOrdersSumBig.compareTo(new BigDecimal("0")) != 0) {
                clockRate = currentPeriodAddBellsSumBig.divide(currentPeriodOrdersSumBig, 2, RoundingMode.HALF_UP);//加钟率

                //当前周期充值率(本周期内充值订单数/本单数)
                String currentPeriodRechargeSum = ordersDao.selectOrdersCurrentPeriodRechargeSum(artificerId, endTime, startTime,1);
                BigDecimal c = new BigDecimal(currentPeriodRechargeSum);
                divide1 = c.divide(currentPeriodOrdersSumBig, 2, RoundingMode.HALF_UP);//充值率
            } else {
                clockRate = new BigDecimal("0");
                divide1 = new BigDecimal("0");
            }
            map.put("jzl",String.valueOf(clockRate));//加钟率
            map.put("czl",String.valueOf(divide1));//充值率
            //在线时长
            String mint = ordersDao.selectOrdersZxscNum(artificerId,startTime,endTime);
            map.put("zxsc",String.valueOf(mint));//在线时长
            map.put("ddsl",currentPeriodOrdersSum);//订单数量

        }

        return Result.success().put("data",pageList);
    }

    @Override
    public Result selectUserListByConsortiaId(Integer page,Integer limit,String userName,String phone,Long consortiaId,Long shopId,Integer flag,String time){
        return Result.success().put("data",new PageUtils(baseMapper.selectUserListByConsortiaId(new Page<>(page,limit),userName,phone,consortiaId,shopId,flag,time)));
    }

    @Override
    public void timing(Long artificerId) {
        UserRecharge userRecharge = new UserRecharge();
        userRecharge.setType("1");
        userRecharge.setCreateTime(LocalDateTime.now().toString());
        BigDecimal bigDecimal = new BigDecimal(1);
        userRecharge.setUserRecharge(bigDecimal);
        userRecharge.setArtificerId(artificerId);
        userRechargeDao.insert(userRecharge);
    }

    @Override
    public Result integral(String artificerId, String type, Integer current, Integer size, String date, Integer fundType) {
        Period period = new Period();
        period.setFundType(fundType);
        period.setFundData(DateUtil.parse(date));
        Period period1 = calculationPeriod(period);
        Date startFundData = period1.getStartFundData();
        Date endFundData = period1.getEndFundData();

        String start = DateUtil.formatDateTime(startFundData);
        String end = DateUtil.formatDateTime(endFundData);

        List<UserRecharge> req = Lists.newArrayList();
        List<UserRecharge> integral = userRechargeDao.integral(artificerId, new Page<>(current, size), type, start, end);
        List<UserRecharge> count = userRechargeDao.integral(artificerId, new Page<>(current, 10000000), type, start, end);

        //根据formattedDate去分组
        Map<String, List<UserRecharge>> collect = integral.stream().collect(Collectors.groupingBy(UserRecharge::getFormattedDate));

        collect.forEach((k, v) -> {
            UserRecharge userRecharge = new UserRecharge();
            userRecharge.setFormattedDate(k);
            userRecharge.setChildren(v);
            req.add(userRecharge);
        });
        //倒叙排列
        req.sort(Comparator.comparing(UserRecharge::getFormattedDate, Comparator.reverseOrder()));
        return Result.success().put("data", req).put("count", count.size());
    }

    @Override
    public Result storedValue(String date, String type, String artificerId) {
        Map<String, String> map = Maps.newHashMap();
        Period period = new Period();
        period.setFundType(Integer.valueOf(type));
        period.setFundData(DateUtil.parse(date));
        Period period1 = calculationPeriod(period);
        Date startFundData = period1.getStartFundData();
        Date endFundData = period1.getEndFundData();

        String start = DateUtil.formatDateTime(startFundData);
        String end = DateUtil.formatDateTime(endFundData);

        int i = Integer.parseInt(commonInfoDao.findOne(100000).getValue());
        //储存积分
        String storedValue = userRechargeDao.storedValue(start, end, "2", artificerId);
        //在线积分
        String onlineCredits = userRechargeDao.storedValue(start, end, "1", artificerId);
        map.put("storedValue", storedValue);
        map.put("onlineCredits", onlineCredits);
        //长时间
        map.put("intervalDatesUltimately", start + "-" + end);
        int num1 = Integer.parseInt((NumberUtil.toStr(new BigDecimal(storedValue))));
        int num2 = Integer.parseInt(NumberUtil.toStr(new BigDecimal(onlineCredits)));
        int i1 = num2 * i / 60;
        //在线时长
        map.put("onLineTime", i1 + "");
        map.put("sum", String.valueOf(num1 + num2));

        return Result.success().put("data", map);
    }

    @Override
    public Result selectArtificerByArtificerId(Long artificerId) {
        return Result.success().put("data", baseMapper.selectById(artificerId));
    }

    public Result getHomeArtificerList(Integer page, Integer limit, Integer isStart,Integer status, String city, String longitude, String latitude){
        Map<String, Object> map = new HashMap<String, Object>();
        Page<Artificer> pages=new Page<>(page,limit);
        IPage<Artificer> artificerIPage = baseMapper.selectArtificerList(pages, null, "",longitude, latitude, 1, 2, 1, status, city, null,"",1,0,null,"");
        map.put("nearData",new PageUtils(artificerIPage));
        map.put("startData",new PageUtils(baseMapper.getHomeStartArtificerList(pages,isStart,status,city)));
        return Result.success(map);
    }

    /**
     * 技师首页获取当期订单，加钟订单，充值订单
     * @param userId 技师id
     * @param page 第几页
     * @param limit 每页几条
     * @param orderType 类型 1当期 2加钟 3充值
     * @param isSfwc 0不包含 1包含  空为全部
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return
     */
    @Override
    public Result getOrderTypeList(Long userId, Integer page, Integer limit, Integer orderType, Integer isSfwc,String startTime,String endTime) {
        Map<String, Object> map = new HashMap<String, Object>();
        Page<Orders> pages=new Page<>(page,limit);
        IPage<Orders> ordersIPage = null;
        //当期订单数：计算订单发生了按摩行为的订单数，订单状态经历了开始服务到订单结束。
        String currentPeriodOrdersSum = ordersDao.selectOrdersArtificerIntegral(userId, endTime, startTime);
        if(currentPeriodOrdersSum.isEmpty() || currentPeriodOrdersSum.equals("0")){
            map.put("data",new PageUtils(pages));
            map.put("earnings","0");
            return  Result.success(map);
        }
        //订单数
        BigDecimal currentPeriodOrdersSumBig = new BigDecimal(currentPeriodOrdersSum);
        //查询收益
        String earnings = "0";
        BigDecimal cy100 = new BigDecimal(100);
        if(orderType == 1){//1当期
//            ordersIPage = ordersDao.getDangqiList(pages, userId,isSfwc,startTime,endTime);
            ordersIPage = ordersDao.selectDividedIntoDetails(pages, userId,startTime,endTime,null);
            BigDecimal yeji = ordersDao.selectOrdersArtificerIntegralEarnings(userId, endTime, startTime);
            yeji = yeji.setScale(2,BigDecimal.ROUND_HALF_UP);
            earnings = yeji.toString();
        }else if(orderType == 2){//2加钟
            //查询列表
//            ordersIPage = ordersDao.getJiazhongList(pages, userId,isSfwc,startTime,endTime);
            ordersIPage = ordersDao.selectDividedIntoDetails(pages, userId,startTime,endTime,isSfwc);
            //当期加钟率：本周期内，加钟数/本单数
            String jzl = ordersDao.selectOrdersArtificerIntegraladdNum(userId, endTime, startTime);
            //加钟数
            BigDecimal num = new BigDecimal(jzl);
            BigDecimal clockRate = num.divide(currentPeriodOrdersSumBig, 2, BigDecimal.ROUND_HALF_UP);
            clockRate = clockRate.multiply(cy100);
            earnings = clockRate.intValue()+"%";
            System.out.println(currentPeriodOrdersSumBig+"=========="+num+"---"+clockRate);
        }else if(orderType == 3){//3充值
            ordersIPage = ordersDao.getChongzhiList(pages, userId,isSfwc,startTime,endTime);
            //当前周期充值率(本周期内充值订单数/本单数)
            String currentPeriodRechargeSum = ordersDao.selectOrdersCurrentPeriodRechargeSum(userId, endTime, startTime,1);
            BigDecimal c = new BigDecimal(currentPeriodRechargeSum);
            BigDecimal divide1 = c.divide(currentPeriodOrdersSumBig, 2, BigDecimal.ROUND_HALF_UP);
            divide1 = divide1.multiply(cy100);
            earnings = divide1.intValue()+"%";
            System.out.println(currentPeriodOrdersSumBig+"=========="+c+"---"+divide1);
        }else if(orderType == 4){//业绩
//            ordersIPage = ordersDao.getDangqiList(pages, userId,isSfwc,startTime,endTime);
            ordersIPage = ordersDao.selectDividedIntoDetails(pages, userId,startTime,endTime,null);
            int yeji = ordersDao.selectOrdersArtificerIntegralAchievement(userId, endTime, startTime);
            earnings = yeji+"";
        }

        map.put("data",new PageUtils(ordersIPage));
        map.put("earnings",earnings);
        return  Result.success(map);
    }

    @Override
    public Result getJifenList(Long userId, String startTime, String endTime) {
        //1.获取业绩积分
        List<Orders> yjjfList = ordersDao.getYjjfList(userId,startTime,endTime);
        int yjjf = 0;
        for (Orders par:yjjfList) {
            yjjf += (int) Double.parseDouble(par.getJifen());
        }
        //2.获取储值积分（为他充值的）
        List<Orders> czjfList = ordersDao.getCzjfList(userId,startTime,endTime);
        int czjf = 0;
        for (Orders par:czjfList) {
            czjf += (int) Double.parseDouble(par.getJifen());
        }
        //3.获取订单充值积分
        List<Orders> ddczList = ordersDao.getDdczList(userId,startTime,endTime);
        int ddczjf = 0;
        for (Orders par:ddczList) {
            ddczjf += (int) Double.parseDouble(par.getJifen());
        }
        //4.获取在线时长积分
        List<Orders> zxscList = ordersDao.getZxscList(userId,startTime,endTime);
        int zxscjf = 0;
        for (Orders par:zxscList) {
            zxscjf += (int) Double.parseDouble(par.getJifen());
        }
        int sumJf = 0;
        sumJf = yjjf + czjf + ddczjf + zxscjf;
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("yjjfList",yjjfList);
        map.put("yjjf",yjjf);
        map.put("czjfList",czjfList);
        map.put("czjf",czjf);
        map.put("ddczList",ddczList);
        map.put("ddczjf",ddczjf);
        map.put("zxscList",zxscList);
        map.put("zxscjf",zxscjf);
        map.put("sumJf",sumJf);
        return Result.success(map);
    }

    @Override
    public Result updateShz(Artificer artificer) {
        if(artificer.getArtificerId()!=null){

            try {
                if(!StringUtils.isEmpty(artificer.getLifePhoto())){
                    String lifePhoto = artificer.getLifePhoto();//生活照
                    if(artificer.getLifePhoto().indexOf(",")>-1){
                        lifePhoto = artificer.getLifePhoto().split(",")[0];
                    }
                    Artificer artificerPar = baseMapper.selectById(artificer.getArtificerId());
                    String artificerImg = artificerPar.getArtificerImg();//头像

                    log.error("---------图片----------生活照："+lifePhoto);
                    log.error("---------图片----------头像照："+artificerImg);


                    FaceMain faceMain = new FaceMain();
                    AipFace client = faceMain.creatApiClent();
//                    String image1 = "https://img0.baidu.com/it/u=2620353834,3334301303&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=670";
//                    String image2 = "https://img1.baidu.com/it/u=3388895316,506060607&fm=253&fmt=auto&app=138&f=JPEG?w=608&h=338";
                    MatchRequest req1 = new MatchRequest(lifePhoto, "URL");//
                    MatchRequest req2 = new MatchRequest(artificerImg, "URL");
                    ArrayList<MatchRequest> requests = new ArrayList<>();
                    requests.add(req1);
                    requests.add(req2);

                    org.json.JSONObject res = client.match(requests);

                    //对比
                    log.error("---------res----------："+res);

                    //保存结果
                    org.json.JSONObject result = res.getJSONObject("result");
                    log.error("---------result----------："+result);

                    String score = String.valueOf(result.getInt("score"));
                    System.out.println("--------score-----------------:"+score);
                    artificer.setBdxsl(score);
                }
            }catch (Exception e){
                e.printStackTrace();
            }



            artificer.setUpdateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            baseMapper.updateById(artificer);
            return Result.success();
        }else{
            return Result.error("您未实名认证，不能提交生活照！");
        }
    }

    @Override
    public Artificer selectByPhone(String mobile) {
        return baseMapper.selectByPhone(mobile);
    }

    @Override
    public Result selectArtificerPhbList(Integer page, Integer limit, String startTime, String endTime, String type) {
        IPage<Map<String,Object>> pageList = null;
        if(!StringUtils.isEmpty(endTime)){
            endTime = endTime+" 23:59:59";
        }
        if(StringUtils.equals(type,"1")){//在线时长
            pageList = baseMapper.getZxscList(new Page<>(page,limit),startTime,endTime);
        }else if(StringUtils.equals(type,"2")){//业绩
            pageList = baseMapper.getYejiList(new Page<>(page,limit),startTime,endTime);
        }else if(StringUtils.equals(type,"3")){//加钟率
            pageList = baseMapper.getJzlList(new Page<>(page,limit),startTime,endTime);
        }else if(StringUtils.equals(type,"4")){//充值率
            pageList = baseMapper.getCzlList(new Page<>(page,limit),startTime,endTime);

        }
        return Result.success().put("data",pageList);
    }

//    public static void main(String[] args) {
//        String lifePhoto = "http://1.92.152.160/file/uploadPath/2024/07/09/a892623c518812421cec310d3d5e8d0a.jpg";
//        String artificerImg = "https://sausers.blxinchuang.com/file/uploadPath/2024/07/03/423843a244c16b04819a131c2160c0af.png";
//
//
//        String base64Img1 = FileUploadUtils.encodeImageToBase64(lifePhoto);
//        String base64Img2 = FileUploadUtils.encodeImageToBase64(artificerImg);
//
//        System.out.println(base64Img1);
//
//    }


}