package com.house365.ws.interfaces.rest;

import com.google.common.base.Strings;
import com.house365.beans.entity.*;
import com.house365.beans.vo.ReportHouseVo;
import com.house365.commons.system.HttpClientUtil;
import com.house365.rest.context.Parameter;
import com.house365.rest.exception.ServiceRunException;
import com.house365.rest.parameter.House365RestObject;
import com.house365.rest.parameter.House365RestResponse;
import com.house365.web.util.StringUtils;
import com.house365.ws.dao.mapper.*;
import com.house365.ws.service.interfaces.IAttachmentService;
import com.house365.ws.service.interfaces.ICustomerStatusLogService;
import com.house365.ws.service.interfaces.IUserService;
import com.house365.ws.system.ReturnAppResult;
import net.sf.json.JSONObject;
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.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 获取置业报告详情接口
 *
 * @author Created by Administrator on 2020/4/26.
 */
@Service("getReport")
public class GetReportImpl implements IGetReport {

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

    @Autowired
    private PropertyReportMapper reportMapper;
    @Autowired
    private ReportHouseMapper houseMapper;
    @Autowired
    private ReportAttachMapper attachMapper;

    @Autowired
    private CustomerMergeMapper mergeMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ICustomerStatusLogService customerStatusLogService;
    @Autowired
    private IAttachmentService attachmentService;
    @Autowired
    private IUserService userService;

