'use strict';

const Controller = require('egg').Controller;
const moment = require('moment');
class Export20190425 extends Controller {

    //新房 包含了对应的新房户型和小区信息
    async moveNewHouse() {
        const { ctx } = this;
        let data = {
            pageIndex: 1,
            pageSize: 999,
            orderConditions: [{
                key: 'id',
                orderSequence: 'asc',
            }]
        }
        const retList = await ctx.helper.send_request(this.config.HOUSE_SERVICE_API + '/v1/newhouse/list', data, { method: 'POST' });
        if (retList.status !== 200) {
            ctx.failed('error');
        }
        let newHouseList = retList.data;
        let ret = {
            new_org_count: newHouseList.rowCount,
            new_data: [],
            type_data: [],
        };
        if (newHouseList.rowCount > 0) {
            let list = newHouseList.results;
            let newHouseData = [];
            for (let i in list) {
                const houseType = { 1: '住宅', 2: '公寓', 3: '别墅', 4: '商业', 5: '写字', 6: '底商' };
                newHouseData[i] = {
                    id: list[i].id,
                    name: list[i].name,
                    developer_id: 4,//暂时默认写个4
                    province: list[i].residential.province,
                    city: list[i].residential.city,
                    area: list[i].residential.county,
                    address: list[i].address,
                    sale_province: list[i].residential.province,
                    sale_city: list[i].residential.city,
                    sale_area: list[i].residential.county,
                    sale_address: list[i].saleAddress,
                    tags: list[i].tags.replace(/'/g, '"'),
                    sale_type: list[i].saleType,
                    house_type: houseType[list[i].houseType],
                    reference_avg_price: list[i].referenceAvgPrice,
                    reference_total_price: list[i].referenceTotalPrice,
                    image: list[i].image,
                    corner: list[i].cornerMarker,
                    discount: list[i].discount || null,
                    favourable_info: list[i].favourableInfo || null,
                    decoration_type: list[i].decorationType || null,
                    description: list[i].description || null,
                    open_date: list[i].openDate,
                    due_date: list[i].dueDate,
                    plan_rooms: list[i].planRooms,
                    plan_parks: list[i].planParks,
                    plan_near_by: list[i].planNearBy,
                    pre_sale_permit: list[i].preSalePermit,
                    pre_sale_permit_date: list[i].preSalePermitDate,
                    building_numbers: list[i].buildingNumbers,
                    selling_qualification: list[i].xxx,
                    remark: list[i].remark,
                    // is_reality: list[i].xxx,
                    order_id: list[i].orderNum === 9999 ? 0 : list[i].orderNum,
                    status: Number(list[i].state) === 0 ? 'offline' : 'online',
                    valid: 1,
                    created_at: list[i].createdAt,
                    updated_at: list[i].updatedAt || null,
                    // deleted_at: list[i].xxx,
                    option_city_code: list[i].residential.city,
                    option_district_code: list[i].residential.county,
                    option_bizicircle_code: list[i].residential.region,
                    residential_property_right_years: list[i].residential.propertyRightYears,
                    residential_property_fee: list[i].residential.propertyFee,
                    residential_property_company: list[i].residential.propertyCompany,
                    residential_heat_supply_type: list[i].residential.heatSupplyType,
                    residential_water_suppler_type: list[i].residential.waterSupplyType,
                    residential_power_suppler_type: list[i].residential.powerSupplyType,
                    residential_land_area: list[i].residential.landArea,
                    residential_house_area: list[i].residential.houseArea,
                    residential_area_ratio: list[i].residential.areaRatio,
                    residential_green_ratio: list[i].residential.greenRatio,
                    residential_arch_type: list[i].residential.archType,
                    residential_nearby: list[i].residential.nearBy,
                }

                //户型
                if (list[i].newHouseType.length > 0) {
                    let newHouseType = list[i].newHouseType;
                    let newHouseDataTypeData = [];
                    for (let j in newHouseType) {
                        newHouseDataTypeData[j] = {
                            id: newHouseType[j].id,
                            new_house_id: newHouseType[j].newHouseId,
                            type: newHouseType[j].type,
                            image: newHouseType[j].image,
                            tags: newHouseType[j].tags.replace(/'/g, '"'),
                            apartment: newHouseType[j].apartment,
                            sale_type: newHouseType[j].saleType,
                            area: newHouseType[j].area,
                            orientation: newHouseType[j].orientation,
                            num: newHouseType[j].num,
                            price: newHouseType[j].price,
                            discount: newHouseType[j].discount,
                            status: Number(newHouseType[j].state) === 0 ? 'offline' : 'online',
                            remark: newHouseType[j].remark,
                            valid: 1,
                            created_at: newHouseType[j].created_at,
                            updated_at: newHouseType[j].updated_at || null,
                            // deleted_at: list.newHouseType[j].xxx,
                        }
                    }
                    let type_data = await ctx.realestateModel.NewHouseType.bulkCreate(newHouseDataTypeData, { ignoreDuplicates: true });
                    ret.type_data = ret.type_data.concat(type_data);
                }
            }
            //房源信息和小区信息
            let new_data = await ctx.realestateModel.NewHouse.bulkCreate(newHouseData, { ignoreDuplicates: true });
            ret.new_data = ret.new_data.concat(new_data);
        }
        ret.new_count = ret.new_data.length;
        ret.type_count = ret.type_data.length;
        ctx.success(ret);
    }


    //收藏
    async moveCollection() {
        const { ctx } = this;
        let ret = {
            data: [],
        };
        let k = 0;
        for (k = 1; k < 999; k++) {
            let data = {
                pageIndex: k,
                pageSize: 500,
                orderConditions: [{
                    key: 'id',
                    orderSequence: 'asc',
                }]
            }
            const result = await ctx.helper.send_request(this.config.HOUSE_SERVICE_API + '/v1/collection/list', data, { method: 'POST' });
            if (result.status !== 200) {
                ctx.failed('error');
            }
            let res = result.data;
            if (res.results.length === 0) {
                break;
            }
            ret.org_count = res.rowCount;
            let list = res.results;
            let addData = [];
            for (let i in list) {
                addData[i] = {
                    id: list[i].id,
                    user_id: list[i].userId,
                    app_user_id: list[i].appUserId,
                    house_style: list[i].houseStyle,
                    connect_id: list[i].connectId,
                    state: list[i].state,
                    remark: list[i].remark,
                    created_at: list[i].createdAt,
                    updated_at: list[i].updatedAt || null,
                    // deleted_at: list[i].xxx,
                }
            }
            let addRes = await ctx.realestateModel.Collection.bulkCreate(addData, { ignoreDuplicates: true });
            ret.data = ret.data.concat(addRes);
        }
        ret.count = ret.data.length;
        ctx.success(ret);
    }

    //预约
    async moveOrder() {
        const { ctx } = this;
        let ret = {
            data: [],
        };
        let k = 0;
        for (k = 1; k < 999; k++) {
            let data = {
                pageIndex: k,
                pageSize: 500,
                orderConditions: [{
                    key: 'id',
                    orderSequence: 'asc',
                }]
            }
            const result = await ctx.helper.send_request(this.config.HOUSE_SERVICE_API + '/v1/order/list', data, { method: 'POST' });
            if (result.status !== 200) {
                ctx.failed('error');
            }
            let res = result.data;
            if (res.results.length === 0) {
                break;
            }
            ret.org_count = res.rowCount;
            let list = res.results;
            let addData = [];
            for (let i in list) {
                addData[i] = {
                    id: list[i].id,
                    user_id: list[i].userId,
                    app_user_id: list[i].appUserId,
                    house_style: list[i].houseStyle,
                    connect_id: list[i].connectId,
                    name: list[i].name,
                    phone: list[i].phone,
                    order_at: list[i].orderAt,
                    state: list[i].state,
                    remark: list[i].remark,
                    created_at: list[i].createdAt,
                    updated_at: list[i].updatedAt || null,
                    // deleted_at:list[i].xxx,
                }
            }
            let addRes = await ctx.realestateModel.Order.bulkCreate(addData, { ignoreDuplicates: true });
            ret.data = ret.data.concat(addRes);
        }
        ret.count = ret.data.length;
        ctx.success(ret);
    }


    //搜索历史
    async moveHistory() {
        const { ctx } = this;
        let ret = {
            data: [],
        };
        let k = 0;
        for (k = 1; k < 999; k++) {
            let data = {
                pageIndex: k,
                pageSize: 500,
                orderConditions: [{
                    key: 'id',
                    orderSequence: 'asc',
                }]
            }
            const result = await ctx.helper.send_request(this.config.HOUSE_SERVICE_API + '/v1/searchhistory/list', data, { method: 'POST' });
            if (result.status !== 200) {
                ctx.failed('error');
            }
            let res = result.data;
            if (res.results.length === 0) {
                break;
            }
            ret.org_count = res.rowCount;
            let list = res.results;
            let addData = [];
            for (let i in list) {
                addData[i] = {
                    id: list[i].id,
                    user_id: list[i].userId,
                    app_user_id: list[i].appUserId,
                    key_word: list[i].keyWord,
                    house_style: list[i].houseStyle,
                    state: list[i].state,
                    created_at: list[i].createdAt,
                    // updated_at: list[i].xxx,
                    // deleted_at: list[i].xxx,
                }
            }
            let addRes = await ctx.realestateModel.SearchHistory.bulkCreate(addData, { ignoreDuplicates: true });
            ret.data = ret.data.concat(addRes);
        }
        ret.count = ret.data.length;
        ctx.success(ret);
    }

    //足迹
    async moveFoot() {
        const { ctx } = this;
        let ret = {
            data: [],
        };
        let k = 0;
        for (k = 1; k < 999; k++) {
            let data = {
                pageIndex: k,
                pageSize: 500,
                orderConditions: [{
                    key: 'id',
                    orderSequence: 'asc',
                }]
            }
            const result = await ctx.helper.send_request(this.config.HOUSE_SERVICE_API + '/v1/footprint/list', data, { method: 'POST' });
            if (result.status !== 200) {
                ctx.failed('error');
            }
            let res = result.data;
            if (res.results.length === 0) {
                break;
            }
            ret.org_count = res.rowCount;
            let list = res.results;
            let addData = [];
            for (let i in list) {
                addData[i] = {
                    id: list[i].id,
                    user_id: list[i].userId,
                    // app_type_id:list[i].xxx,
                    app_user_id: list[i].appUserId,
                    house_style: list[i].houseStyle,
                    connect_id: list[i].connectId,
                    state: list[i].state,
                    remark: list[i].remark,
                    created_at: list[i].createdAt,
                    updated_at: list[i].updatedAt || null,
                    // deleted_at: list[i].xxx,
                }
            }
            let addRes = await ctx.realestateModel.FootPrint.bulkCreate(addData, { ignoreDuplicates: true });
            ret.data = ret.data.concat(addRes);
        }
        ret.count = ret.data.length;
        ctx.success(ret);
    }

    //租房数据迁移
    async moveRentalHouse() {

        const { ctx } = this;
        let data = {
            pageIndex: 1,
            pageSize: 999,
            orderConditions: [{
                key: 'id',
                orderSequence: 'asc',
            }]
        }
        const result = await ctx.helper.send_request(this.config.HOUSE_SERVICE_API + '/v1/rentalHouse/list', data, { method: 'POST' });
        if (result.status !== 200) {
            ctx.failed('error');
        }
        const now_time = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
        const rental_houses = result.data.results;
        const residential_developers = { 568: 1, 569: 1, 570: 2, 571: 2, 572: 2, 573: 3, 574: 3, 575: 4, 576: 5, 577: 2, 578: 2, 579: 2, 580: 2, 581: 2, 582: 2, 583: 2, 584: 2, 585: 2, 586: 2, 587: 3, 588: 3, 589: 3, 590: 6, 591: 7, 592: 8, 593: 8, 594: 9, 595: 9, 596: 9, 597: 9, 598: 9, 599: 9 };
        const rental_house_type_data = [];
        const rental_house_data = [];
        for (const i in rental_houses) {
            const rental_house = rental_houses[i];
            const residential = rental_house.residential;
            const rental_house_types = rental_house.rentalHouseType;
            for (const j in rental_house_types) {
                const rental_house_type = rental_house_types[j];
                rental_house_type_data.push({
                    name: rental_house_type.name,
                    rental_house_id: rental_house_type.rentalHouseId,
                    type: rental_house_type.type,
                    price: rental_house_type.price,
                    discount: rental_house_type.discount,
                    area: rental_house_type.area,
                    remark: rental_house_type.remark,
                    status: rental_house_type.state ? 'online' : 'offline',
                    created_at: rental_house_type.createdAt,
                    updated_at: now_time,
                });
            }
            const tmp = {
                id: rental_house.id,
                name: rental_house.name,
                province: residential.province,
                city: residential.city,
                area: residential.county,
                option_city_code: residential.city,
                option_district_code: residential.county,
                option_bizicircle_code: residential.region,
                developer_id: residential_developers[residential.id],
                rental_type: 1,
                address: rental_house.address.replace('杭州市', '').replace('重庆市', '').replace('北京市', ''),
                price: rental_house.price,
                discount: rental_house.discount,
                image: rental_house.image,
                business_license: rental_house.businessLicense,
                notice: rental_house.notice,
                tags: rental_house.tags,
                favourable_info: rental_house.favourableInfo,
                limit_cities: rental_house.limitCities,
                room_configuration: rental_house.roomConfiguration,
                description: rental_house.description,
                order_id: 0,
                status: 'online',
                valid: 1,
                created_at: rental_house.createdAt,
                updated_at: now_time,
            }
            rental_house_data.push(tmp);
        }
        const rental_house_ret = await ctx.realestateModel.RentalHouse.bulkCreate(rental_house_data);
        const rental_house_type_ret = await ctx.realestateModel.RentalHouseType.bulkCreate(rental_house_type_data);
        const ret = { rental_house_count: rental_house_ret.length, rental_house_ret, rental_house_type_count: rental_house_type_ret.length, rental_house_type_ret };
        ctx.success(ret);
    }

    //开发商数据迁移
    async moveDeveloper() {

        const { ctx } = this;
        let data = {
            pageIndex: 1,
            pageSize: 999,
            orderConditions: [{
                key: 'id',
                orderSequence: 'asc',
            }]
        }
        const result = await ctx.helper.send_request(this.config.HOUSE_SERVICE_API + '/v1/developer/list', data, { method: 'POST' });
        if (result.status !== 200) {
            ctx.failed('error');
        }
        const now_time = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
        const developers = result.data.results;
        const developer_data = [];
        for (let i in developers) {
            const developer = developers[i];
            developer_data.push({
                id: developer.id,
                short_name: developer.shortName,
                name: developer.name,
                logo: developer.logo,
                order_id: developer.orderNum,
                description: developer.description,
                status: 'online',
                valid: 1,
                created_at: developer.createdAt,
                updated_at: now_time,

            });
        }
        const developer_ret = await ctx.realestateModel.Developer.bulkCreate(developer_data);
        const ret = { affect_count: developer_ret.length, developer_ret };
        ctx.success(ret);
    }

    //
    async moveHouseImage() {

        const { ctx } = this;
        let data = {
            pageIndex: 1,
            pageSize: 500,
            orderConditions: [{
                key: 'id',
                orderSequence: 'asc',
            }]
        }
        let house_image_data = [];
        const now_time = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
        for (let i = 1; i < 999; i++) {
            data.pageIndex = i;
            const result = await ctx.helper.send_request(this.config.HOUSE_SERVICE_API + '/v1/houseimage/list', data, { method: 'POST' });
            if (result.status !== 200) {
                ctx.failed('error');
            }
            const house_images = result.data.results;
            if (house_images.length === 0) break;
            for (let j in house_images) {
                const house_image = house_images[j];
                if (house_image.state === 0) continue;
                house_image_data.push({
                    // id: house_image.id,
                    path: house_image.path,
                    connect_id: house_image.connectId,
                    type: house_image.type,
                    description: house_image.description,
                    remark: house_image.remark,
                    status: 'online',
                    valid: 1,
                    created_at: house_image.createdAt,
                    updated_at: now_time
                });
            }
        }
        const house_image_ret = await ctx.realestateModel.HouseImage.bulkCreate(house_image_data);
        const ret = { affect_count: house_image_ret.length, house_image_ret };
        ctx.success(ret);

    }

    async updateNewHouseTotalPrice() {
        const { ctx } = this;
        let query = 'SELECT aa.id,aa.`name`,aa.reference_avg_price,aa.reference_total_price,MIN(bb.area) min_area from new_house aa LEFT JOIN new_house_type bb ON (aa.id = bb.new_house_id AND bb.area IS NOT NULL AND bb.area != 0) WHERE aa.reference_total_price = 0 GROUP BY aa.id';
        let queryFilter = {
            type: ctx.realestateModel.QueryTypes.SELECT,
            raw: true
        }
        let data = await ctx.realestateModel.query(query, queryFilter);
        let taskList = [];
        for (let i in data) {
            if (data[i].min_area === null) {
                continue;
            }
            if (Number(data[i].min_area) === 0) {
                // ctx.logger.info(data[i]);
                continue;
            }
            if (Number(data[i].reference_total_price) !== 0) {
                continue;
            }
            if (Number(data[i].reference_avg_price) === 0) {
                continue;
            }
            let totalPrice = Math.ceil(Number(data[i].reference_avg_price) * Number(data[i].min_area) / 10000);
            let update = { reference_total_price: totalPrice };
            let where = { where: { id: data[i].id } }
            taskList[i] = ctx.realestateModel.NewHouse.update(update, where);
        }

        let retList = await Promise.all(taskList).then(result => {
            return result;
        }).catch(error => {
            ctx.failed(error);
        });
        ctx.success(retList);

    }

}

module.exports = Export20190425;
