'use strict';
const Controller = require('egg').Controller;
const _ = require('lodash');
const R = require('ramda');
const moment = require('moment');
class ToolController extends Controller {

    //公积金房贷测算
    async gjjLoanMeasureInfo() {

        const { ctx } = this;
        const app_user_id = ctx.appUserId;
        // const app_user_id = '23b6c1a6-87b8-4a3d-bf87-6a48d4cd5fdb';
        const token = ctx.cookies.get('token', { signed: false });
        // const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjp7ImFwcF91c2VyX2lkIjoiMjNiNmMxYTYtODdiOC00YTNkLWJmODctNmE0OGQ0Y2Q1ZmRiIiwicGFzc3BvcnQiOiIxNTY1NTIwNzc5OCIsImFwcF9pZCI6IjM1M2MyZjRhLTVlZjgtNDQxOC05MDgyLTM1MzRiOWM4MDJkYyIsInVpZCI6ImVhYWY5ZDZkLTVkOTgtNDZhYi04YmJlLTYzOTAwNDZhZmJlZiIsImxvZ2luX3R5cGUiOiIxIiwiYWNjb3VudF9pZCI6IjFhNTYyZTQ3LTg1NDQtNDllNC04ZDI1LTkzNTgxMWI1YjQzOCIsImNoYW5uZWxfaWQiOiI5N2Y2MTA2MC00YWMxLTExZTktYTJhMC1hZGQxYWU3MzQyOWIiLCJkZXZpY2VfaWQiOiI2NzVmNmFhMS1iNGE0LTRmNjMtYjc1Ni1jY2JiZmIzZjk0ODciLCJvaWQiOiI4MTU2NDMiLCJkZXZpY2VfbG9naW5fbG9nc19pZCI6IjUyNDc4ZTliLTM4MmUtNDcyYy05NjA4LTY2M2VjMTk3MzQ1ZSIsImFwcF90eXBlX2lkIjoiMjE1MGQwZjEtZWUwNy00ZDE3LWEwMTktMjUxYmUzNjk5YmQxIn0sImV4cCI6MTU2MTYwNjc4NSwiaWF0IjoxNTU5MDQwNDI1fQ.tIz28GI9uCt8XWD32LCxyCq2SxzhWbaLxYKcu5aKC1E';

        const area = ctx.params.area;
        let months;
        let balance;
        if (app_user_id) {
            const url = this.config.NODE_BASE_URL + `/career-server/house/gjj_quota/${area}/${app_user_id}`;
            const gjj_loan_measure_results = await ctx.curl(url, { method: 'GET', headers: { Authorization: 'Bearer ' + token }, dataType: 'json' });
            ctx.logger.info(JSON.stringify({ url: url, gjj_loan_measure_results: gjj_loan_measure_results }));
            if (gjj_loan_measure_results.status === 200 && gjj_loan_measure_results.data && gjj_loan_measure_results.data.ret) {
                const measure_info = gjj_loan_measure_results.data.ret;
                months = measure_info.months;
                balance = measure_info.balance;
            }
        }

        ctx.success({ months, balance });
    }

    //存钱罐地图搜索
    async getMapHouses() {
        const { ctx } = this;
        const input_parmas = ctx.query;
        const rule = {
            house_style: { type: 'string', required: true },
            keyword: { type: 'string', required: true },
            // page: { type: 'string', required: false },
        }
        ctx.validate(rule, input_parmas);
        const house_style = input_parmas.house_style;
        const keyword = input_parmas.keyword;
        const page = input_parmas.page;
        const where = { where: { name: { $like: `%${keyword}%` } } };
        let results = [];
        let map_houses_results;
        if (house_style === 'used_house') {
            map_houses_results = await ctx.blockModel.HousePriceMap3.all(where);
            const map_houses = map_houses_results;
            for (let i in map_houses) {
                const item = map_houses[i];
                if (('price' in item) && !item.price) {
                    continue;
                }
                results.push({
                    id: item.id,
                    name: item.name,
                    longitude: item.longitude,
                    latitude: item.latitude,
                    price: item.price,
                    unit: item.unit || '元/平',
                    level: 3,
                });
            }
        } else if (house_style === 'new_house') {
            map_houses_results = await ctx.blockModel.HouseNewHousePriceMap2.all(where);
            const map_houses = map_houses_results;
            for (let i in map_houses) {
                const item = map_houses[i];
                if (('price' in item) && !item.price) {
                    continue;
                }
                if (('count' in item) && !item.count) {
                    continue;
                }
                results.push({
                    id: item.id,
                    name: item.name,
                    longitude: item.longitude,
                    latitude: item.latitude,
                    price: item.price,
                    count: item.count,
                    unit: item.unit || '个楼盘',
                    level: 2,
                });
            }
        }

        ctx.success({ results });

    }

