package com.sysu.admin.site;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.sysu.admin.controller.city.CityRepository;
import com.sysu.admin.controller.city.District;
import com.sysu.admin.controller.city.DistrictRepository;
import com.sysu.admin.controller.crop.CropLand;
import com.sysu.admin.controller.crop.CropLandService;
import com.sysu.admin.controller.crop.CropLandVo;
import com.sysu.admin.controller.crop.CropPoint;
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.core.token.annotation.GoToken;
import com.xiesx.fastboot.core.token.handle.CurrentToken;
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.RequestBody;
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.Date;
import java.util.List;
import java.util.Map;

/**
 * 读取地图数据信息
 */
@RequestMapping("/site/crop")
@Controller
public class SiteCropLandController 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(@RequestBody CommonVo commonVo){
        CropLand cityLand = cityLandService.findByPoint(new Double[]{commonVo.getX1(), commonVo.getY1()});
        if(cityLand == null){
            return R.fail();
        }
        cityLand.setWkt(GeoCastUtil.geomToWkt(cityLand.getGeom()));
        return R.succ(cityLand);
    }

    @RequestMapping("/getGeoJson")
    @ResponseBody
    public BaseResult getGeojson(@RequestBody CommonVo commonVo, @GoToken() CurrentToken currentToken){
        List<CropPoint> cropLandList = cityLandService.findCropLandNoGeomByTableNamesAndBBox(commonVo.getTableNames(),
                commonVo.getX1(),commonVo.getY1(),commonVo.getX2(),commonVo.getY2(), commonVo.getStatus());
        return R.succ(cropLandList);
    }


    @RequestMapping("/publish")
    @ResponseBody
    public BaseResult publish(@RequestBody CropLandVo vo, @GoToken() CurrentToken currentToken){
        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("/batchPublish")
    @ResponseBody
    @Transactional
    public BaseResult batchPublish(@RequestBody CropLandVo vo){
        if(StringUtils.isNotBlank(vo.getFileBase64())){
            Path path = cityLandService.fileByBase64(vo.getFileBase64(),"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);
            }else{
                return R.fail("请选择区县！");
            }
        }
        return R.succ();
    }

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

    @RequestMapping("/export")
    @ResponseBody
    @Transactional
    public void export(@RequestBody 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(@RequestBody String data){
        String wkt = JSON.parseObject(data).get("wkt").toString();
        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();
    }


}













