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.service.AccessTokenService;
import cn.com.countrygarden.bi.main.service.dup.CaseFieldService;
import cn.com.countrygarden.bi.main.service.dup.DupCommService;
import cn.com.countrygarden.bi.main.service.dup.impl.ExcelHelper;
import cn.com.countrygarden.bi.main.service.twerp.hm.TbHsprCommunityService;
import cn.com.countrygarden.bi.main.service.twerp.hm.TbSysOrganService;
import cn.com.countrygarden.bi.main.service.twerp.hm.TbSysUserService;
import cn.com.countrygarden.bi.main.util.MD5;
import com.alibaba.fastjson.JSONObject;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.*;

/**
 * Created by huangzhengjun on 2018/2/6.
 */
//@Controller("caseFieldController")
@RestController()
@RequestMapping("/api/biapp/caseField")
public class CaseFieldController {

    private final Logger logger = LoggerFactory.getLogger(CaseFieldController.class);

    @Autowired
    private Environment env;

    @Autowired
    private DupCommService dupCommService;

    @Autowired
    private AccessTokenService accessTokenService;

    @Autowired
    private CaseFieldService caseFieldService;

    @Autowired
    private TbSysUserService tbSysUserService;

    @Autowired
    private TbSysOrganService tbSysOrganService;

    @Autowired
    private TbHsprCommunityService tbHsprCommunityService;

    /**
     * 附件上传后缀
     */
    public static final String[] ATTACH_TYPE_SUFFIX=new String[]{
            ".bmp.jpg.png.tif.gif.pcx.tga.exif.fpx.svg.psd.cdr.pcd.dxf.ufo.eps.ai.raw.wmf.webp",
            ".txt.zip.pdf.rar.7z.xls.xlsx.doc.docx.ppt.cvs.bmp.jpg.png.tif.gif.pcx.tga.exif.fpx.svg.psd.cdr.pcd.dxf.ufo.eps.ai.raw.wmf.webp"
    };
    /**
     * @param multipartFiles
     * @param request
     * @param response
     * @return
     * @throws ServiceException
     */
    @ResponseBody
    @RequestMapping(value = "/fileUpload", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    public Result upload(
            @RequestParam(value = "type", defaultValue = "", required = true) Integer type,
            @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("请选择需要上传的文件");
        }

        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());