    //存钱罐地图
    async getMapPoint() {
        const { ctx } = this;
        const input_parmas = ctx.params;
        const rule = {
            house_style: { type: 'string', required: true },
            area_code: { type: 'string', required: true },
            level: { type: 'string', required: true },
        }
        ctx.validate(rule, input_parmas);

        const house_style = input_parmas.house_style;
        const area_code = input_parmas.area_code;
        const level = input_parmas.level;

        let ret = [];
        if (house_style === 'used_house') {
            if (parseInt(level) === 1) {
                const price_city_ret = await ctx.blockModel.HousePriceCity.one({ where: { id: area_code } });
                if (price_city_ret && price_city_ret.id) ret = await ctx.service.house.v2.tool.getUsedHouseMapPoint(area_code, level);
            } else {
                ret = await ctx.service.house.v2.tool.getUsedHouseMapPoint(area_code, level);
            }
        } else if (house_style === 'new_house') {
            ret = await ctx.service.house.v2.tool.getNewHouseMapPoint(area_code, level);
        }

        ctx.success({ results: ret });
    }

    //存钱罐推荐的楼盘跳转到地图页 获取点位信息给前端
    async getHousePoint() {

        const { ctx } = this;
        const house_id = ctx.query.house_id;
        console.info(house_id);
        const new_house = await ctx.realestateModel.NewHouse.one({ where: { id: house_id } });
        const new_house_name = new_house.name;
        const map_house = await ctx.blockModel.HouseNewHousePriceMap2.one({ where: { name: new_house_name } });
        let result = {};
        if (map_house && map_house.id) {
            result = {
                name: map_house.name,
                longitude: map_house.longitude,
                latitude: map_house.latitude,
                price: map_house.price,
                unit: map_house.unit,
            }
        } else {
            const city_codes = [new_house.province, new_house.city, new_house.area];
            const cities = await ctx.blockModel.City.all({ where: { code: { $in: city_codes } } });
            const city = (cities && cities[1] && cities[1].name) ? cities[1].name : '';
            const address = R.pluck('name', cities).join('') + new_house.address;
            const gps_info = await ctx.helper.getGPS(address, city);
            if (gps_info.lng && gps_info.lat) {
                result = {
                    house_id,
                    name: new_house_name,
                    longitude: gps_info.lng,
                    latitude: gps_info.lat,
                    price: new_house.reference_avg_price,
                    unit: '元/平',
                }
            }
        }

        ctx.success({ result });
    }

    //存钱罐 附近房源点位
    async getHouseNearbyPoint() {

        const { ctx } = this;
        const input_parmas = ctx.request.body;
        const rule = {
            right_corner_gps: { type: 'string', required: true },
            left_corner_gps: { type: 'string', required: true },
        }
        ctx.validate(rule, input_parmas);
        const right_point = ctx.helper.checkGps(input_parmas.right_corner_gps).split(',');
        const left_point = ctx.helper.checkGps(input_parmas.left_corner_gps).split(',');
        const house_nearby_points = await ctx.blockModel.HouseNewHousePriceMap2.all({ where: { longitude: { $between: [left_point[1], right_point[1]] }, latitude: { $between: [left_point[0], right_point[0]] } } });
        const results = house_nearby_points.map(item => { return { name: item.name, longitude: item.longitude, latitude: item.latitude, price: item.price, unit: item.unit } });
        ctx.success({ results });
    }

