package com.house365.ws.interfaces.impl;

import com.house365.beans.entity.CustomerEntity;
import com.house365.beans.entity.PropertyReportEntity;
import com.house365.beans.entity.ReportHouseEntity;
import com.house365.beans.entity.ReportLogEntity;
import com.house365.beans.vo.PropertyReportVo;
import com.house365.commons.system.HttpClientUtil;
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.dao.mapper.CustomerMergeMapper;
import com.house365.ws.dao.mapper.PropertyReportMapper;
import com.house365.ws.dao.mapper.ReportHouseMapper;
import com.house365.ws.dao.mapper.ReportLogMapper;
import com.house365.ws.interfaces.server.IPropertyReportInterface;
import com.house365.ws.system.ReturnResult;
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.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.net.URLEncoder;
import java.util.*;

/**
 * @author Created by Administrator on 2020/4/17.
 */
@Service("propertyReport")
public class PropertyReportImpl implements IPropertyReportInterface {

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

    @Autowired
    private PropertyReportMapper mapper;
    @Autowired
    private ReportHouseMapper houseMapper;
    @Autowired
    private ReportLogMapper logMapper;
    @Autowired
    private CustomerMergeMapper mergeMapper;

    @Override
    public PropertyReportEntity getById(int id) {
        return mapper.getById(id);
    }

    @Override
    public MapListResponse list(MapListRequest request) {
        MapListResponse response = new MapListResponse();
        try {
            Map<String, Object> map = new HashMap<>(10);
            Map<String, Object> searchParams = request.getSearchParams();
            int start = 50 * (request.getPaging().getCurrentPage() - 1);
            map.put("start", start);
            map.put("limit", 50);
            map.put("phone", searchParams.get("phone"));
            if (searchParams.get("isSend") != null && StringUtils.isNotBlank(searchParams.get("isSend").toString())) {
                String sendStatus = searchParams.get("isSend").toString();
                if ("1".equals(sendStatus)) {
                    map.put("sendStatus", 1);
                } else if ("2".equals(sendStatus)) {
                    map.put("sendStatus", 0);
                } else {
                    map.put("sendStatus", -1);
                }
            }
            int userId = Integer.valueOf(searchParams.get("userId").toString());
            String city = searchParams.get("city").toString();
            if (userId != 1) {
                map.put("createId", userId);
            }
            map.put("city", city);
            List<Map<String, Object>> list = mapper.queryList(map);
            int count = mapper.queryCount(map);
            request.getPaging().setRecords(count);
            response.setPaging(request.getPaging());
            response.setObjectList(list);
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(e.getMessage());
        }
        return response;
    }

    @Override
    public List<PropertyReportEntity> queryByConditions(Map<String, Object> map) {
        List<PropertyReportEntity> list = mapper.queryByConditions(map);
        if (CollectionUtils.isNotEmpty(list)) {
            return list;
        }
        return Collections.emptyList();
    }

