package com.yunzhi.marketing.xlk.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunzhi.marketing.base.ResponseBean;
import com.yunzhi.marketing.common.StringUtils;
import com.yunzhi.marketing.entity.TaBuilding;
import com.yunzhi.marketing.entity.TaCheckin;
import com.yunzhi.marketing.entity.TdCity;
import com.yunzhi.marketing.mapper.TdCityMapper;
import com.yunzhi.marketing.xlk.dto.SearchHouseDTO;
import com.yunzhi.marketing.xlk.entity.SearchHouse;
import com.yunzhi.marketing.xlk.mapper.SearchHouseMapper;
import com.yunzhi.marketing.xlk.service.ISearchHouseService;
import com.yunzhi.marketing.xlk.vo.ExportSearchHouseVO;
import com.yunzhi.marketing.xlk.vo.QuestionnaireVO;
import com.yunzhi.marketing.xlk.vo.SearchHouseVO;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;

/**
 * <p>
 * 帮我找房  服务实现类
 * </p>
 *
 * @author jobob
 * @since 2021-05-19
 */
@Service
public class SearchHouseServiceImpl extends ServiceImpl<SearchHouseMapper, SearchHouse> implements ISearchHouseService {

    @Autowired
    private SearchHouseMapper searchHouseMapper;

    @Autowired
    private TdCityMapper tdCityMapper;

    /**
     * 查询我的找房需求列表
     *
     *
     * @param pg
     * @param searchHouse
     * @return
     */
    @Override
    public ResponseBean selectSearchHouseList(IPage<SearchHouseVO> pg, SearchHouseVO searchHouse) {
        IPage<SearchHouseVO> result = searchHouseMapper.selectSearchHouseList(pg,searchHouse);
        return ResponseBean.success(result);
    }

    @Override
    public SearchHouseVO selectSearchHouseDetail(String id) {
        return searchHouseMapper.selectSearchHouseDetail(id);
    }

    /**
     * 推荐逻辑如下
     * 1、先判断区域+价格，如果有符合楼盘，则推荐，如无看2；
     * 2、判断城市+价格，如过有符合楼盘，则推荐，如无看3；
     * 3、如选择了“不限城市”，则判断价格，在当前城市内推荐一个符合的。
     * @param searchHouseDTO
     * @return
     */
    @Override
    public List<TaBuilding> getRecommendBuildings(Integer orgId, SearchHouseDTO searchHouseDTO) {
        // 区域
        String area = searchHouseDTO.getIntentArea();
        Integer areaId = StringUtils.isEmpty(area) ? null : Integer.valueOf(area);
        // 区域所属城市
        Integer areaCity = null;
        if (null != areaId) {
            TdCity city = tdCityMapper.selectById(areaId);
            areaCity = city.getParentid();
        }

        // 当前城市
        Integer cityId = searchHouseDTO.getCityId();
        // 最小总价
        Integer minPriceW = Integer.parseInt(searchHouseDTO.getMinPrice());
        if (minPriceW > 10000) {
            minPriceW = minPriceW / 10000;
        }
        // 最大总价
        Integer maxPriceW = Integer.parseInt(searchHouseDTO.getMaxPrice());
        if (maxPriceW > 10000) {
            maxPriceW = maxPriceW / 10000;
        }
        // 面积字典
        Integer areaResultId = searchHouseDTO.getAreaResultId();
        //
        Integer[] unitPrice = getUnitPriceRange(minPriceW, maxPriceW, areaResultId);
        // 最小单价
        Integer minPrice = unitPrice[0];
        // 最大单价
        Integer maxPrice = unitPrice[1];

        // 最多推荐5个楼盘
        int limit = 5;

        if (null != areaId) {
            // 1、先判断区域+价格
            List<TaBuilding> lst1 = searchHouseMapper.getRecommendBuildings(orgId, null, areaId, minPriceW, maxPriceW, minPrice, maxPrice, limit);
            if (null != lst1 && lst1.size() > 0) {
                return lst1;
            }

            // 2、判断城市+价格
            List<TaBuilding> lst2 = searchHouseMapper.getRecommendBuildings(orgId, areaCity, null, minPriceW, maxPriceW, minPrice, maxPrice, limit);
            if (null != lst2 && lst2.size() > 0) {
                return lst2;
            }
        }

        // 3、当前城市
        return searchHouseMapper.getRecommendBuildings(orgId, cityId, null, minPriceW, maxPriceW, minPrice, maxPrice, limit);
    }