    //生成购房计划
    async generateBuyHousePlan() {

        const { ctx } = this;
        const input_parmas = ctx.request.body;
        const rule = {
            city_code: { type: 'string', required: true },
            area_code: { type: 'string', required: false },
            total_price: { type: 'object', required: true },
            down_payment: { type: 'string', required: true },
            invest_payment: { type: 'string', required: true },
            prepare_time: { type: 'string', required: true },
            house_style: { type: 'string', required: false },
        }
        ctx.validate(rule, input_parmas);
        if (!parseFloat(input_parmas.invest_payment)) {
            ctx.failed('现有金额不能为0');
        }
        const area_code = input_parmas.area_code;
        const city_code = input_parmas.city_code;
        const total_price = input_parmas.total_price;
        if (!parseFloat(total_price.max) || !parseFloat(total_price.min)) {
            ctx.failed('总价区间不能为0');
        }
        // const house_style = input_parmas.house_style ? input_parmas.house_style : 'new_house';


        let where = {
            reference_total_price: { $between: [parseFloat(total_price.min), parseFloat(total_price.max)] },
            option_city_code: city_code,
            option_district_code: area_code,
            status: 'online',
            valid: 1,
        }
        let recommend_houses = await ctx.realestateModel.NewHouse.list({ limit: 6, page: 1, where: where, order: [['order_id', 'desc']] });//推荐房源
        if (recommend_houses.count < 6) {
            delete where.option_district_code;
            const out_house_ids = R.pluck('id', recommend_houses.rows);
            where.id = { $notIn: out_house_ids };
            const recommend_houses_supplement = await ctx.realestateModel.NewHouse.list({ limit: 6, page: 1, where: where, order: [['order_id', 'desc']] });//推荐房源
            recommend_houses = [...recommend_houses.rows, ...recommend_houses_supplement.rows];
        }
        recommend_houses = recommend_houses.splice(0, 6);
        const recommend_houses_formats = [];
        for (let i in recommend_houses) {
            const recommend_house = recommend_houses[i];
            recommend_houses_formats.push(await ctx.service.house.v2.newHouse.formatNewHouseBasic(recommend_house));
        }
        recommend_houses = recommend_houses_formats;
        // recommend_houses = await ctx.service.house.v2.newHouse.formatNewHouseTypeList(recommend_houses);

        const house_plan = await ctx.service.house.v2.tool.generateHousePlan(input_parmas);//计算购房能力 生成购房计划
        const ret = {
            house_plan,
            recommend_houses,
        }

        ctx.success({ results: ret });
    }

    //生成购房计划
    async generateBuyHousePlan_2_1() {

        const { ctx } = this;
        const input_parmas = ctx.request.body;
        const rule = {
            city_code: { type: 'string', required: true },
            total_price: { type: 'object', required: true },
            down_payment_rate: { type: 'string', required: true },//首付成数
            down_payment: { type: 'string', required: true },//首付
            invest_payment: { type: 'string', required: true },//现有现金
            prepare_time: { type: 'string', required: true },
            house_style: { type: 'string', required: false },
        }
        ctx.validate(rule, input_parmas);
        if (!parseFloat(input_parmas.invest_payment)) {
            ctx.failed('现有金额不能为0');
        }

        const city_code = input_parmas.city_code;
        const total_price = input_parmas.total_price;
        // const down_payment = parseFloat(input_parmas.down_payment);
        const invest_payment = parseFloat(input_parmas.invest_payment);
        const down_payment_rate = parseFloat(input_parmas.down_payment_rate);

        if (!parseFloat(total_price.max) || !parseFloat(total_price.min)) {
            ctx.failed('总价区间不能为0');
        }
        const house_plan = await ctx.service.house.v2.tool.generateHousePlan_2_1(input_parmas);//计算购房能力 生成购房计划
        // if (house_plan.status !== 2) {
        //     total_price.max = invest_payment * 2 / down_payment_rate + 30;
        //     total_price.min = invest_payment * 2 / down_payment_rate - 30;
        // }

        let where = {
            reference_total_price: { $between: [parseFloat(total_price.min), parseFloat(total_price.max)] },
            option_city_code: city_code,
            status: 'online',
            valid: 1,
        }
        const recommend_houses_formats = [];
        let recommend_houses = await ctx.realestateModel.NewHouse.list({ limit: 6, page: 1, where: where, order: [['order_id', 'desc']] });//推荐房源
        for (let i in recommend_houses.rows) {
            const recommend_house = recommend_houses.rows[i];
            recommend_houses_formats.push(await ctx.service.house.v2.newHouse.formatNewHouseBasic(recommend_house));
        }
        recommend_houses = recommend_houses_formats.splice(0, 6);


        const headers = {
            cookie: ctx.request.headers.cookie
        }

        const banners_result = await ctx.helper.send_request(this.config.NODE_BASE_URL + '/51app/api/block/all', { alias: '51fangc_tool_plan_banners' }, { method: 'GET', dataType: 'json', headers: headers });
        let banners = [];
        if (banners_result.status === 200) {
            banners = banners_result.data.results;
        }

        const ret = {
            house_plan,
            banners,
            recommend_houses,
        }

        ctx.success({ results: ret });
    }

