package com.sysu.admin.controller.crop.range;

import com.querydsl.core.types.Predicate;
import com.sysu.admin.support.base.BaseService;
import com.xiesx.fastboot.core.jpa.JpaPlusRepository;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Optional;

@Service
public class LandRangeIndexService extends BaseService<LandRangeIndex, PKRP> {

    @Autowired
    private LandRangeIndexRepository mLandRangeIndexRepository;

    private static String defaultTableName = "p_crop";


    public String[] getTableNames(Double x1, Double y1,Double x2, Double y2){
        String wkt = "POLYGON (("+x1+" "+y1+", "+x1+" "+y2+", "+x2+" "+y2+", "+x2+" "+y1+", "+x1+" "+y1+"))";
        String[] res = mLandRangeIndexRepository.findTableNameByWkt(wkt);
        if(ObjectUtils.isEmpty(res)){
            return new String[]{defaultTableName};
        }else{
            return res;
        }
    }

    public String getTableName(Long id){
        return getByCropId(id).getTableName();
    }

    public LandRangeIndex getByCropId(Long id){
        if(id == null){
            throw new NullPointerException("getByCropId(id) id is null");
        }
        QLandRangeIndex qLandRangeIndex = QLandRangeIndex.landRangeIndex;
        Predicate predicate = qLandRangeIndex.pk.start.loe(id).and(qLandRangeIndex.pk.end.goe(id));
        Optional<LandRangeIndex>  landRangeIndex = mLandRangeIndexRepository.findOne(predicate);
        if(landRangeIndex.isPresent()){
            return landRangeIndex.get();
        }
        LandRangeIndex res = new LandRangeIndex();
        res.setPk(new PKRP().end(0L).start(0L));
        res.setName("其他地区");
        res.setTableName(defaultTableName);
        return res;
    }

    public String getTableNameByCode(String code){
        QLandRangeIndex qLandRangeIndex = QLandRangeIndex.landRangeIndex;
        Optional<LandRangeIndex> landRangeIndex = mLandRangeIndexRepository.findOne(qLandRangeIndex.code.eq(code));
        if(landRangeIndex.isPresent()){
            return landRangeIndex.get().getTableName();
        }
        return defaultTableName;
    }

    public String getTableName(Double[] point){
        return mLandRangeIndexRepository.findTableNameByPoint("Point("+point[0]+" "+point[1]+")");
    }

    public String getAllTableNames(){
        String[] resArray = mLandRangeIndexRepository.findAllTableName();
        StringBuffer res = new StringBuffer(resArray.length * 15);
        for(int i=0;i<resArray.length;i++){
            if(i > 0){
                res.append(",");
            }
            res.append(resArray[i]);
        }
        return res.toString();
    }



    @Override
    public JpaPlusRepository<LandRangeIndex, PKRP> r() {
        return mLandRangeIndexRepository;
    }
}