    @Override
    public PropertyReportVo queryVo(Map<String, Object> map) {
        PropertyReportVo vo = new PropertyReportVo();
        List<PropertyReportEntity> list = mapper.queryByConditions(map);
        if (CollectionUtils.isNotEmpty(list)) {
            vo.setEntity(list.get(0));
            for (PropertyReportEntity entity : list) {
                Map<String, Object> queryMap = new HashMap<>(5);
                queryMap.put("relateId", entity.getId());
                List<ReportHouseEntity> houseList = houseMapper.queryByConditions(queryMap);
                if (CollectionUtils.isNotEmpty(houseList)) {
                    vo.setList(houseList);
                }
            }
        }
        return vo;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public HResult save(PropertyReportVo vo, String city) {
        HResult result = new HResult();
        try {
            PropertyReportEntity entity = vo.getEntity();
            List<ReportHouseEntity> list = vo.getList();
            mapper.save(entity);
            int id = entity.getId();
//            String url = "http://m.house365.com/H5/dist/index.html#/?id=" + id;
            String url = "http://report.house365.com/index.html#/?id=" + id;
            Map<String, Object> map = new HashMap<>(5);
            map.put("id", id);
            map.put("reportUrl", url);
            mapper.updateUrl(map);
            if (CollectionUtils.isNotEmpty(list)) {
                for (ReportHouseEntity e : list) {
                    if(e.getOrderNo() == 0){
                        e.setOrderNo(1000);
                    }
                    e.setRelateId(id);
                    e.setCity(city);
                    if (StringUtils.isBlank(e.getDeliveryTime())) {
                        e.setDeliveryTime("");
                    }
                    houseMapper.save(e);
                }
            }
            //新增日志
            ReportLogEntity logEntity = new ReportLogEntity();
            logEntity.setRelateId(id);
            logEntity.setAction("生成新报告");
            logEntity.setCreateId(entity.getCreateId());
            logEntity.setCreateName(entity.getCreateName());
            logEntity.setCreateTime(new Date());
            logMapper.save(logEntity);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("新增置业报告失败", e);
            result.setStatus(-1);
            result.setErrorMessage("新增置业报告失败");
            throw new RuntimeException();
        }
        return result;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public HResult update(PropertyReportVo vo, String city) {
        HResult result = new HResult();
        try {
            PropertyReportEntity entity = vo.getEntity();
            List<ReportHouseEntity> list = vo.getList();
            mapper.update(entity);
            Map<String, Object> queryMap = new HashMap<>(5);
            queryMap.put("relateId", entity.getId());
            List<ReportHouseEntity> oldList = houseMapper.queryByConditions(queryMap);
            if (CollectionUtils.isNotEmpty(oldList)) {
                for (ReportHouseEntity house : oldList) {
                    int id = house.getId();
                    houseMapper.delete(id);
                }
            }
            int id = entity.getId();
            //更新置业报告时，直接替换绑定楼盘，删除原有的，再去新增新绑定的
            if (CollectionUtils.isNotEmpty(list)) {
                for (ReportHouseEntity e : list) {
                    if(e.getOrderNo() == 0){
                        e.setOrderNo(1000);
                    }
                    e.setRelateId(id);
                    e.setCity(city);
                    if (StringUtils.isBlank(e.getDeliveryTime())) {
                        e.setDeliveryTime("");
                    }
                    houseMapper.save(e);
                }
            }
            //新增更新日志
            ReportLogEntity logEntity = new ReportLogEntity();
            logEntity.setRelateId(id);
            logEntity.setAction("生成新报告");
            logEntity.setCreateId(entity.getCreateId());
            logEntity.setCreateName(entity.getCreateName());
            logEntity.setCreateTime(new Date());
            logMapper.save(logEntity);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("更新置业报告失败", e);
            result.setStatus(-1);
            result.setErrorMessage("更新置业报告失败");
            throw new RuntimeException();
        }
        return result;
    }

    @Override
    public HResult sendMessage(int id) {
        HResult result = new HResult();
        try {
            PropertyReportEntity entity = mapper.getById(id);
            CustomerEntity customer = mergeMapper.queryById(entity.getCustomerId());
            String url = entity.getReportUrl();
            String name = customer.getManagerName();
            String city = customer.getCityCode();
            String mobile = entity.getPhone();
//            String mobile = "18862152977";
            String msg = "您的房博士" + name + "本次为您生成的专属置业报告，详见链接：" + url;
            msg = URLEncoder.encode(msg, "GBK");
            String smUrl = "http://mysms.house365.com:81/index.php/Interface/apiSendMobil/jid/104/depart/1/city/";
            smUrl = smUrl + city + "/" + "mobileno/" + mobile;
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("msg", msg));
            String data = HttpClientUtil.doGet(smUrl, params, null);
            Map<String, Object> updateMap = new HashMap<>(5);
            if (data != null) {
                logger.info("发送置业报告短信成功");
                //更新发送短信时间及状态
                updateMap.put("sendStatus", 1);
            } else {
                logger.info("发送置业报告短信失败");
                result.setStatus(-1);
                result.setErrorMessage("发送置业报告短信失败");
                updateMap.put("sendStatus", 2);
            }
            Date date = new Date();
            updateMap.put("sendTime", date);
            updateMap.put("id", id);
            mapper.updateSendStatus(updateMap);
            //新增发送短信日志
            ReportLogEntity logEntity = new ReportLogEntity();
            logEntity.setRelateId(id);
            logEntity.setAction("发送短信");
            logEntity.setCreateId(entity.getCreateId());
            logEntity.setCreateName(entity.getCreateName());
            logEntity.setCreateTime(date);
            logMapper.save(logEntity);
        } catch (Exception e) {
            result.setStatus(-1);
            result.setErrorMessage("发送置业报告短信失败");
            e.printStackTrace();
            logger.error("发送置业报告短信失败", e);
        }
        return result;
    }

    @Override
    public List<ReportLogEntity> queryReportLog(int id) {
        Map<String, Object> map = new HashMap<>(5);
        map.put("relateId", id);
        List<ReportLogEntity> list = logMapper.queryByConditions(map);
        if (CollectionUtils.isNotEmpty(list)) {
            return list;
        }
        return Collections.emptyList();
    }

    @Override
    public List<ReportHouseEntity> queryHouse(int id,int order) {
        Map<String, Object> map = new HashMap<>(5);
        map.put("relateId", id);
        map.put("order", order);
        List<ReportHouseEntity> houseList = houseMapper.queryByConditions(map);
        if (CollectionUtils.isNotEmpty(houseList)) {
            return houseList;
        }
        return Collections.emptyList();
    }
}