    //购房计划城市区域列表
    async planAreaList() {

        const { ctx } = this;

        const city_list_results = await ctx.service.house.v2.newHouse.getNewHouseCity();//v2.2 2019-8-27 15:18:26
        const city_list_ret = city_list_results.results;

        const city_list = [];
        for (let i in city_list_ret) {
            let city = city_list_ret[i];
            if (city.name.indexOf('市辖区') !== -1) {
                city = await ctx.blockModel.City.one({ where: { id: city.parent } });
                if (!city || !city.id) {
                    continue;
                }
            }

            city_list.push({
                id: city.id,
                name: city.name,
                code: city.code,
                letter: city.fword.toUpperCase(),
            });
        }
        const cities_ids = R.pluck('code', city_list);
        const districts = await ctx.blockModel.HouseDistrict.all({ where: { city_id: { $in: cities_ids } } });
        const results = [];
        for (let i in city_list) {
            const city = city_list[i];
            const children = districts.filter(item => { return (parseInt(item.city_id) === parseInt(city.code)) ? true : false });
            city._children = children.map(item => { return { id: item.id, name: item.name, code: item.id } });
            // city._children.unshift({ id: -1, name: '全部', code: 0 });
            results.push(city);
        }

        ctx.success({ results });
    }

    //type类型；trend：房价走势图；increase：房价涨跌 ;question: 购房问题；supply：供需趋势图
    async getHousePriceFeature() {

        const { ctx } = this;
        const input_parmas = ctx.params;
        const rule = {
            type: { type: 'string', required: true },
            city_code: { type: 'string', required: true },
        }
        ctx.validate(rule, input_parmas);

        const type = input_parmas.type;
        const city_code = input_parmas.city_code;
        const area_code = ctx.query.area_code;
        console.info(area_code);

        let ret = [];
        if (type === 'trend') {
            if (area_code) {
                ret = await ctx.blockModel.HousePriceTrend2.one({ where: { id: area_code, pid: city_code } });
            } else {
                ret = await ctx.blockModel.HousePriceTrend.one({ where: { id: city_code } });
            }
            ret = ret ? ret.trend_json : [];
        } else if (type === 'increase') {
            ret = await ctx.blockModel.HousePriceIncrease.one({ where: { id: city_code } });
            ret = ret ? ret.increase_json : [];
        } else if (type === 'question') {
            ret = await ctx.blockModel.HouseQuestion.one({ where: { id: city_code } });
            ret = ret ? ret.question_json : [];
        } else if (type === 'supply') {
            if (area_code) {
                ret = await ctx.blockModel.HouseSupplyDemand2.one({ where: { id: area_code, pid: city_code } });
            } else {
                ret = await ctx.blockModel.HouseSupplyDemand.one({ where: { id: city_code } });
            }
            ret = ret ? ret.supply_demand_json : [];
        }

        ctx.success(ret);
    }

    //购房资格的问题可支持的城市
    async getHouseQuestionCity() {
        const { ctx } = this;
        //所有支持的城市编码
        let filter = {
            attributes: ['id']
        }
        let cityCode = await ctx.blockModel.HouseQuestion.findAll(filter);
        let ret = { results: [] };
        if (cityCode !== undefined && cityCode.length > 0) {
            let cityCodes = _.uniq(_.map(cityCode, 'id'));
            let cityFilter = {
                where: { code: { $in: cityCodes } }
            }
            let cityName = await ctx.blockModel.City.findAll(cityFilter);
            ret.results = cityName !== undefined ? cityName : [];
        }
        ctx.success(ret);
    }

    //房价指数可支持的城市
    async getHousePriceFeatureCity() {

        const { ctx } = this;
        const results = await ctx.blockModel.HousePriceCity.all({});
        const city_codes = R.pluck('id', results);
        const cities = await ctx.blockModel.City.all({ where: { code: { $in: city_codes } }, order: [['pinyin', 'asc']] });

        ctx.success({ results: cities });
    }

    //城市月参考均价
    async getHousePriceCity() {

        const { ctx } = this;
        const city_code = ctx.query.city_code;
        let result = await ctx.blockModel.HousePriceCity.one({ where: { id: city_code } });
        let city;
        if (result && result.id) {
            city = await ctx.blockModel.City.one({ where: { code: result.id } });
        }
        if (!city) {//如果价格城市不支持 则直接取第一个 产品要求默认北京，以防爬取过来的数据没有北京所以默认第一个 表里北京基本会是第一个
            result = await ctx.blockModel.HousePriceCity.one({});
        }
        if (result && result.id) {
            city = await ctx.blockModel.City.one({ where: { code: result.id } });
        }
        const month = moment(new Date()).format('MM');
        const ret = {
            name: city.name,
            description: `${month}月参考均价`,
            price: result.price,
            unit: '元/平',
        }

        ctx.success({ result: ret });

    }