    @Override
    public Object exectue(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        House365RestResponse<Map<String, Object>> response = new House365RestResponse<>();
        Map<String, Object> paramMap = parameter.getArgs();
        // 业务层统一处理
        try {
            int id = Integer.valueOf(getMapValueByKey("id", paramMap, "0"));
            PropertyReportEntity entity = reportMapper.getById(id);
            if (entity != null) {
                Map<String, Object> resultMap = new HashMap<>(10);
                House365RestObject<Map<String, Object>> restObject = new House365RestObject<>();
                CustomerEntity customerEntity = mergeMapper.queryById(entity.getCustomerId());
                if (customerEntity != null) {
                    String city = customerEntity.getCityCode();
                    //获取置业报告资质
                    Map<String, Object> attachMap = new HashMap<>(10);
                    attachMap.put("city", city);
                    List<ReportAttachEntity> attachList = attachMapper.queryByConditions(attachMap);
                    if (CollectionUtils.isNotEmpty(attachList)) {
                        resultMap.put("attachList", attachList);
                    }
                    int managerId = customerEntity.getManagerId();
                    UserEntity userEntity = (UserEntity) userService.getById(managerId);
                    if (userEntity != null) {
                        Map<String, Object> userMap = new HashMap<>(10);
                        userMap.put("name", userEntity.getRealName());
                        userMap.put("mobile", userEntity.getMobile());
                        userMap.put("wxNumber", userEntity.getWxNumber());
                        userMap.put("wxCodeImgUrl", userEntity.getWxCodeImgUrl());
                        userMap.put("goodat", userEntity.getGoodat());
                        userMap.put("description", userEntity.getDescription());
                        if (userEntity.getScore() != null) {
                            userMap.put("score", String.format("%.1f", userEntity.getScore()));
                            userMap.put("evaluateCount", userEntity.getEvaluateCount());
                        } else {
                            userMap.put("score", "0");
                            userMap.put("evaluateCount", "");
                        }
                        //获取带看次数
                        int seeCount = customerStatusLogService.getSeeCount(userEntity.getId());
                        seeCount += userEntity.getDefaultVisit();
                        userMap.put("seeCount", seeCount);
                        userMap.put("defaultVisit", userEntity.getDefaultVisit());
                        //400短号分机号前加公司固话
                        if (StringUtils.isNotBlank(userEntity.getHotlinephone())) {
                            userMap.put("mobile", ("4008908365," + userEntity.getHotlinephone()));
                        } else {
                            userMap.put("mobile", "");
                        }
                        List<BaseAttachment> headImg = attachmentService.queryByResourceIdAndResouceType(String.valueOf(managerId), "hgs_user_headImg");

                        if (CollectionUtils.isNotEmpty(headImg)) {
                            userMap.put("headImage", headImg.get(0).getRemotePath());
                        } else {
                            userMap.put("headImage", "http://img33.house365.com/M00/1B/86/rBEBp1pu2JyAIp4jAAAGEjOUX2M365.jpg");
                        }
                        resultMap.put("user", userMap);
                    }

                    Map<String, Object> searchMap = new HashMap<>(10);
                    searchMap.put("relateId", entity.getId());
                    searchMap.put("order", 1);
                    List<ReportHouseEntity> houseList = houseMapper.queryByConditions(searchMap);
                    if (CollectionUtils.isNotEmpty(houseList)) {
                        for (ReportHouseEntity house : houseList) {
                            house.setBusList("");
                        }
                        resultMap.put("houseList", houseList);
                        searchMap.put("group", 1);
                        searchMap.put("order", 1);
                        List<ReportHouseEntity> houseNewList = houseMapper.queryByConditions(searchMap);
                        if (CollectionUtils.isNotEmpty(houseNewList)) {
                            List<ReportHouseVo> houseVoList = new ArrayList<>();
                            for (ReportHouseEntity e : houseNewList) {
                                ReportHouseVo vo = new ReportHouseVo();
                                String name = e.getHouseName();
                                searchMap.put("group", 0);
                                searchMap.put("houseName", name);
                                //获取相同楼盘名的楼盘并整合
                                List<ReportHouseEntity> houseList1 = houseMapper.queryByConditions(searchMap);
                                List<Map<String, Object>> mapList = new ArrayList<>();
                                if (CollectionUtils.isNotEmpty(houseList1)) {
                                    for (ReportHouseEntity a : houseList1) {
                                        Map<String, Object> putMap = new HashMap<>(10);
                                        putMap.put("houseName", name);
                                        putMap.put("district", a.getDistrict());
                                        putMap.put("unitType", a.getUnitType());
                                        putMap.put("area", a.getArea());
                                        putMap.put("imageUrl", a.getImageUrl());
                                        putMap.put("goods", a.getGoods());
                                        mapList.add(putMap);
                                    }
                                    vo.setList(mapList);
                                }
                                vo.setHouseName(name);
                                vo.setDistrict(e.getDistrict());
                                vo.setHouseUrl(e.getHouseUrl());
                                //获取楼盘公交信息
                                String url = "http://mapi.house365.com/taofang/v1.0/xf";
                                List<NameValuePair> queryParams = new ArrayList<>(5);
                                queryParams.add(new BasicNameValuePair("method", "getBusStop"));
                                queryParams.add(new BasicNameValuePair("prj_id", String.valueOf(e.getProjectId())));
                                queryParams.add(new BasicNameValuePair("channel", String.valueOf(e.getChannel())));
                                queryParams.add(new BasicNameValuePair("city", e.getCity()));
                                String data = HttpClientUtil.doGet(url, queryParams, 60000, "utf-8");

                                if (data != null) {
                                    JSONObject json = JSONObject.fromObject(data);
                                    String flag = json.get("success").toString();
                                    if ("true".equals(flag)) {
                                        String busInfo = json.get("data").toString();
                                        vo.setBusInfo(busInfo);
                                    } else {
                                        vo.setBusInfo("");
                                    }
                                } else {
                                    response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
                                    response.setMsg("调取楼盘公交接口失败");
                                    return response;
                                }
                                houseVoList.add(vo);
                            }
                            resultMap.put("houseVoList", houseVoList);
                        }
                    }

                    resultMap.put("entity", entity);
                    restObject.setEntity(resultMap);
                    response.setData(restObject);
                    response.setMsg("查询成功");
                    response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
                }
            } else {
                response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
                response.setMsg("根据id查询到的置业报告为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg("查询置业报告详情失败");
        }
        return JSONObject.fromObject(response).toString();
    }

    private String getMapValueByKey(String key, Map<String, Object> map, String defaultValue) {
        String value = "";
        if (map.containsKey(key) && map.get(key) != null && !Strings.isNullOrEmpty(((String[]) map.get(key))[0])) {
            value = ((String[]) map.get(key))[0];
        }

        if (Strings.isNullOrEmpty(value)) {
            value = defaultValue;
        }
        return value;
    }

    @Override
    public boolean isControlService() {
        return false;
    }

    @Override
    public boolean isLogService() {
        return false;
    }

    @Override
    public boolean isMonitorService() {
        return false;
    }

    @Override
    public Object rollback() {
        return null;
    }

    @Override
    public void commit() {

    }
}
