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

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.service.AccessTokenService;
import cn.com.countrygarden.bi.main.service.resident.ExcelDataParser;
import cn.com.countrygarden.bi.main.service.resident.ResidentQuotaService;
import cn.com.countrygarden.bi.main.service.resident.model.QuotaData;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
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 org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@RestController("ResidentQuotaController")
@RequestMapping("/api/resident/quota")
public class QuotaController {

    @Autowired
    private AccessTokenService accessTokenService;

    @Autowired
    private ResidentQuotaService residentQuotaService;


    @ResponseBody
    @RequestMapping(value = "/upload", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    public Result upload(@RequestParam(value = "year", defaultValue = "2017", required = true) int year,
                         @RequestParam(value = "uploadfile", defaultValue = "", required = true) MultipartFile multipartFile,
                         HttpServletRequest request, HttpServletResponse response) throws ServiceException {
        String accessToken = request.getParameter("AccessToken");
        AccessToken token = accessTokenService.findByToken(accessToken);

        if (multipartFile == null) {
            throw new ServiceException("请选择需要上传的文件");
        }

        CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile) multipartFile;
        if (commonsMultipartFile.isEmpty()) {
            return Response.responseFail("上传文件为空文件");
        }
        String fileName = commonsMultipartFile.getOriginalFilename();
        if (fileName.indexOf(".xlsx") <= 0 || fileName.indexOf(".xls") <= 0) {
            return Response.responseFail("上传文件应为excel文件格式为：xlsx 或 xls");
        }

        List<QuotaData> proposalDataList = null;
        InputStream inputStream = null;
        try {
            inputStream = commonsMultipartFile.getInputStream();
            Workbook workbook = null;
            if (fileName.indexOf(".xlsx") > 0) {
                workbook = new XSSFWorkbook(inputStream);
            } else {
                workbook = new HSSFWorkbook(inputStream);
            }

            ExcelDataParser parser = new ExcelDataParser();
            proposalDataList = parser.parseQuota(workbook);
            residentQuotaService.parseUploadFile(proposalDataList, year, token.getUserCode());
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new ServiceException(ex.getMessage());
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return Response.response(proposalDataList);
    }

    @RequestMapping(value = "", method = {RequestMethod.GET}, produces = {"application/json;charset=utf-8"})
    public Object search(@RequestParam(name = "year", required = true) int year,
                         @RequestParam(name = "page", required = false, defaultValue = "1") int page,
                         @RequestParam(name = "size", required = false, defaultValue = "10") int size,
                         HttpServletRequest request, HttpServletResponse response) throws ServiceException {
        String accessToken = request.getParameter("AccessToken");
        AccessToken token = accessTokenService.findByToken(accessToken);
        return Response.response(residentQuotaService.search(token.getUserCode(), year, page, size));
    }

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