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

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.sqx.common.utils.PageUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.artificer.dao.ArtificerMassageDao;
import com.sqx.modules.artificer.dao.CollectArtificerDao;
import com.sqx.modules.artificer.entity.Artificer;
import com.sqx.modules.artificer.entity.ArtificerMassage;
import com.sqx.modules.artificer.entity.ArtificerTime;
import com.sqx.modules.artificer.entity.CollectArtificer;
import com.sqx.modules.artificer.service.ArtificerMassageService;
import com.sqx.modules.artificer.service.ArtificerTimeService;
import com.sqx.modules.artificer.service.CollectArtificerService;
import com.sqx.modules.common.service.CommonInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.locks.ReentrantReadWriteLock;


@Service
public class CollectArtificerServiceImpl extends ServiceImpl<CollectArtificerDao, CollectArtificer> implements CollectArtificerService {

    @Autowired
    private ArtificerTimeService artificerTimeService;
    @Autowired
    private CommonInfoService commonInfoService;

    private ReentrantReadWriteLock reentrantReadWriteLock=new ReentrantReadWriteLock(true);

    @Override
    public Result insertCollect(CollectArtificer collectArtificer){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        reentrantReadWriteLock.writeLock().lock();
        try {
            CollectArtificer collectArtificer1 = selectCollectArtificerByUserId(collectArtificer.getUserId(), collectArtificer.getArtificerId(),collectArtificer.getClassify());
            if(collectArtificer1!=null){
                if(collectArtificer1.getClassify()==1){
                    baseMapper.deleteById(collectArtificer1.getCollectId());
                }else{
                    collectArtificer1.setCreateTime(sdf.format(new Date()));
                    baseMapper.updateById(collectArtificer1);
                }
            }else{
                collectArtificer.setCreateTime(sdf.format(new Date()));
                baseMapper.insert(collectArtificer);
            }
            return Result.success();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            reentrantReadWriteLock.writeLock().unlock();
        }
        return Result.error("系统繁忙，请稍后再试！");
    }


    @Override
    public CollectArtificer selectCollectArtificerByUserId(Long userId,Long artificerId,Integer classify){
        return baseMapper.selectOne(new QueryWrapper<CollectArtificer>().eq("user_id",userId).eq("artificer_id",artificerId).eq("classify",classify));
    }

    @Override
    public Result selectCollectList(Long userId,Integer page,Integer limit,String longitude,String latitude){
        Page<Artificer> pages=new Page<>(page,limit);
        IPage<Artificer> artificerIPage = baseMapper.selectArtificerListByCollectUserId(pages, userId, longitude, latitude);
        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();

            String hour = sdfHour.format(dateTime);
            String minute = sdfMinute.format(dateTime);
            int minuteInt = Integer.parseInt(minute);
            int hourInt = Integer.parseInt(hour);
            if(minuteInt>=30){
                if(hourInt==23){
                    hourInt=0;
                    minuteInt=0;
                }else{
                    minuteInt=0;
                    hourInt=hourInt+1;
                }
            }else{
                minuteInt=30;
            }
            StringBuilder stringBuilders=new StringBuilder();
            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=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=0;
                    }else{
                        minuteInt=0;
                        hourInt=hourInt+1;
                    }
                }else{
                    minuteInt=30;
                }
                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;
                    }
                }
            }
        }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="01";
                times=time+":00";
            }else{
                time=String.valueOf(Integer.parseInt(time)+1);
                times=time+":00";
            }
            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="01";
                    times=time+":00";
                }else{
                    time=String.valueOf(Integer.parseInt(time)+1);
                    times=time+":00";
                }
                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="01";
                        times=time+":00";
                        calendar.add(Calendar.DAY_OF_MONTH,1);
                        date = simpleDateFormat.format(calendar.getTime());
                    }else{
                        time=String.valueOf(Integer.parseInt(time)+1);
                        times=time+":00";
                    }
                }
            }
        }
        return Result.success().put("data",new PageUtils(artificerIPage));
    }

    @Override
    public int selectCountByUserId(Long artificerId,  String startTime,String endTime ) {
        return baseMapper.selectCountByUserId(artificerId,startTime,endTime);
    }

}