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.ManagerData;
import cn.com.countrygarden.bi.main.service.AccessTokenService;
import cn.com.countrygarden.bi.main.service.dup.ManagerDataService;
import cn.com.countrygarden.bi.main.service.dup.impl.ExcelHelper;
import cn.com.countrygarden.bi.main.service.dup.impl.ManagerDataSchedule;
import cn.com.countrygarden.bi.main.util.MD5;
import cn.com.countrygarden.bi.main.util.RedisUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
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.core.env.Environment;
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.File;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by chenweijiang on 2017/9/11.
 */
@RestController()
@RequestMapping("/api/fenghuang/manager")
public class ManagerDataController {
    @Autowired
    private ManagerDataService managerDataService;
    @Autowired
    private Environment env;
    @Autowired
    private AccessTokenService accessTokenService;

    @RequestMapping(value = "/search", produces = "application/json;charset=utf-8",  method = RequestMethod.GET)
    public Object findManagerData(@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,
                                  HttpServletRequest request, HttpServletResponse response){
        String accessToken = request.getParameter("AccessToken");
        AccessToken token = accessTokenService.findByToken(accessToken);
        return managerDataService.findManagerData(isUnFinished,organCode,commId,startDateStr,endDateStr,token.getUserCode(),size,page);
    }

    @RequestMapping(value = "/export", produces = "multipart/form-data",  method = RequestMethod.GET)
    public Object exportManagerData(@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,

                                  HttpServletRequest request, HttpServletResponse response){
        String accessToken = request.getParameter("AccessToken");
        AccessToken token = accessTokenService.findByToken(accessToken);
        Result result = managerDataService.findManagerData(isUnFinished,organCode,commId,startDateStr,endDateStr,token.getUserCode(),0,1);

        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet();
        ExcelHelper helper = new ExcelHelper();
        helper.createManagerHeader(workbook,sheet);
        helper.createManageBody((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;

    }

    @RequestMapping(value = "/lastmanagers", produces = "application/json;charset=utf-8",  method = RequestMethod.GET)
    public Object findLastInsertManagers(@RequestParam(value = "organCode",required = false,defaultValue = "") String organCode,
                                         @RequestParam(value = "commId",required = false,defaultValue = "") String commId,
                                         @RequestParam(value = "startDate",required = false)String startDateStr,
                                         @RequestParam(value = "endDate",required = false)String endDateStr,
                                         @RequestParam(value = "startDateInquire",required = false)String startDateInquire,
                                         @RequestParam(value = "endDateInquire",required = false)String endDateInquire,
                                         HttpServletRequest request, HttpServletResponse response){
        if(StringUtils.isEmpty(organCode) || StringUtils.isEmpty(commId)){
            return Response.responseFail("请先选择区域与项目");
        }
        String accessToken = request.getParameter("AccessToken");
        AccessToken token = accessTokenService.findByToken(accessToken);
        List<ManagerData> managers = managerDataService.findLastManagers(organCode,commId,startDateStr,endDateStr,startDateInquire,endDateInquire);
        return Response.response(managers);
    }

    @RequestMapping(value = "/add", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    public Object addManagerDatas(@RequestBody List<ManagerData> managerDatas,
                                         HttpServletRequest request, HttpServletResponse response){

        String accessToken = request.getParameter("AccessToken");
        AccessToken token = accessTokenService.findByToken(accessToken);
        if(managerDatas.size()<=0){
            return Response.responseFail("请先填写完整项目信息");
        }
        managerDataService.addManagers(managerDatas,token.getUserCode());
        return Response.response("");
    }


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

        //记录上传的文件名称
        StringBuilder sb = new StringBuilder();

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

        String fileName = "";
        for (MultipartFile multipartFile : multipartFiles) {

            String basePath = env.getProperty("resident.file.path");
            String accessPath = env.getProperty("resident.file.url.base");
            if (StringUtils.isEmpty(basePath)) {
                basePath = request.getServletContext().getRealPath("");
            }
            //save file
            Instant instant = Instant.now();
            LocalDateTime dateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());

            fileName = multipartFile.getOriginalFilename();
            int i = fileName.lastIndexOf(".");
            String str = fileName.substring(i);
            String  strtoLowerCase=str.toLowerCase();
                int indeof=(".ppt.doc.xlsx.xls.docx.rar.zip.pdf.7z").indexOf
                        (strtoLowerCase);

                if(indeof!=-1){

            //文件存放路径 /uploadFile/年/月/日/时/分/秒
            String saveDirectory = "/uploadFile/" + dateTime.getYear() + "/"
                    + dateTime.getMonthValue() + "/" + dateTime.getDayOfMonth()
                    + "/" + dateTime.getHour() + dateTime.getMinute() + dateTime.getSecond();

            String saveFileName = saveDirectory + "/" + MD5.GetMD5Code(dateTime.toString()) + FilenameUtils.getBaseName(fileName) + "." + FilenameUtils.getExtension(fileName);
//            String saveFileName = saveDirectory + "/" + fileName;
            File dir = new File(basePath + saveDirectory);

            if (!dir.exists()) {
                dir.mkdirs();
            }
            sb.append(accessPath + saveFileName + ",");
            File saveFile = new File(basePath + saveFileName);
            try {
                ((CommonsMultipartFile) multipartFile).getFileItem().write(saveFile);
            } catch (Exception e) {

                throw new ServiceException("无法保存上传文件：" + e.getMessage());
            }
            }else {
                return Response.responseFail("无法保存上传文件");
            }
        }
        sb.delete(sb.length() - 1, sb.length());
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("name", fileName);
        resultMap.put("url", sb.toString());
        return Response.response(resultMap);



    }


    @RequestMapping(value = "/update",produces = "application/json;charset=utf-8",  method = RequestMethod.POST)
    public Object updateManagerData(@RequestBody ManagerData managerData,
                                  HttpServletRequest request, HttpServletResponse response){

        String accessToken = request.getParameter("AccessToken");
        AccessToken token = accessTokenService.findByToken(accessToken);
        managerDataService.updateManagerData(managerData, token.getUserCode());
        return Response.response("");
    }

    @RequestMapping(value = "/delete/{id}",produces = "application/json;charset=utf-8",  method = RequestMethod.DELETE)
    public Object deleteManagerData(@PathVariable("id") int managerDataId,
                                    HttpServletRequest request, HttpServletResponse response){

        String accessToken = request.getParameter("AccessToken");
        AccessToken token = accessTokenService.findByToken(accessToken);
        managerDataService.deleteManagerData(managerDataId, token.getUserCode());

        return Response.response("");
    }

    @Autowired
    private ManagerDataSchedule managerDataSchedule;

    @RequestMapping(value = "/managerDataSchedule", produces = "application/json;charset=utf-8", method = RequestMethod.GET)
    public Result managerDataSchedule(@RequestParam(value = "type",defaultValue = "0")int type){
        if(type==1)RedisUtils.del(ManagerDataSchedule.cacheKey);
        managerDataSchedule.syncErpToUserTarget();
        return Response.response();
    }



}
