package com.house365.web.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.house365.beans.entity.CustomerEntity;
import com.house365.beans.entity.PropertyReportEntity;
import com.house365.beans.entity.ReportHouseEntity;
import com.house365.beans.entity.UserEntity;
import com.house365.beans.system.Page;
import com.house365.beans.vo.PropertyReportVo;
import com.house365.commons.system.HttpClientUtil;
import com.house365.web.system.controller.BaseController;
import com.house365.web.util.MemoryPropertyPlaceholderConfigurer;
import com.house365.web.util.MobileUtil;
import com.house365.web.util.SessionConstants;
import com.house365.ws.beans.request.MapListRequest;
import com.house365.ws.beans.response.MapListResponse;
import com.house365.ws.beans.util.HResult;
import com.house365.ws.interfaces.server.ICustomer;
import com.house365.ws.interfaces.server.IPropertyReportInterface;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
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.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springside.modules.web.Servlets;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.RoundingMode;
import java.text.NumberFormat;
import java.util.*;

/**
 * 置业报告controller
 *
 * @author Created by Administrator on 2020/4/17.
 */
@Controller
@RequestMapping("/propertyreport")
public class PropertyReportController extends BaseController {

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

    @Autowired
    private IPropertyReportInterface reportInterface;
    @Autowired
    private ICustomer customer;


    /**
     * 置业报告列表
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/list")
    public String list(Integer number, Model model, HttpServletRequest request) {
        try {
            UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
            String city = (String) request.getSession().getAttribute("city");
            Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
            searchParams.put("userId", userEntity.getId());
            searchParams.put("city", city);
            Page page = new Page(50);
            if (null != number) {
                page.setCurrentPage(number);
            }
            MapListRequest listRequest = new MapListRequest();
            listRequest.setPaging(page);
            listRequest.setSearchParams(searchParams);
            MapListResponse response = reportInterface.list(listRequest);

            List<Map<String, Object>> objectList = response.getObjectList();
            if(userEntity.getShowMobile() != 1) {
                for (Map<String, Object> i : objectList) {
                    if(i != null && i.containsKey("phone")) {
                        i.replace("phone",MobileUtil.hidePhone(String.valueOf(i.get("phone"))));
                    }
                }
            }

            model.addAttribute("page", response.getPaging());
            model.addAttribute("dataList", objectList);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("置业报告列表", e);
        }
        return getAutoUrl();
    }

    /**
     * 跳转新增置业报告
     *
     * @return 结果视图
     */
    @RequestMapping(value = "toAdd/{customerId}")
    public String toAdd(Model model, @PathVariable int customerId,HttpServletRequest request) {
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        CustomerEntity entity = customer.queryById(customerId);
        if(userEntity.getShowMobile() != 1) {
            entity.setPhone(MobileUtil.hidePhone(entity.getPhone()));
        }
        model.addAttribute("data", entity);
        return getAutoUrl("add");
    }

    /**
     * 新增置业报告
     *
     * @return 结果视图
     */
    @RequestMapping(value = "/save", method = {RequestMethod.POST})
    @ResponseBody
    public HResult save(@RequestBody PropertyReportVo vo, HttpServletRequest request) {
        HResult result = new HResult();
        try {
            UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
            String city = (String) request.getSession().getAttribute("city");
            Date date = new Date();
            PropertyReportEntity entity = vo.getEntity();
            String district = "";
            String districtId = "";
            String distr = dealDis(entity.getDistrict(), district, districtId);
            districtId = distr.split("-")[1];
            if (districtId.contains(",")) {
                districtId = districtId.substring(0, districtId.lastIndexOf(","));
            }
            district = distr.split("-")[0];
            if (district.contains(",")) {
                district = district.substring(0, district.lastIndexOf(","));
            }
            entity.setDistrict(district);
            entity.setDistrictId(districtId);
            entity.setCreateId(userEntity.getId());
            entity.setCreateName(userEntity.getRealName());
            entity.setUpdateId(userEntity.getId());
            entity.setUpdateName(userEntity.getRealName());
            entity.setCreateTime(date);
            entity.setUpdateTime(date);
            entity.setSendStatus(0);
            entity.setReportUrl("");
            entity.setCity(city);
            result = reportInterface.save(vo, city);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("新增置业报告失败", e);
            result.setStatus(-1);
            result.setErrorMessage("新增置业报告失败");
        }
        return result;
    }

