package com.house365.web.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.house365.beans.entity.DepartmentEntity;
import com.house365.commons.system.HttpClientUtil;
import com.house365.web.util.MemoryPropertyPlaceholderConfigurer;
import com.house365.web.util.SessionConstants;
import com.house365.ws.beans.request.ProjectListRequest;
import com.house365.ws.beans.response.ProjectListResponse;
import com.house365.ws.beans.util.HResult;
import com.house365.ws.interfaces.server.IProject;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author hqc
 */
@Controller
@RequestMapping("remote")
public class RemoteController {

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

    @Autowired
    private IProject project;

    @ResponseBody
    @RequestMapping(value = "projectList", method = {RequestMethod.GET, RequestMethod.POST})
    public String projectList(HttpServletRequest request) {
        DepartmentEntity currDept = (DepartmentEntity) request.getSession()
                .getAttribute(SessionConstants.SESSION_CURRNET_DEPT_KEY);

        String result = "";
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("s", "/Api/getProInfo"));
        params.add(new BasicNameValuePair("city", currDept.getDescripition()));
        params.add(new BasicNameValuePair("limit", request
                .getParameter("limit")));
        params.add(new BasicNameValuePair("contract", request.getParameter("contractCode")));

        try {
            result = HttpClientUtil.doGet(MemoryPropertyPlaceholderConfigurer.getContextProperty("projects.server.url"), params);
        } catch (IOException ex) {
            logger.error("调用服务失败", ex);
        } catch (Throwable ex) {
            logger.error("调用服务失败", ex);
        }
        return result;

    }

    @ResponseBody
    @RequestMapping(value = "/getProject")
    public HResult getProject(HttpServletRequest request) {
        HResult response = new HResult();
        try {
            DepartmentEntity currDept = (DepartmentEntity) request.getSession().getAttribute(SessionConstants.SESSION_CURRNET_DEPT_KEY);
            String oldContractNo = request.getParameter("oldContractNo");
            String contractCode = request.getParameter("contractCode");
            String city = currDept.getDescripition();
            //当判断为新输入的合同号，做查重校验
            if (!contractCode.equals(oldContractNo)) {
                ProjectListRequest req = new ProjectListRequest();
                Map<String, Object> paraMap = new HashMap<>(10);
                paraMap.put("EQ_contractCode", contractCode);
                paraMap.put("EQ_city", city);
                req.setSearchParams(paraMap);
                req.setLimit(1);
                ProjectListResponse projectList = project.getProjectList(req);
                if (CollectionUtils.isNotEmpty(projectList.getObjectList())) {
                    response.setStatus(101);
                    response.setErrorMessage("该项目已存在");
                }
            }

            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("s", "/Api/getProInfo"));
            params.add(new BasicNameValuePair("city", city));
            params.add(new BasicNameValuePair("limit", request.getParameter("limit")));
            params.add(new BasicNameValuePair("contract", contractCode));
            params.add(new BasicNameValuePair("isAccurate", "1"));

            String result = HttpClientUtil.doGet(MemoryPropertyPlaceholderConfigurer.getContextProperty("projects.server.url"), params);
            if (result != null) {
                ObjectMapper objectMapper = new ObjectMapper();
                Map<String, Object> resultMap = objectMapper.readValue(result, Map.class);
                boolean status = (boolean) resultMap.get("status");
                if (status) {
                    if (resultMap.get("data") != null) {
                        List<Map<String, Object>> list = (List<Map<String, Object>>) resultMap.get("data");
                        if (CollectionUtils.isNotEmpty(list)) {
                            response.setData(list.get(0));
                        } else {
                            response.setStatus(101);
                            response.setErrorMessage("经管系统中未找到该合同号，请核实");
                        }
                    }
                } else {
                    response.setStatus(101);
                    response.setErrorMessage("经管系统中未找到该合同号，请核实");
                }
            } else {
                response.setStatus(101);
                response.setErrorMessage("经管系统中未找到该合同号，请核实");
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(101);
            response.setErrorMessage("根据合同号获取project失败");
            logger.error("根据合同号获取project失败", e);
        }
        return response;
    }

}
