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.twerp.hm.TbSysUser;
import cn.com.countrygarden.bi.main.service.AccessTokenService;
import cn.com.countrygarden.bi.main.service.dup.CaseFieldInfoService;
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.TbSysUserService;
import com.alibaba.fastjson.JSONObject;
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.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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by huangzhengjun on 2018/2/8.
 */
@RestController()
@RequestMapping("/api/biapp/caseFieldInfo")
public class CaseFieldInfoController {

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

    @Autowired
    private AccessTokenService accessTokenService;

    @Autowired
    private DupCommService dupCommService;

    @Autowired
    private CaseFieldInfoService caseFieldInfoService;

    @Autowired
    private TbSysUserService tbSysUserService;

    /**
     * 录入案场基础信息
     *
     * @param requestData
     * @param request
     * @return
     * @throws ServiceException
     */
    @ResponseBody
    @RequestMapping(value = "/insertCaseFieldInfo", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    public Result insertCaseFieldInfo(@RequestBody 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("createdBy", userCode);

        int i = caseFieldInfoService.insertCaseFieldInfo(paramMap);
        if (i > 0) {
            resultMap.put("result", "添加成功");
        } else {
            resultMap.put("result", "添加失败");

        }
        return Response.response(resultMap);
    }


    /**
     * 修改案场基础信息
     *
     * @param requestData
     * @param request
     * @return
     * @throws ServiceException
     */
    @ResponseBody
    @RequestMapping(value = "/modifyCaseFieldInfo", produces = "application/json;charset=utf-8", method = RequestMethod.PUT)
    public Result modifyCaseFieldInfo(@RequestBody JSONObject requestData, HttpServletRequest request) throws ServiceException {

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

        Map<String, Object> resultMap = caseFieldInfoService.modifyCaseFieldInfo(paramMap);
        return Response.response(resultMap);

    }


    /**
     * 软删除案场基础信息
     *
     * @param request
     * @return
     * @throws ServiceException
     */
    @ResponseBody
    @RequestMapping(value = "/deleteCaseFieldInfoById/{id}", produces = "application/json;charset=utf-8", method = RequestMethod.DELETE)
    public Result deleteCaseFieldInfoById(@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();

//        int id = Integer.parseInt(request.getParameter("id"));

        int i = caseFieldInfoService.deleteCaseFieldInfoById(id, userCode);
        if (i > 0) {
            resultMap.put("result", "删除成功");
        } else {
            resultMap.put("result", "删除失败");

        }
        return Response.response(resultMap);
    }

    /**
     * 按条件查询案场基础信息
     *
     * @param request
     * @return
     * @throws ServiceException
     */
    @ResponseBody
    @RequestMapping(value = "/queryCaseFieldInfo", produces = "application/json;charset=utf-8", method = RequestMethod.GET)
    public Result queryCaseFieldInfo(@RequestParam(value = "size", required = false, defaultValue = "10") int size,
                                     @RequestParam(value = "page", required = false, defaultValue = "1") int page,
                                     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 organCode = request.getParameter("organCode");
        String commId = request.getParameter("commId");
        String caseFieldId = request.getParameter("caseFieldId");
        //默认展示改用户所在区域或项目下的所有案场信息
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("organCode", organCode);

        TbSysUser byUserCode = tbSysUserService.findByUserCode(userCode);
//        List<DupOrgan> organList = dupCommService.findDupCommByUserCode(token.getUserCode(), null, false, false);
        String newOrgan = null;
        List<String> organs = new ArrayList<>();
        List<String> comms = new ArrayList<>();
        Result queryCaseFieldInfo =  null ;
        //如果传入的项目参数为空，那么就查询登录人的可查看的所有纯案场或者案场常规混合的项目，
        if (organCode == null || "".equals(organCode)) {
            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 queryCaseFieldInfo;
            }
        } else if (commId == null || "".equals(commId)) {
            List<Map<String, String>> commList = dupCommService.findCommsByUserCodeAndOrganCode(userCode, organCode);
            if (commList != null && commList.size() > 0) {
                for (Map map : commList) {
                    comms.add(String.valueOf(map.get("commId")));
                }
            }
        } else {
            paramMap.put("commId", commId);
        }


//        if (organList != null && organList.size() >0) {
//            for (DupOrgan dupOrgan1:organList){
//                organs.add(dupOrgan1.getOrganCode());
//            }
//        }
//        List<ErpCommunity> communityList = null;
//        if (organCode == null || "".equals(organCode)) {
//            paramMap.put("organCode", newOrgan);
//            paramMap.put("organs",organs);
//            communityList = dupCommService.findByUserCode(userCode, newOrgan, false);
//        } else {
//            communityList = dupCommService.findByUserCode(userCode, organCode, false);
//        }

//        String newCommId = null;
//        List<String> commIds = new ArrayList<>();
//        if (communityList != null && communityList.size() > 0) {
//            for (ErpCommunity community : communityList) {
//                commIds.add(community.getCommId());
//            }
//        }


//        if (commId != null && !"".equals(commId)) {
//
//            paramMap.put("commId", commId);
//        } else if (commIds != null) {
//            paramMap.put("commIds", commIds);
//        }

        paramMap.put("commIds", comms);
        paramMap.put("caseFieldId", caseFieldId);
        paramMap.put("page", page);
        paramMap.put("size", size);
        queryCaseFieldInfo = caseFieldInfoService.queryCaseFieldInfo(paramMap);

        return queryCaseFieldInfo;
    }


    /**
     * 导出案场名称信息
     *
     * @param organCode
     * @param commId
     * @param caseFieldId
     * @param size
     * @param page
     * @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 organCode,
                                @RequestParam(value = "commId", required = false) String commId,
                                @RequestParam(value = "caseFieldId", required = false) String caseFieldId,
                                @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);
        String userCode = token.getUserCode();

        //默认展示改用户所在区域或项目下的所有案场信息
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("organCode", organCode);

        TbSysUser byUserCode = tbSysUserService.findByUserCode(userCode);
//        List<DupOrgan> organList = dupCommService.findDupCommByUserCode(token.getUserCode(), null, false, false);
        String newOrgan = null;
        List<String> organs = new ArrayList<>();
        List<String> comms = new ArrayList<>();

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

        paramMap.put("commIds", comms);
        paramMap.put("caseFieldId", caseFieldId);
        paramMap.put("page", page);
        paramMap.put("size", 99999);

        Result result = caseFieldInfoService.queryCaseFieldInfo(paramMap);

        Object data = result.getData();

        ExcelHelper helper = new ExcelHelper();
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet();
        //创建头部
        helper.createCaseFieldInfoHeader(workbook, sheet);
        //创建正文体
        helper.createCaseFieldInfoBody(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;
    }

}
