'use strict';
const cheerio = require('cheerio');
const request = require('request');
const Controller = require('egg').Controller;
const USER_AGENT = [
    'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.122 UBrowser/4.0.3214.0 Safari/537.36',
    'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Maxthon/4.4.3.4000 Chrome/30.0.1599.101 Safari/537.36',
    'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.84 Safari/535.11 SE 2.X MetaSr 1.0',
    'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; QQBrowser/7.0.3698.400)',
    'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.71 Safari/537.1 LBBROWSER',
    'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.11 TaoBrowser/2.0 Safari/536.11',
    'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko',
    'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36',
    'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.133 Safari/534.16',
    'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
    'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36',
    'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.57.2 (KHTML, like Gecko) Version/5.1.7 Safari/534.57.2',
    'Mozilla/5.0 (X11; U; Linux x86_64; zh-CN; rv:1.9.2.10) Gecko/20100922 Ubuntu/10.10 (maverick) Firefox/3.6.10',
    'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0',
    'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; en) Opera 9.50',
    'Mozilla/5.0 (Windows NT 5.1; U; en; rv:1.8.1) Gecko/20061208 Firefox/2.0.0 Opera 9.50',
    'Opera/8.0 (Windows NT 5.1; U; en)',
    'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36 OPR/26.0.1656.60',
    'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SV1; QQDownload 732; .NET4.0C; .NET4.0E; SE 2.X MetaSr 1.0)',
    'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)',
    'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E; LBBROWSER)',
    "Mozilla/5.0 (Linux; U; Android 2.3.6; en-us; Nexus S Build/GRK39F) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1",
    "Avant Browser/1.2.789rel1 (http://www.avantbrowser.com)",
    "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/532.5 (KHTML, like Gecko) Chrome/4.0.249.0 Safari/532.5",
    "Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US) AppleWebKit/532.9 (KHTML, like Gecko) Chrome/5.0.310.0 Safari/532.9",
    "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/534.7 (KHTML, like Gecko) Chrome/7.0.514.0 Safari/534.7",
    "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) AppleWebKit/534.14 (KHTML, like Gecko) Chrome/9.0.601.0 Safari/534.14",
    "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.14 (KHTML, like Gecko) Chrome/10.0.601.0 Safari/534.14",
    "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.20 (KHTML, like Gecko) Chrome/11.0.672.2 Safari/534.20",
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.27 (KHTML, like Gecko) Chrome/12.0.712.0 Safari/534.27",
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.24 Safari/535.1",
    "Mozilla/5.0 (Windows NT 6.0) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.120 Safari/535.2",
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.36 Safari/535.7",
    "Mozilla/5.0 (Windows; U; Windows NT 6.0 x64; en-US; rv:1.9pre) Gecko/2008072421 Minefield/3.0.2pre",
    "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.10) Gecko/2009042316 Firefox/3.0.10",
    "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-GB; rv:1.9.0.11) Gecko/2009060215 Firefox/3.0.11 (.NET CLR 3.5.30729)",
    "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6 GTB5",
    "Mozilla/5.0 (Windows; U; Windows NT 5.1; tr; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8 ( .NET CLR 3.5.30729; .NET4.0E)",
    "Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1",
    "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:2.0.1) Gecko/20100101 Firefox/4.0.1",
    "Mozilla/5.0 (Windows NT 5.1; rv:5.0) Gecko/20100101 Firefox/5.0",
    "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0a2) Gecko/20110622 Firefox/6.0a2",
    "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:7.0.1) Gecko/20100101 Firefox/7.0.1",
    "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0b4pre) Gecko/20100815 Minefield/4.0b4pre",
    "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0 )",
    "Mozilla/4.0 (compatible; MSIE 5.5; Windows 98; Win 9x 4.90)",
    "Mozilla/5.0 (Windows; U; Windows XP) Gecko MultiZilla/1.6.1.0a",
    "Mozilla/2.02E (Win95; U)",
    "Mozilla/3.01Gold (Win95; I)",
    "Mozilla/4.8 [en] (Windows NT 5.1; U)",
    "Mozilla/5.0 (Windows; U; Win98; en-US; rv:1.4) Gecko Netscape/7.1 (ax)",
    "HTC_Dream Mozilla/5.0 (Linux; U; Android 1.5; en-ca; Build/CUPCAKE) AppleWebKit/528.5  (KHTML, like Gecko) Version/3.1.2 Mobile Safari/525.20.1",
    "Mozilla/5.0 (hp-tablet; Linux; hpwOS/3.0.2; U; de-DE) AppleWebKit/534.6 (KHTML, like Gecko) wOSBrowser/234.40.1 Safari/534.6 TouchPad/1.0",
];
class ToolController extends Controller {

    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') {
            ret = await ctx.service.house.tool.getUsedHouseMapPoint(area_code, level);
        } else if (house_style === 'new_house') {
            ret = await ctx.service.house.tool.getNewHouseMapPoint(area_code, level);
        }

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

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

        const { ctx } = this;
        const input_parmas = ctx.request.body;
        const rule = {
            area_code: { type: 'string', required: true },
            area_name: { type: 'string', required: true },
            down_payment: { type: 'string', required: true },
            invest_payment: { type: 'string', required: true },
            total_price: { 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');
        }
        if (!parseFloat(input_parmas.total_price)) {
            ctx.failed('面积不能为0');
        }
        // const target_house = await ctx.blockModel.HousePriceMap.one({ where: { id: input_parmas.area_code } });
        const area_code = input_parmas.area_code;
        const total_price = parseFloat(input_parmas.total_price);
        const area_name = input_parmas.area_name;

        const house_style = input_parmas.house_style ? input_parmas.house_style : 'new_house';


        let filter = {
            total_price: { min: total_price - 30, max: total_price + 30 },
            area_code: { bizcircle_code: area_code },
        }
        let recommend_houses = await ctx.service.house.newHouse.getNewHouseList(filter);//推荐房源

        let house_map;
        let district_code;
        if (recommend_houses.count === 0) {

            if (house_style === 'new_house') {
                house_map = await ctx.blockModel.HouseNewHousePriceMap2.one({ where: { id: area_code } });
            } else if (house_style === 'used_house') {
                house_map = await ctx.blockModel.HousePriceMap3.one({ where: { id: area_code } });
            }
            district_code = (house_map && house_map.pid) ? house_map.pid : '';

            filter.area_code = { district_code: district_code }
            recommend_houses = await ctx.service.house.newHouse.getNewHouseList(filter);//推荐房源
        }

        if (recommend_houses.count === 0) {

            let city_code;
            if (house_style === 'new_house') {
                house_map = await ctx.blockModel.HouseNewHousePriceMap.one({ where: { id: district_code } });
            } else if (house_style === 'used_house') {
                house_map = await ctx.blockModel.HousePriceMap2.one({ where: { id: district_code } });
                house_map = await ctx.blockModel.HousePriceMap.one({ where: { id: house_map.pid } });
            }
            city_code = (house_map && house_map.pid) ? house_map.pid : '';
            filter.area_code = { city_code: city_code };
            recommend_houses = await ctx.service.house.newHouse.getNewHouseList(filter);//推荐房源
        }
        recommend_houses = recommend_houses.results.splice(0, 4);
        // const recommend_houses = [];//推荐房源

        const house_plan = await ctx.service.house.tool.generateHousePlan(input_parmas);//计算购房能力 生成购房计划
        let fine_houses = [];
        if (house_plan.status !== 0) {
            filter = {
                name: area_name,
            }
            fine_houses = await ctx.service.house.newHouse.getNewHouseList(filter);//推荐房源
            fine_houses = fine_houses.results.splice(0, 1);
        }
        const ret = {
            house_plan,
            fine_houses,
            recommend_houses,
        }

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

    //type类型；trend：房价指数；increase：房价涨跌 ;question: 购房问题
    async getHousePriceFeature() {

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

        const type = input_parmas.type;
        const area_code = input_parmas.area_code;
        let ret = [];
        if (type === 'trend') {
            ret = await ctx.blockModel.HousePriceTrend.one({ where: { id: area_code } });
            ret = ret ? ret.trend_json : [];
        } else if (type === 'increase') {
            ret = await ctx.blockModel.HousePriceIncrease.one({ where: { id: area_code } });
            ret = ret ? ret.increase_json : [];
        } else if (type === 'question') {
            ret = await ctx.blockModel.HouseQuestion.one({ where: { id: area_code } });
            ret = ret ? ret.question_json : [];
        }

        ctx.success(ret);
    }

    //房产估价
    async calculateHousePrice() {

        const { ctx } = this;
        const input_params = ctx.request.body;
        const rule = {
            residential_id: { type: 'string', required: true, },
            residential_name: { type: 'string', required: true, },
            area: { type: 'string', required: true },
            direction_str: { type: 'string', required: true },
            floor: { type: 'string', required: true },
            total_floor: { type: 'string', required: true },
            city_py: { type: 'string', required: true },
        };
        ctx.validate(rule, input_params);
        // const city = await ctx.blockModel.City.one({ where: { code: input_params.area_code } });
        // if (!city || !city.pinyin || Object.keys(city).length === 0) {
        //     ctx.failed('暂不支持城市');
        // }
        // const city_pinyin_array = city.pinyin.split(' ');
        // let city_pinyin = '';
        // for (let i = 0; i < city_pinyin_array.length - 1; i++) {
        //     const pinyin = city_pinyin_array[i];
        //     city_pinyin += pinyin;
        // };
        const city_pinyin = input_params.city_py;
        const residential_id = input_params.residential_id;
        const residential_name = input_params.residential_name;
        const area = input_params.area;
        const direction_str = input_params.direction_str;
        const floor = input_params.floor;
        const total_floor = input_params.total_floor;
        const qfang_url_area = `https://${city_pinyin}.qfang.com/fangjia/area`;
        // const query_string = encodeURIComponent(`userName=&gardenId=&gardenInternalID=${residential_id}&name=${residential_name}&area=${area}&floor=${floor}&totlaFloor=${total_floor}&directionStr=${direction_str}&buildingId=&building=&roomNoId=&roomNo=&subQueryType=quick`);
        // const qfang_url_chaxun = 'https://hangzhou.qfang.com/fangjia/chaxun?userName=&gardenId=&gardenInternalID=1f552c71-2747-4539-aeaa-0fc37a6dcd10&name=%E4%B8%87%E9%83%BD%E6%99%B6%E5%BA%A7&area=12&floor=2&totlaFloor=10&directionStr=SOUTHEAST&buildingId=&building=&roomNoId=&roomNo=&subQueryType=quick';
        const qfang_url_chaxun = `https://${city_pinyin}.qfang.com/fangjia/chaxun?userName=&gardenId=&gardenInternalID=${residential_id}&name=${encodeURIComponent(residential_name)}&area=${area}&floor=${floor}&totlaFloor=${total_floor}&directionStr=${direction_str}&buildingId=&building=&roomNoId=&roomNo=&subQueryType=quick`;
        // console.info(qfang_url_chaxun);
        // const data = {
        //     userName: '',
        //     gardenId: '',
        //     gardenInternalID: 'c1283359-9995-4a52-ae76-ca06135b825c',
        //     name: '中天九溪诚品',
        //     area: 100,
        //     floor: 2,
        //     totlaFloor: 6,
        //     directionStr: 'SOUTHEAST',
        //     buildingId: '',
        //     building: '',
        //     roomNoId: '',
        //     roomNo: '',
        //     subQueryType: 'quick',
        // }

        // await this.httprequest(qfang_url_chaxun, data);
        // return;
        let ret1;
        try {
            ret1 = await ctx.curl(qfang_url_area, { method: 'POST' });
        } catch (error) {
            ctx.failed('暂不支持该城市');
        }

        // ctx.success(ret1); return;
        const headers = ret1.headers;
        const cookies = headers['set-cookie'];
        let cookie = '';
        for (let i in cookies) {
            const cookie_items = cookies[i].split(';');
            cookie += cookie_items[0] + '; ';
        }
        const user_agent_length = USER_AGENT.length;
        const random = Math.floor(Math.random() * user_agent_length);
        const user_agent = USER_AGENT[random];

        const ret2 = await new Promise((resolve, reject) => {
            request({
                url: qfang_url_chaxun,
                jar: request.jar(),
                headers: {
                    'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
                    'accept-encoding': 'gzip, deflate, br',
                    'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8',
                    'cache-control': 'max-age=0',
                    'cookie': cookie,
                    'referer': qfang_url_chaxun,
                    'upgrade-insecure-requests': 1,
                    'user-agent': user_agent,
                }

            }, function (error, response, body) {
                ctx.logger.info('qfang_url_chaxun_result: ' + JSON.stringify(response));
                // ctx.logger.info('qfang_url_chaxun_html: ' + body);
                if (!error && response.statusCode == 200) {
                    var resultStr = body.replace(/\ +/g, ""); //去掉空格
                    resultStr = resultStr.replace(/[ ]/g, "");    //去掉空格
                    resultStr = resultStr.replace(/[\r\n]/g, ""); //去掉回车换行
                    resultStr = resultStr.replace(/[\n]/g, ""); //去掉换行
                    resultStr = resultStr.replace(/[\r]/g, ""); //去掉回车
                    resolve(body) // 请求成功的处理逻辑
                }
            });
        });

        let average_price = 0;
        let average_price_unit = '';
        let total_price = 0;
        let total_price_unit = '';

        if (ret2 && ret2.length !== 0) {
            const $ = cheerio.load(ret2);
            average_price_unit = $('p.title-result span').text();
            average_price = parseFloat($('.average-price-data p.title-result').text().replace(average_price_unit, ''));
            total_price = parseFloat($('#targetNum').text());
            total_price_unit = $('span.average-price', '.fl').text().replace(total_price, '');
            if (!average_price || !total_price) {
                average_price = 0;
                average_price_unit = '';
                total_price = 0;
                total_price_unit = '';
            }
        }

        ctx.success({ average_price, average_price_unit, total_price, total_price_unit });
    }

    //并无实际用途  只用于调试测试用
    async httprequest(url, data) {
        const { ctx } = this;
        let ret2 = await ctx.curl('https://hangzhou.qfang.com/fangjia/area', { method: 'POST', data: data });

        var cookies = ret2.headers['set-cookie'];
        var cookie = '';
        for (let item in cookies) {
            let cookie_items = cookies[item].split(';');
            cookie += cookie_items[0] + '; ';
        }

        console.log(url)
        request({
            url: url,
            jar: request.jar(),
            headers: {
                'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
                'accept-encoding': 'gzip, deflate, br',
                'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8',
                'cache-control': 'max-age=0',
                'cookie': cookie,
                'referer': 'https://hangzhou.qfang.com/fangjia/chaxun?userName=&gardenId=&gardenInternalID=F3365A31BBB6F477E040A8C112002A44&name=%E5%9F%8E%E4%B8%AD%E8%8A%B1%E5%9B%AD&area=100&floor=1&totlaFloor=12&directionStr=NORTHSOUTH&buildingId=&building=&roomNoId=&roomNo=&subQueryType=quick',
                'upgrade-insecure-requests': 1,
                'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36',
            }

        }, function (error, response, body) {
            //console.log(error)
            console.log(response)
            if (!error && response.statusCode == 200) {


                var resultStr = body.replace(/\ +/g, ""); //去掉空格
                resultStr = resultStr.replace(/[ ]/g, "");    //去掉空格
                resultStr = resultStr.replace(/[\r\n]/g, ""); //去掉回车换行
                resultStr = resultStr.replace(/[\n]/g, ""); //去掉换行
                resultStr = resultStr.replace(/[\r]/g, ""); //去掉回车

                //console.log(resultStr) // 请求成功的处理逻辑

            }
        });
    };


    async getQFangAreaList() {

        const { ctx } = this;
        const input_parmas = ctx.query;
        const rule = {
            keyword: { type: 'string', required: true },
            city_py: { type: 'string', required: true },
        }
        ctx.validate(rule, input_parmas);
        // const city = await ctx.blockModel.City.one({ where: { code: input_parmas.area_code } });
        // if (!city || !city.pinyin || Object.keys(city).length === 0) {
        //     ctx.failed('暂不支持城市');
        // }
        // const city_pinyin_array = city.pinyin.split(' ');
        // let city_pinyin = '';
        // for (let i = 0; i < city_pinyin_array.length - 1; i++) {
        //     const pinyin = city_pinyin_array[i];
        //     city_pinyin += pinyin;
        // };
        const city_pinyin = input_parmas.city_py;
        const qfang_url = `https://${city_pinyin}.qfang.com/fangjia/getGarden`;
        const keyword = encodeURIComponent(input_parmas.keyword);
        let result;
        try {
            result = await ctx.helper.send_request(qfang_url + '?keyword=' + keyword, {}, { dataType: 'json' });
        } catch (error) {
            ctx.failed('暂不支持该城市');
        }

        let ret = [];
        if (result.status !== 200) {
            ctx.failed('暂不支持该城市');
        }
        if (result.status === 200 && result.data && result.data.items) {
            const residential_items = result.data.items;
            for (let i in residential_items) {
                const residential_item = residential_items[i];
                ret.push({
                    residential_id: residential_item.id,
                    residential_name: residential_item.name,
                });
            }
        }

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

module.exports = ToolController;