    /**
     * 获取导出的数据集合
     *
     * @param searchHouse
     * @return
     */
    @Override
    public List<ExportSearchHouseVO> selectExportHouseList(SearchHouseVO searchHouse) {
        List<ExportSearchHouseVO> searchHouseVOS = searchHouseMapper.selectExportHouseList(searchHouse);
        searchHouseVOS.forEach(e -> {
            String questionnaire = e.getQuestionnaire();
            List<QuestionnaireVO> questionnaireVO = JSON.parseArray(questionnaire,QuestionnaireVO.class);
            questionnaireVO.forEach(s -> {
                try {
                    Field declaredField = e.getClass().getDeclaredField(s.getKey());
                    String name = declaredField.getName();
                    String subName = name.substring(0, 1).toUpperCase() + name.substring(1);
                    Method method = e.getClass().getMethod("set" + subName,String.class);
                    String result = String.valueOf(s.getResult());
                    String type = s.getType();
                    String resultId = null == s.getResultId() ? null : String.valueOf(s.getResultId());
                    if (searchHouse.getType() == 4) {
                        if (name == "maxPrice"){
                            Integer price = Integer.valueOf(result) / 10000;
                            result = String.valueOf(price);
                        }
                    }else if (searchHouse.getType() == 1) {
                        if (name == "maxPrice"){
                            Integer price = Integer.valueOf(result) / 10000;
                            result = String.valueOf(price);
                        }
                        if (type == "checkbox") {
                            result = resultId;
                        }
                        if (type == "checkboxs") {
                            JSONArray optionArr = JSONArray.parseArray(String.valueOf(s.getOptions()));
                        }
                    }else if (searchHouse.getType() == 3) {
                        if (name == "maxPrice"){
                            Integer price = Integer.valueOf(result) / 10000;
                            result = String.valueOf(price);
                        }
                        if (type == "checkbox") {
                            result = resultId;
                        }
                    }
                    method.invoke(e,result);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            });

        });
        return searchHouseVOS;
    }

    private Integer[] getUnitPriceRange(Integer minPriceW, Integer maxPriceW, Integer areaResultId) {
        long minPrice = minPriceW * 10000;
        long maxPrice = maxPriceW * 10000;

        // 字典过滤 - 必须与小程序端保持一致
        switch (areaResultId) {
            case 1:
                // 60㎡ 以下, 则按照 30 - 60 处理
                minPrice = minPrice / 60;
                maxPrice = maxPrice / 30;
                break;
            case 2:
                // 60 - 90
                minPrice = minPrice / 90;
                maxPrice = maxPrice / 60;
                break;
            case 3:
                // 90 - 110
                minPrice = minPrice / 110;
                maxPrice = maxPrice / 90;
                break;
            case 4:
                // 110 - 130
                minPrice = minPrice / 130;
                maxPrice = maxPrice / 110;
                break;
            case 5:
                // 130 - 150
                minPrice = minPrice / 150;
                maxPrice = maxPrice / 130;
                break;
            case 6:
                // 150 - 200
                minPrice = minPrice / 200;
                maxPrice = maxPrice / 150;
                break;
            default:
                // 200 以上
                minPrice = minPrice / 200;
                maxPrice = maxPrice / 200;
                break;
        }

        return new Integer[] {Math.toIntExact(minPrice), Math.toIntExact(maxPrice)};
    }
}