            String fileName = multipartFile.getOriginalFilename();
            int i = fileName.lastIndexOf(".");
            String str = fileName.substring(i);
            String  strtoLowerCase=str.toLowerCase();
            int indeof=(ATTACH_TYPE_SUFFIX[type]).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 {
                throw new ServiceException("上传文件失败，上传文件后缀必须为："+ ATTACH_TYPE_SUFFIX[type]);
            }
        }

        sb.delete(sb.length() - 1, sb.length());

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("files", sb.toString());

        return Response.response(resultMap);
    }


    /**
     * 数据录入
     *
     * @param requestData
     * @param request
     * @return
     * @throws ServiceException
     */
    @ResponseBody
    @RequestMapping(value = "/input", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    public Result input(@RequestBody JSONObject requestData, HttpServletRequest request) throws ServiceException {
        String accessToken = request.getParameter("AccessToken");
        AccessToken token = accessTokenService.findByToken(accessToken);
        String userCode = token.getUserCode();
        Map<String, Object> map = requestData.toJavaObject(Map.class);

        Map<String, Object> resultMap = new HashMap();
        int i = 0;
        //拿到前端传来的案场对象，将其插入数据库中即可
        if (map != null) {
            map.put("createdBy", userCode);
            i = caseFieldService.insertCaseField(map);
        }
        if (i > 0) {
            resultMap.put("result", "录入成功");
        } else {
            resultMap.put("result", "录入失败");

        }
        return Response.response(resultMap);
    }


    /**
     * @param requestData
     * @param request
     * @return
     * @throws ServiceException
     */
    @ResponseBody
    @RequestMapping(value = "/queryByKeys", produces = "application/json;charset=utf-8", method = RequestMethod.GET)
    public Result queryByKeys(@RequestParam(value = "size", required = false, defaultValue = "10") int size,
                              @RequestParam(value = "page", required = false, defaultValue = "1") int page,
                              @RequestParam(value = "organ", required = false) String organ,
                              @RequestParam(value = "comm", required = false) String comm,
                              @RequestParam(value = "caseFieldId", required = false) String caseFieldId,
                              @RequestParam(value = "beginDate", required = false) String beginDate,
                              @RequestParam(value = "endDate", required = false) String endDate,
                              @RequestBody(required = false) JSONObject requestData, HttpServletRequest request) throws ServiceException {
        String accessToken = request.getParameter("AccessToken");
        AccessToken token = accessTokenService.findByToken(accessToken);
        String userCode = token.getUserCode();

        List<String> organs = new ArrayList<>();
        List<String> comms = new ArrayList<>();
//        if (organ == null || "".equals(organ)) {
//
//            List<DupOrgan> organList = dupCommService.findDupCommByUserCode(token.getUserCode(), null, false, false);
//            if (organList != null && organList.size() > 0) {
//                for (DupOrgan dupOrgan : organList) {
//                    organs.add(dupOrgan.getOrganCode());
//                }
//            }
//        }
        //如果传入的项目参数为空，那么就查询登录人的可查看的所有纯案场或者案场常规混合的项目，
        Result queryByKeys = null;
        if (organ == null || "".equals(organ)) {
        	List<Map<String, String>> organList = dupCommService.findCommsByUserCode(userCode);
            if (organList != null && organList.size() > 0) {
                for (Map map : organList) {
                    comms.add(String.valueOf(map.get("commId")));
                }
            }else if (organList == null || organList.size()==0) {
            		return queryByKeys;
            }
        } else if (comm == null || "".equals(comm)) {
        	List<Map<String, String>> commList = dupCommService.findCommsByUserCodeAndOrganCode(userCode, organ);
            if (commList != null && commList.size() > 0) {
                for (Map map : commList) {
                    comms.add(String.valueOf(map.get("commId")));
                }
            }
        }
        List<Map<String, Object>> resultList = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        if (requestData != null) {
            map = requestData.toJavaObject(Map.class);
        } else {
            map.put("organCode", organ);
            map.put("organs", organs);
            map.put("commId", comm);
            map.put("comms", comms);
            map.put("caseField", caseFieldId);
            map.put("beginDate", beginDate);
            map.put("endDate", endDate);
            map.put("page", page);
            map.put("size", size);
        }
        
        queryByKeys = caseFieldService.queryByKeys(map);
        return queryByKeys;
    }


    /**
     * 根据ID进行删除，逻辑删
     *
     * @param request
     * @return
     * @throws ServiceException
     */
    @ResponseBody
    @RequestMapping(value = "/softDeleteById/{id}", produces = "application/json;charset=utf-8", method = RequestMethod.DELETE)
    public Result softDeleteById(@PathVariable("id") int id, HttpServletRequest request) throws ServiceException {
        Map<String, Object> resultMap = new HashMap<>();
        String accessToken = request.getParameter("AccessToken");
        AccessToken token = accessTokenService.findByToken(accessToken);
        String userCode = token.getUserCode();

//        String id = request.getParameter("id");

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("id", id);
        paramMap.put("userCode", userCode);
        int i = caseFieldService.softDeleteById(paramMap);
        if (i > 0) {
            resultMap.put("result", "删除成功");
        } else {
            resultMap.put("result", "删除失败");

        }
        return Response.response(resultMap);
    }


    /**
     * 根据ID对案场信息进行修改
     *
     * @param requestData
     * @param request
     * @return
     * @throws ServiceException
     */
    @ResponseBody
    @RequestMapping(value = "/modifyCaseFieldById", produces = "application/json;charset=utf-8", method = RequestMethod.PUT)
    public Result modifyCaseFieldById(@RequestBody(required = false) JSONObject requestData, HttpServletRequest request) throws ServiceException {
        Map<String, Object> resultMap = new HashMap<>();
        String accessToken = request.getParameter("AccessToken");
        AccessToken token = accessTokenService.findByToken(accessToken);
        String userCode = token.getUserCode();

        Map<String, Object> paramMap = requestData.toJavaObject(Map.class);

        paramMap.put("updatedBy", userCode);
        paramMap.put("updateDate", new Date());

        resultMap = caseFieldService.modifyCaseFieldById(paramMap);

        return Response.response(resultMap);
    }


    /**
     * 查询所有的纯案场或者案场常规混合的区域
     *
     * @param request
     * @return
     * @throws ServiceException
     */
    @ResponseBody
    @RequestMapping(value = "/findCaseFieldOrgans", produces = "application/json;charset=utf-8", method = RequestMethod.GET)
    public Result findCaseFieldOrgans(HttpServletRequest request) throws ServiceException {
        List<Map<String, Object>> resultList = new ArrayList<>();
        String accessToken = request.getParameter("AccessToken");
        AccessToken token = accessTokenService.findByToken(accessToken);
        String userCode = token.getUserCode();

        //查询用户信息，拿到organID
//        List<DupOrgan> organList = dupCommService.findDupCommByUserCode(token.getUserCode(), null, false, false);
//        String organCode = "";
//        if (organList != null && organList.size() > 0) {
//            organCode = organList.get(0).getOrganCode();
//        }
//        List<Map<String, Object>> caseFieldOrgans = tbSysOrganService.findCaseFieldOrgans(organCode);
        List<Map<String, String>> organsByUserCode = dupCommService.findOrgansByUserCode(userCode);

        return Response.response(organsByUserCode);
    }

    /**
     * 查询所有的纯案场或者案场常规混合的项目
     *
     * @param request
     * @return
     * @throws ServiceException
     */
    @ResponseBody
    @RequestMapping(value = "/findCaseFieldCommByOrganCode", produces = "application/json;charset=utf-8", method = RequestMethod.GET)
    public Result findCaseFieldCommByOrganCode(
            @RequestParam(value = "organCode", required = true) String organCode,
            HttpServletRequest request) throws ServiceException {
        String accessToken = request.getParameter("AccessToken");
        AccessToken token = accessTokenService.findByToken(accessToken);
        String userCode = token.getUserCode();

//        Map<String, Object> paramMap = new HashMap<>();
//
//        String newOrgan = null;
//        List<DupOrgan> organList = dupCommService.findDupCommByUserCode(token.getUserCode(), null, false, false);
//        if (organList != null && organList.size() == 1) {
//            DupOrgan dupOrgan = organList.get(0);
//            newOrgan = dupOrgan.getOrganCode();
//        }
//
//        if (organCode == null || "".equals(organCode)) {
//            paramMap.put("organCode", newOrgan);
//            organCode = newOrgan;
//        }
//
//        List<Map<String, Object>> caseFieldCommByOrganCode = tbHsprCommunityService.findCaseFieldCommByOrganCode(organCode);
        List<Map<String, String>> commsByUserCodeAndOrganCode = dupCommService.findCommsByUserCodeAndOrganCode(userCode, organCode);

        return Response.response(commsByUserCodeAndOrganCode);

    }


    /**
     * 导出案场基础信息
     *
     * @param organ
     * @param comm
     * @param caseField
     * @param beginDate
     * @param endDate
     * @param size
     * @param page
     * @param requestData
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/output", produces = "application/json; charset=utf-8", method = RequestMethod.GET)
    public Result outputSummary(@RequestParam(value = "organCode", required = false) String organ,
                                @RequestParam(value = "commId", required = false) String comm,
                                @RequestParam(value = "caseFieldId", required = false) String caseField,
                                @RequestParam(value = "beginDate", required = false) String beginDate,
                                @RequestParam(value = "endDate", required = false) String endDate,
                                @RequestParam(value = "size", required = false, defaultValue = "10") int size,
                                @RequestParam(value = "page", required = false, defaultValue = "1") int page,
                                @RequestBody(required = false) JSONObject requestData,
                                HttpServletRequest request, HttpServletResponse response) {
        String accessToken = request.getParameter("AccessToken");
        AccessToken token = accessTokenService.findByToken(accessToken);
        String userCode = token.getUserCode();

        List<String> organs = new ArrayList<>();
        List<String> comms = new ArrayList<>();
        //如果传入的项目参数为空，那么就查询登录人的可查看的所有纯案场或者案场常规混合的项目，
        if (organ == null || "".equals(organ)) {
            List<Map<String, String>> organList = dupCommService.findCommsByUserCode(userCode);
            if (organList != null && organList.size() > 0) {
                for (Map map : organList) {
                    comms.add(String.valueOf(map.get("commId")));
                }
            }
        } else if (comm == null || "".equals(comm)) {
            List<Map<String, String>> commList = dupCommService.findCommsByUserCodeAndOrganCode(userCode, organ);
            if (commList != null && commList.size() > 0) {
                for (Map map : commList) {
                    comms.add(String.valueOf(map.get("commId")));
                }
            }
        }

        List<Map<String, Object>> resultList = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        if (requestData != null) {
            map = requestData.toJavaObject(Map.class);
        } else {
            map.put("organCode", organ);
            map.put("organs", organs);
            map.put("commId", comm);
            map.put("comms", comms);
            map.put("caseField", caseField);
            map.put("beginDate", beginDate);
            map.put("endDate", endDate);
            map.put("page", page);
            map.put("size", 999999);
        }

        Result result = caseFieldService.queryByKeys(map);
        Object data = result.getData();

//        PageData pageData = reportWeeklyService.searchSummary(token.getUserCode(), searchKey, organId, contractorName, startDteStr, endDateStr, state, 1, 0);
        ExcelHelper helper = new ExcelHelper();
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet();
        //创建头部
        helper.createCaseFieldHeader(workbook, sheet);
        //创建正文体
        helper.createCaseFieldBody(result, 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;
    }
    
}
