package cn.com.countrygarden.bi.main.controller.dup;

import cn.com.countrygarden.bi.main.core.Response;
import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.exception.ServiceException;
import cn.com.countrygarden.bi.main.model.AccessToken;
import cn.com.countrygarden.bi.main.model.PageData;
import cn.com.countrygarden.bi.main.model.dup.BuoyData;
import cn.com.countrygarden.bi.main.service.AccessTokenService;
import cn.com.countrygarden.bi.main.service.dup.BuoyDataService;
import cn.com.countrygarden.bi.main.service.dup.DupCommService;
import cn.com.countrygarden.bi.main.service.dup.ManagerDataService;
import cn.com.countrygarden.bi.main.service.dup.impl.ExcelHelper;
import org.apache.commons.lang.time.DateUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.List;

@RestController()
@RequestMapping("/api/fenghuang/buoy")
public class BuoyDataController {

    @Autowired
    private DupCommService dupCommService;

    @Autowired
    private AccessTokenService accessTokenService;

    @Autowired
    private BuoyDataService buoyDataService;

    @RequestMapping(value = "/add", produces = "application/json;charset=utf-8",  method = RequestMethod.POST)
    public Object addBuoyData(@RequestBody BuoyData data,
                              HttpServletRequest request, HttpServletResponse response){
        String accessToken = request.getParameter("AccessToken");
        AccessToken token = accessTokenService.findByToken(accessToken);
        Calendar beginDate = DateUtils.toCalendar(data.getBeginDate());
        if(beginDate.get(Calendar.DAY_OF_WEEK)!=2){
            throw new ServiceException("请重新选择日期，开始日期为周一，结束日期为周日");
        }
        Calendar endDate = DateUtils.toCalendar(data.getEndDate());
        if(endDate.get(Calendar.DAY_OF_WEEK)!=1){
            throw new ServiceException("请重新选择日期，开始日期为周一，结束日期为周日");
        }
        buoyDataService.addBuoyData(data,token.getUserCode());
        return Response.response("");
    }

    @RequestMapping(value = "/update", produces = "application/json;charset=utf-8",  method = RequestMethod.POST)
    public Object updateBuoyData(@RequestBody BuoyData data,
                                 HttpServletRequest request, HttpServletResponse response){
        String accessToken = request.getParameter("AccessToken");
        AccessToken token = accessTokenService.findByToken(accessToken);
        buoyDataService.updateBuoyData(data,token.getUserCode());
        return Response.response("");
    }

    @RequestMapping(value = "/delete/{id}",produces = "application/json;charset=utf-8",  method = RequestMethod.DELETE)
    public Object deleteBuoyData(@PathVariable("id") int dataId,
                                 HttpServletRequest request, HttpServletResponse response){
        String accessToken = request.getParameter("AccessToken");
        AccessToken token = accessTokenService.findByToken(accessToken);
        buoyDataService.deleteBuoyData(dataId,token.getUserCode());
        return Response.response("");
    }

    @RequestMapping(value = "/search", produces = "application/json;charset=utf-8",  method = RequestMethod.GET)
    public Object queryBuoyData(@RequestParam(value = "isUnFinished",required = false,defaultValue = "false") Boolean isUnFinished,
                                @RequestParam(value = "organCode",required = false,defaultValue = "") String organCode,
                                @RequestParam(value = "commId",required = false,defaultValue = "") String commId,
                                @RequestParam(value = "startDate",required = true)String startDateStr,
                                @RequestParam(value = "endDate",required = true)String endDateStr,
                                @RequestParam(value = "size",required = false, defaultValue="10") int size,
                                @RequestParam(value = "page",required = false, defaultValue="1") int page,
                                @RequestParam(value = "isSum",required = false, defaultValue="false") boolean isSum,
                                HttpServletRequest request, HttpServletResponse response){
        String accessToken = request.getParameter("AccessToken");
        AccessToken token = accessTokenService.findByToken(accessToken);
        return buoyDataService.query(isUnFinished, token.getUserCode(),organCode,commId,startDateStr,endDateStr,isSum,size,page);
    }

    @RequestMapping(value = "/export", produces = "multipart/form-data",  method = RequestMethod.GET)
    public Object queryBuoyData(@RequestParam(value = "isUnFinished",required = false,defaultValue = "false") Boolean isUnFinished,
                                @RequestParam(value = "organCode",required = false,defaultValue = "") String organCode,
                                @RequestParam(value = "commId",required = false,defaultValue = "") String commId,
                                @RequestParam(value = "startDate",required = true)String startDateStr,
                                @RequestParam(value = "endDate",required = true)String endDateStr,
                                @RequestParam(value = "isSum",required = false, defaultValue="false") boolean isSum,
                                HttpServletRequest request, HttpServletResponse response){
        String accessToken = request.getParameter("AccessToken");
        AccessToken token = accessTokenService.findByToken(accessToken);
        Result result = buoyDataService.query(isUnFinished,token.getUserCode(),organCode,commId,startDateStr,endDateStr,isSum,0,1);
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet();
        ExcelHelper helper = new ExcelHelper();
        helper.createBuoyHeader(workbook,sheet);
        helper.createBuoyBody((PageData) result.getData(),workbook,sheet);
        response.setContentType("multipart/form-data");
        String fileName = "export.xlsx";
        try {
            fileName = URLEncoder.encode("浮标数.xlsx","UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setHeader("Content-Disposition", "attachment;fileName="+fileName);

        OutputStream outputStream =null;
        try{
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
        } catch (Exception ex){

        } finally {
            try{
                workbook.close();
            } catch (Exception ex){

            }
        }

        return null;
    }
}