    /**
     * 跳转修改置业报告
     *
     * @return 结果视图
     */
    @RequestMapping(value = "toEdit/{customerId}")
    public String toEdit(Model model, @PathVariable int customerId,HttpServletRequest request) {
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        CustomerEntity entity = customer.queryById(customerId);
        Map<String, Object> map = new HashMap<>(5);
        map.put("customerId", customerId);
        List<PropertyReportEntity> reportList = reportInterface.queryByConditions(map);
        if (CollectionUtils.isNotEmpty(reportList)) {
            PropertyReportEntity report = reportList.get(0);

            String districtId = report.getDistrictId();
            String district = report.getDistrict();
            if (district.contains(",")) {
                String[] disArray = district.split(",");
                String[] disIdArray = districtId.split(",");
                StringBuilder builder = new StringBuilder();
                for (int i = 0; i < disArray.length; i++) {
                    builder.append("'").append(disIdArray[i]).append("-").append(disArray[i]).append("'").append(",");
                }
                districtId = "[" + builder.toString().substring(0, builder.toString().lastIndexOf(",")) + "]";
            } else {
                districtId = "[" + "'" + districtId + "-" + district + "'" + "]";
            }
            report.setDistrictId(districtId);
            String roomType = report.getRoomType();
            roomType = "[" + roomType + "]";
            report.setRoomType(roomType);
            String channel = report.getChannel();
            channel = "[" + channel + "]";
            report.setChannel(channel);
            model.addAttribute("report", report);
        }
        if(userEntity.getShowMobile() != 1) {
            entity.setPhone(MobileUtil.hidePhone(entity.getPhone()));
        }
        model.addAttribute("data", entity);
        return getAutoUrl("update");
    }


    /**
     * 修改置业报告
     *
     * @return 结果视图
     */
    @RequestMapping(value = "/update", method = {RequestMethod.POST})
    @ResponseBody
    public HResult update(@RequestBody PropertyReportVo vo, HttpServletRequest request) {
        HResult result = new HResult();
        try {
            UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
            String city = (String) request.getSession().getAttribute("city");
            Date date = new Date();
            PropertyReportEntity entity = vo.getEntity();
            PropertyReportEntity oldEntity = reportInterface.getById(entity.getId());
            String district = "";
            String districtId = "";
            String distr = dealDis(entity.getDistrict(), district, districtId);
            districtId = distr.split("-")[1];
            district = distr.split("-")[0];
            if (district.contains(",")) {
                district = district.substring(0, district.lastIndexOf(","));
                districtId = districtId.substring(0, districtId.lastIndexOf(","));
            }
            oldEntity.setDistrict(district);
            oldEntity.setDistrictId(districtId);
            oldEntity.setSex(entity.getSex());
            oldEntity.setTotalPriceMin(entity.getTotalPriceMin());
            oldEntity.setTotalPriceMax(entity.getTotalPriceMax());
            oldEntity.setDownPaymentMin(entity.getDownPaymentMin());
            oldEntity.setDownPaymentMax(entity.getDownPaymentMax());
            oldEntity.setAreaMin(entity.getAreaMin());
            oldEntity.setAreaMax(entity.getAreaMax());
            oldEntity.setChannel(entity.getChannel());
            oldEntity.setRoomType(entity.getRoomType());
            oldEntity.setHasAttach(entity.getHasAttach());
            oldEntity.setBuyPurpose(entity.getBuyPurpose());
            oldEntity.setIsLoan(entity.getIsLoan());
            oldEntity.setDownPaymentRatio(entity.getDownPaymentRatio());
            oldEntity.setUpdateId(entity.getId());
            oldEntity.setUpdateName(userEntity.getRealName());
            oldEntity.setUpdateTime(date);
            vo.setEntity(oldEntity);

            result = reportInterface.update(vo, city);
        } catch (Exception e) {
            result.setStatus(-1);
            result.setErrorMessage("修改置业报告失败");
            e.printStackTrace();
            logger.error("修改置业报告失败", e);
        }
        return result;
    }