    //房价指数，搜索结果
    async getHousePriceFeatureSearch() {

        const { ctx } = this;
        const input_parmas = ctx.request.body;
        const keyword = input_parmas.keyword;
        let city_code = input_parmas.city_code;
        const zhixiaqu_map = { 110000: 110100, 500000: 500100, 120000: 120100, 310000: 310100 };
        let results = [];
        if (keyword && city_code) {
            const month = moment(new Date()).format('MM');
            if (['110000', '500000', '120000', '310000'].includes(city_code)) {
                city_code = zhixiaqu_map[city_code];
            }

            const city_result = await ctx.blockModel.City.one({ where: { code: city_code } });
            const area_results = await ctx.blockModel.City.all({ where: { name: { $like: `%${keyword}%` }, level: 3, parent: city_result.id } });
            const area_results_codes = R.pluck('code', area_results);
            const area_map = R.zipObj(area_results_codes)(area_results);

            if (area_results_codes && area_results_codes.length > 0) {

                //城市房价
                const house_price_map_results = await ctx.blockModel.HousePriceMap.all({ where: { id: { $in: area_results_codes } } });
                const price_map_results = house_price_map_results.map(item => { return { name: item.name, code: item.id, description: `${month}月参考价`, price: item.price, unit: '元/平' } });

                //房价走势
                let out_codes = R.pluck('code', price_map_results);//去重
                const house_price_trend_results = await ctx.blockModel.HousePriceTrend2.all({ where: { id: { $in: area_results_codes, $notIn: out_codes } } });
                const price_trend_results = house_price_trend_results.map(item => { return { name: area_map[item.id]['name'] ? area_map[item.id]['name'] : keyword, code: item.id, description: `${month}月参考价`, price: '-----', unit: '元/平' } });

                //房价供需趋势
                out_codes = out_codes.concat(R.pluck('code', price_trend_results));//去重
                const house_supply_demand_results = await ctx.blockModel.HouseSupplyDemand2.all({ where: { id: { $in: area_results_codes, $notIn: out_codes } } });
                const supply_demand_results = house_supply_demand_results.map(item => { return { name: area_map[item.id]['name'] ? area_map[item.id]['name'] : keyword, code: item.id, description: `${month}月参考价`, price: '-----', unit: '元/平' } });

                results = [...price_map_results, ...price_trend_results, ...supply_demand_results];
            }

        }

        ctx.success({ results });
    }

    // 获取51shequ的oss签名
    async getBusinessSignature() {

        const { ctx } = this;

        const region = 'oss-cn-hangzhou';
        const bucket = '51shequ';

        const id = 'LTAIubEuBfdUOJ5m';
        const key = '83J27tCC2CxHhL2uQvTRcCbEZX2jGK';
        const host = '//' + bucket + '.' + region + '.aliyuncs.com';
        const url = "//r.51gjj.com/";
        let now = Math.round(new Date().getTime() / 1000).toString();
        const expire = 120;
        let end = now + expire;

        let expiration = new Date(new Date().valueOf() + expire * 1000).toISOString().replace(/\..+/, '') + 'Z';

        let dir = 'images/house/house_analysis/';

        //最大文件大小.用户可以自己设置
        let condition = new Array(3);
        condition[0] = 'content-length-range';
        condition[1] = 0;
        condition[2] = 1048576000;

        let start = new Array('starts-with', '$key', dir);

        let conditions = new Array(condition, start);


        let policy = { expiration: expiration, conditions: conditions };


        let base64_policy = new Buffer(JSON.stringify(policy)).toString('base64');

        let string_to_sign = base64_policy;
        const crypto = require('crypto');
        let signature = crypto.createHmac('sha1', key).update(string_to_sign).digest().toString('base64');;
        // let config = {
        //     region,
        //     accessKeyId: id,
        //     accessKeySecret: key,
        //     bucket: bucket,

        // }
        let results = {
            accessid: id,
            static_host: url + dir,
            host: host,
            policy: base64_policy,
            signature: signature,
            expire: end,
            expiration,
            // config: config,
            dir
        };

        ctx.success({ results });
    }

    //房产估价
}

module.exports = ToolController;
