package com.sysu.admin.controller.crop;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.querydsl.core.types.Predicate;
import com.querydsl.jpa.impl.JPAUpdateClause;
import com.sysu.admin.controller.city.*;
import com.sysu.admin.controller.crop.range.LandRangeIndexService;
import com.sysu.admin.controller.crop.xls.CropExcel;
import com.sysu.admin.controller.crop.xls.CropExcelService;
import com.sysu.admin.controller.crop.xls.CustomHandler;
import com.sysu.admin.controller.crop.xls.PublishCropExcelListener;
import com.sysu.admin.controller.geo.land.LandTaskStatus;
import com.sysu.admin.support.base.ServiceContext;
import com.sysu.admin.support.shiro.ShiroService;
import com.sysu.admin.utils.shape.GeoCastUtil;
import com.xiesx.fastboot.base.result.BaseResult;
import com.xiesx.fastboot.base.result.R;
import com.xiesx.fastboot.utils.CopyUtils;
import org.apache.catalina.util.URLEncoder;
import org.apache.commons.lang3.StringUtils;
import org.locationtech.jts.geom.MultiPolygon;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.util.*;

/**
 * 读取地图数据信息
 */
@RequestMapping("/crop")
@Controller
public class CropLandController extends ServiceContext {

    @Autowired
    CropLandService cityLandService;
    @Autowired
    ShiroService shiroService;
    @Autowired
    LandRangeIndexService mLandRangeIndexService;
    @Autowired
    DistrictRepository districtRepository;
    @Autowired
    CityRepository cityRepository;
    @Autowired
    CropExcelService cropExcelService;

    @RequestMapping("/getInfo")
    @ResponseBody
    public BaseResult getInfo(Double x, Double y){
        CropLand cityLand = cityLandService.findByPoint(new Double[]{x,y});
        if(cityLand == null){
            return R.fail();
        }
        cityLand.setWkt(GeoCastUtil.geomToWkt(cityLand.getGeom()));
        return R.succ(cityLand);
    }

    @RequestMapping("/getGeoJson")
    @ResponseBody
    public BaseResult getGeojson(String tableNames, Double x1, Double y1,Double x2, Double y2, String status){
//        String[] tableNames = mLandRangeIndexService.getTableNames(x1,y1,x2,y2);
        List<CropPoint> cropLandList = cityLandService.findCropLandNoGeomByTableNamesAndBBox(tableNames, x1,y1,x2,y2, status);
        return R.succ(cropLandList);
    }

    @RequestMapping("/getBuffer")
    @ResponseBody
    public BaseResult getBuffer(Double x, Double y, Integer m){
        return R.succ(cityLandService.getBuffer(new Double[]{x, y}, m));
    }

    @RequestMapping("/save")
    @ResponseBody
    public BaseResult save(CropLandVo vo){
        CropLand bean = cityLandService.findOne(vo.getId());
        if(bean.getStatus().intValue() == LandTaskStatus.unpublished.ordinal()){
            bean.setCreator(shiroService.getPrincipalId());
            bean.setCreateDate(new Date());
        }
        BeanUtils.copyProperties(vo, bean, CopyUtils.nullNames(vo));
        bean.setWkt(GeoCastUtil.geomToWkt(bean.getGeom()));
        bean.setCenterPoint(cityLandService.getCenterPoint(bean.getGeom()));
        District district = districtRepository.findByPoint(bean.getCenterPoint());
        if(district != null){
            cityLandService.setCity(bean, district);
        }
        cityLandService.save(bean);
        return R.succ(bean);
    }

    @RequestMapping("/publish")
    @ResponseBody
    public BaseResult publish(CropLandVo vo){
        CropLand bean = cityLandService.findOne(vo.getId());
        if(bean.getStatus().intValue() != LandTaskStatus.unpublished.ordinal()){
            return R.fail("不是未发布的地块！");
        }
        if(bean.getDistrict() == null || bean.getCenterPoint() == null){
            bean.setCenterPoint(cityLandService.getCenterPoint(bean.getGeom()));
            bean.getCenterPoint().setSRID(4326);
            District district = districtRepository.findByPoint(bean.getCenterPoint());
            if(district != null){
                cityLandService.setCity(bean, district);
            }
        }
        bean.setStatus(LandTaskStatus.published.ordinal());
        cityLandService.save(bean);
        return R.succ();
    }



    @RequestMapping("/publish_index")
    public String publishIndex(){
        return "page/publish_task";
    }

    @RequestMapping("/batchPublish")
    @ResponseBody
    @Transactional
    public BaseResult batchPublish(CropLandVo vo, String fileBase64){
        if(StringUtils.isNotBlank(fileBase64)){
            Path path = cityLandService.fileByBase64(fileBase64,"xls",mShiroService.getPrincipalId());
            PublishCropExcelListener publishCropExcelListener = new PublishCropExcelListener(mLandRangeIndexService);
            EasyExcel.read(path.toFile(), CropExcel.class,publishCropExcelListener).doReadAllSync();
            Map<String,List<Long>> stringListMap = publishCropExcelListener.getTableIdsMap();
            for(String tableName : stringListMap.keySet()) {
                cityLandService.batchPublishByIds(tableName, stringListMap.get(tableName));
            }
        }else{
            if(vo.getDistrictId() != null) {
                String tableName = mLandRangeIndexService.getTableNameByCode(vo.getDistrictId());
                cityLandService.batchPublishByTableName(tableName);
            }
        }
        return R.succ();
    }

    @RequestMapping("/export_index")
    public String exportIndex(){
        return "page/export";
    }

    @RequestMapping("/export")
    @ResponseBody
    @Transactional
    public void export(CropLandVo vo, HttpServletResponse response){
        String tableNames;
        if(vo.getDistrictId() == null){
            tableNames = mLandRangeIndexService.getAllTableNames();
        }else{
            tableNames = mLandRangeIndexService.getTableNameByCode(vo.getDistrictId());
        }
        List<CropLand> cropLandList = cityLandService.findAllByStatusAndDistrict(tableNames, vo.getStatus());
        List<CropExcel> cropExcelList = cropExcelService.cropLandToCropExcel(cropLandList);
        String mimetype = "application/x-msdownload";
        String downFileName = "重庆耕地信息.xlsx";
        String inlineType = "attachment"; // 是否内联附件
        response.setContentType(mimetype);
        response.setHeader("Content-Disposition", inlineType
                + ";filename=" + URLEncoder.DEFAULT.encode(downFileName, Charset.defaultCharset()));
        try {
            EasyExcel.write(response.getOutputStream(), CropExcel.class).registerWriteHandler(new CustomHandler())
                    .sheet("sheet1").doWrite(cropExcelList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/addTest")
    @ResponseBody
    public BaseResult addTest(String wkt){
        CropLand bean = new CropLand().setGeom((MultiPolygon)GeoCastUtil.wktToGeom(wkt))
                .setGridcode(2L).setStatus(LandTaskStatus.unpublished.ordinal());
        bean.setCenterPoint(cityLandService.getCenterPoint(bean.getGeom()));
        bean.getCenterPoint().setSRID(4326);
        District district = districtRepository.findByPoint(bean.getCenterPoint());
        if(district != null) {
            cityLandService.setCity(bean, district);
        }
        cityLandService.save(bean);
        return R.succ();
    }


}