    /**
     * 查询置业报告对应楼盘
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/getHouse/{id}", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public HResult getHouse(@PathVariable int id) {
        HResult result = new HResult();
        try {
            List<ReportHouseEntity> houseList = reportInterface.queryHouse(id, 1);
            result.setData(houseList);
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus(500);
            result.setErrorMessage("查询置业报告对应楼盘失败");
            logger.error("查询置业报告对应楼盘失败", e);

        }
        return result;
    }

    /**
     * 获取城市配置
     *
     * @param session
     * @return
     */
    @RequestMapping(value = "/getCityConf", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public HResult getCityConf(HttpSession session) {
        HResult result = new HResult();
        try {
            String city = (String) session.getAttribute("city");
            String url = "http://newapi.house365.com/city/config";
            List<NameValuePair> queryParams = new ArrayList<>(5);
            queryParams.add(new BasicNameValuePair("city", city));
            String data = HttpClientUtil.doGet(url, queryParams, 60000, "utf-8");

            ObjectMapper objectMapper = new ObjectMapper();
            List<Map<String, Object>> list = new ArrayList<>();
            if (data != null) {
                Map<String, Map<String, Map>> map = objectMapper.readValue(data, Map.class);
                Map<String, String> resultMap = map.get("data").get("district");
                for (Map.Entry<String, String> entry : resultMap.entrySet()) {
                    Map<String, Object> dataMap = new HashMap<>(5);
                    dataMap.put("id", entry.getKey());
                    dataMap.put("name", entry.getValue());
                    list.add(dataMap);
                }
                result.setData(list);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus(500);
            result.setErrorMessage("获取城市配置接口报错");
            logger.error("获取城市配置接口报错", e);

        }
        return result;
    }

    /**
     * 调用新房接口查询楼盘数据
     *
     * @param session
     * @return
     */
    @RequestMapping(value = "/searchHouse/{type}", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public HResult searchHouse(HttpSession session, @RequestBody PropertyReportEntity entity, @PathVariable int type) {
        HResult result = new HResult();
        try {
            String city = (String) session.getAttribute("city");
            String dis = entity.getDistrict();
            String district = "";
            String districtId = "";
            int isLoan = entity.getIsLoan();
            int downPaymentRatio = entity.getDownPaymentRatio();
            if (type == 1) {
                String distr = dealDis(dis, district, districtId);
                districtId = distr.split("-")[1];
            }
            String url = "http://mapi.house365.com/taofang/v1.0/xf";
            List<NameValuePair> queryParams = new ArrayList<>(10);
            queryParams.add(new BasicNameValuePair("method", "getHxList"));
            queryParams.add(new BasicNameValuePair("city", city));
            if (type == 1) {
                queryParams.add(new BasicNameValuePair("total_price_min", String.valueOf(entity.getTotalPriceMin())));
                queryParams.add(new BasicNameValuePair("total_price_max", String.valueOf(entity.getTotalPriceMax())));
                queryParams.add(new BasicNameValuePair("area_min", String.valueOf(entity.getAreaMin())));
                queryParams.add(new BasicNameValuePair("area_max", String.valueOf(entity.getAreaMax())));

                queryParams.add(new BasicNameValuePair("channel", entity.getChannel()));
                queryParams.add(new BasicNameValuePair("shi", entity.getRoomType()));
            } else {
                //把楼盘名称赋在客户名方便查询用
                queryParams.add(new BasicNameValuePair("itemname", entity.getCustomerName()));
            }
            queryParams.add(new BasicNameValuePair("page", "1"));
            queryParams.add(new BasicNameValuePair("page_size", "100"));

            queryParams.add(new BasicNameValuePair("dist", districtId));
            String data = HttpClientUtil.doGet(url, queryParams);
            ObjectMapper objectMapper = new ObjectMapper();
            if (data != null) {
                Map<String, Map<String, Map>> map = objectMapper.readValue(data, Map.class);
                List<Map<String, Object>> list = (List<Map<String, Object>>) map.get("data");
                if (CollectionUtils.isNotEmpty(list)) {
                    for (Map<String, Object> m : list) {
                        String totalPrice = m.get("pic_hx_totalprice").toString();

                        double downPayment;
                        double price;
                        if (StringUtils.isNotBlank(totalPrice) && !"0".equals(totalPrice)) {
                            if (isLoan == 0) {
                                downPayment = Math.round(Double.valueOf(totalPrice));
                                m.put("monthPay", "0");
                                m.put("downPayment", downPayment);
                            } else {
                                if (downPaymentRatio != 0) {
                                    downPayment = Double.valueOf(totalPrice) * downPaymentRatio / 100;
                                } else {
                                    downPayment = Double.valueOf(totalPrice) * 30 / 100;
                                }
                                downPayment = Math.round(downPayment);
                                price = Math.round(Double.valueOf(totalPrice) - downPayment);

                                String payUrl = MemoryPropertyPlaceholderConfigurer.getContextProperty("get.pay.url");
                                List<NameValuePair> params = new ArrayList<>(10);
                                params.add(new BasicNameValuePair("method", "calculator.mortgage"));
                                params.add(new BasicNameValuePair("loantype", "1"));
                                params.add(new BasicNameValuePair("calmethod", "1"));
                                params.add(new BasicNameValuePair("bl_year", "30"));
                                params.add(new BasicNameValuePair("bl_rates", "4.9"));
                                params.add(new BasicNameValuePair("bl", String.valueOf(price)));
                                String payData = HttpClientUtil.doGet(payUrl, params);
                                JSONObject json = JSONObject.fromObject(payData);
                                Number code = (Number) json.get("result");
                                if (code.intValue() == 1) {
                                    JSONArray array = (JSONArray) json.get("data");
                                    for (int i = 0; i < array.size(); i++) {
                                        JSONObject obj = array.getJSONObject(i);
                                        String name = obj.get("name").toString();
                                        if ("等额本息".equals(name)) {
                                            JSONObject objData = (JSONObject) obj.get("data");
                                            String payMoney = objData.get("monthlyPayment").toString();
//                                            double pay = Math.round(Double.valueOf(payMoney) / 10000 * 100) * 0.01d;
                                            String pay = formatDouble(Double.valueOf(payMoney) / 10000);
                                            m.put("monthPay", pay);
                                            m.put("downPayment", downPayment);
                                        }
                                    }
                                } else {
                                    result.setStatus(500);
                                    result.setErrorMessage("查询月供接口失败");
                                    return result;
                                }
                            }
                        } else {
                            downPayment = 0;
                            m.put("monthPay", "0");
                            m.put("downPayment", downPayment);
                        }

                        String room = "";
                        String shi = m.get("pic_type").toString();
                        if ("8".equals(shi)) {
                            room += "1室";
                        } else if ("9".equals(shi)) {
                            room += "2室";
                        } else if ("10".equals(shi)) {
                            room += "3室";
                        } else if ("11".equals(shi)) {
                            room += "4室";
                        } else if ("21".equals(shi)) {
                            room += "5室";
                        } else if ("22".equals(shi)) {
                            room += "6室";
                        }
                        room += m.get("pic_ting").toString() + "厅" + m.get("pic_chu").toString() + "厨" + m.get("pic_wei").toString() + "卫";
                        m.put("room", room);
                        String sale = "";
                        int salestat = Integer.valueOf(m.get("salestat").toString());
                        if (salestat == 1) {
                            sale = "地块";
                        } else if (salestat == 2) {
                            sale = "新盘";
                        } else if (salestat == 3) {
                            sale = "在售";
                        } else if (salestat == 4) {
                            sale = "尾盘";
                        } else if (salestat == 5) {
                            sale = "售空";
                        } else if (salestat == 6) {
                            sale = "租售";
                        } else if (salestat == 7) {
                            sale = "在租";
                        }
                        m.put("sale", sale);
                    }
                } else {
                    result.setStatus(404);
                    result.setErrorMessage("查询楼盘数据为空");
                    return result;
                }
                result.setData(list);
            } else {
                result.setStatus(500);
                result.setErrorMessage("调用新房接口查询楼盘数据失败");
                return result;
            }
        } catch (
                Exception e)

        {
            e.printStackTrace();
            result.setStatus(500);
            result.setErrorMessage("调用新房接口查询楼盘数据失败");
            logger.error("调用新房接口查询楼盘数据失败", e);
        }
        return result;
    }

    private String dealDis(String dis, String district, String districtId) {
        try {
            StringBuilder aaa = new StringBuilder();
            StringBuilder bbb = new StringBuilder();
            if (dis.contains(",")) {
                String[] aa = dis.split(",");
                for (String s : aa) {
                    int index = s.indexOf("-");
                    s = s.substring(index + 1);
                    aaa.append(s).append(",");
                }
                for (String s : aa) {
                    int index = s.indexOf("-");
                    String c = s.substring(0, index);
                    bbb.append(c).append(",");
                }
                district = aaa.toString();
                districtId = bbb.toString();
            } else {
                int index = dis.indexOf("-");
                districtId = dis.substring(0, index);
                district = dis.substring(index + 1);
            }
            district = district + "-" + districtId;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return district;
    }

    private static String formatDouble(double d) {
        NumberFormat nf = NumberFormat.getNumberInstance();

        // 保留两位小数
        nf.setMaximumFractionDigits(2);
        // 如果不需要四舍五入，可以使用RoundingMode.DOWN
        nf.setRoundingMode(RoundingMode.UP);
        return nf.format(d);
    }

    /**
     * 查询该客户是否有置业报告
     *
     * @param customerId 客户id
     * @return
     */
    @RequestMapping(value = "/queryReport/{customerId}")
    @ResponseBody
    public HResult queryReport(@PathVariable int customerId) {
        HResult result = new HResult();
        try {
            Map<String, Object> map = new HashMap<>(5);
            map.put("customerId", customerId);
            List<PropertyReportEntity> reportList = reportInterface.queryByConditions(map);
            if (CollectionUtils.isEmpty(reportList)) {
                result.setStatus(101);
            }
        } catch (Exception e) {
            result.setStatus(-1);
            result.setErrorMessage("查询该客户是否有置业报告失败");
            e.printStackTrace();
            logger.error("查询该客户是否有置业报告失败", e);
        }
        return result;
    }

    /**
     * 发送置业报告短信
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/sendMessage/{id}")
    @ResponseBody
    public HResult sendMessage(@PathVariable int id) {
        HResult result = new HResult();
        try {
            result = reportInterface.sendMessage(id);
        } catch (Exception e) {
            result.setStatus(-1);
            result.setErrorMessage("发送置业报告短信失败");
            e.printStackTrace();
            logger.error("发送置业报告短信失败", e);
        }
        return result;
    }

}
