/**
 * 工料机相关控制器
 *
 * @author CaiAoLin
 * @date 2017/6/22
 * @version
 */
import BaseController from "../../common/base/base_controller";
import GLJTypeConst from "../../common/const/glj_type_const";
import GLJListModel from "../models/glj_list_model";
import UnitPriceModel from "../models/unit_price_model";
import MixRatioModel from "../models/mix_ratio_model";
import UnitPriceFileModel from "../models/unit_price_file_model";

const ProjectModel = require('../../pm/models/project_model').project;
class GLJController extends BaseController {

    /**
     * 构造函数
     *
     * @return {void}
     */
    constructor() {
        let parent = super();
        parent.title = '工料机';
    }

    /**
     * 获取工料机相关数据
     *
     * @param {object} request
     * @param {object} response
     * @return {void}
     */
    async getGljList(request, response) {
        // 标段id
        let projectId = request.body.project_id;
        projectId = parseInt(projectId);
        let responseData = {
            err: 0,
            msg: '',
            data: {}
        };
        try {
            if (isNaN(projectId) || projectId <= 0) {
                throw '标段id有误';
            }

            // 获取标段对应的单价文件id
            let unitPriceFileId = await ProjectModel.getUnitPriceFileId(projectId);
            if (unitPriceFileId <= 0) {
                throw '没有对应的单价文件';
            }

            // 获取使用该单价文件的项目数据
            let tenderData = await ProjectModel.getTenderByUnitPriceFileId(unitPriceFileId);
            let usedTenderList = [];
            let usedUnitPriceInfo = {};
            if (tenderData !== null) {
                for (let tmp of tenderData) {
                    usedTenderList.push(tmp.name);
                    usedUnitPriceInfo.name = tmp.property.unitPriceFile.name;
                    usedUnitPriceInfo.id = tmp.property.unitPriceFile.id;
                }
            }

            // 先获取对应标段的项目工料机数据
            let gljListModel = new GLJListModel();
            let [gljList, mixRatioConnectData] = await gljListModel.getListByProjectId(projectId, unitPriceFileId);

            responseData.data.gljList = gljList;
            responseData.data.mixRatioConnectData = mixRatioConnectData;
            responseData.data.usedTenderList = usedTenderList;
            responseData.data.constData = {
                materialIdList: gljListModel.materialIdList,
                ownCompositionTypes: gljListModel.ownCompositionTypes,
                hostname: request.hostname,
                roomId: unitPriceFileId,
                GLJTypeConst: JSON.stringify(GLJTypeConst),
                usedUnitPriceInfo: usedUnitPriceInfo
            };
        } catch (error) {
            responseData.err = 1;
            responseData.msg = error;
        }

        response.json(responseData);
    }

    /**
     * 更新数据
     *
     * @param {object} request
     * @param {object} response
     * @return {void}
     */
    async updateData(request, response) {
        let field = request.body.field;
        let value = request.body.value;
        value = value === 'true' ? 1 : value;
        value = value === 'false' ? 0 : value;
        let id = request.body.id;

        let responseData = {
            err: 0,
            msg: ''
        };
        try {
            // 可编辑的字段
            let editableField = ['is_evaluate', 'unit_price.market_price', 'is_adjust_price', 'mix_ratio.consumption'];
            if (editableField.indexOf(field) < 0) {
                throw '对应字段不能编辑';
            }

            let modelString = 'glj';
            // 切割字段
            let fieldArray = field.split('.');
            modelString = fieldArray.length > 1 ? fieldArray[0] : modelString;
            field = fieldArray.length > 1 ? fieldArray[1] : field;

            // 组合数据
            let updateData = new Object();
            updateData[field] = value;

            let result = false;
            let model = null;
            switch (modelString) {
                case 'glj':
                    model = new GLJListModel();
                    // 更新数据
                    result = await model.updateById(id, updateData);

                    break;
                case 'unit_price':
                    let extend = request.body.extend;
                    model = new UnitPriceModel();
                    // 更新数据
                    result = await model.updatePrice({id: id}, updateData, extend);

                    break;
                case 'mix_ratio':
                    let marketPrice = request.body.market_price;
                    let basePrice = request.body.base_price;

                    model = new MixRatioModel();
                    result = await model.updateById(id, updateData);

                    if (result && marketPrice && basePrice) {
                        // 修改后更新父节点的项目工料机市场单价
                        let mixRatioData = await model.findDataByCondition({id: id});
                        if (mixRatioData.length <= 0) {
                            break;
                        }
                        // 更新市场单价和基价单价
                        let condition = {code: mixRatioData.connect_code, unit_price_file_id: mixRatioData.unit_price_file_id};
                        let unitPriceUpdate = {
                            base_price: basePrice,
                            market_price: marketPrice
                        };
                        let unitPriceModel = new UnitPriceModel();
                        let unitPriceResult = await unitPriceModel.updatePrice(condition, unitPriceUpdate);
                        if (!unitPriceResult) {
                            throw '更新单价数据失败';
                        }
                    }

                    break;
            }

            if (!result) {
                throw '更新失败';
            }
        } catch (error) {
            console.log('error:' + error);
            responseData.err = 1;
        }

        response.json(responseData);
    }

    /**
     * 加载配合比相关数据
     *
     * @return {void}
     */
    async getRatio(request, response) {
        let projectGLJId = request.body.id;
        let projectId = request.body.project_id;
        let responseData = {
            err: 0,
            data: null
        };
        try {
            // 获取标段对应的单价文件id
            let unitPriceFileId = await ProjectModel.getUnitPriceFileId(projectId);
            if (unitPriceFileId <= 0) {
                throw '没有对应的单价文件';
            }

            let gljListModel = new GLJListModel();
            let result = await gljListModel.getCompositionList(projectGLJId, unitPriceFileId);
            if (result.length <= 0) {
                throw '没有找到数据';
            }

            responseData.data = JSON.stringify(result);
        } catch (error) {
            console.log(error);
            responseData.err = 1;
        }

        response.json(responseData);
    }

    /**
     * 删除配合比数据
     *
     * @param {object} request
     * @param {object} response
     * @return {void}
     */
    async deleteMixRatio(request, response) {
        let id = request.body.id;
        id = parseInt(id);
        let responseData = {
            err: 0,
            msg: ''
        };
        try {
            if (isNaN(id) || id <= 0) {
                throw '参数错误';
            }

            let mixRatioModel = new MixRatioModel();
            let result = await mixRatioModel.deleteById(id);
            if (!result) {
                throw '删除失败';
            }
        } catch (error) {
            responseData.err = 1;
            responseData.msg = error;
        }

        response.json(responseData);
    }

    /**
     * 获取项目与单价文件对应的数据
     *
     * @param {object} request
     * @param {object} response
     * @return {void}
     */
    async getProjectInfo(request, response) {
        let projectId = request.body.project_id;
        projectId = parseInt(projectId);
        let responseData = {
            err: 0,
            data: null
        };
        try {
            let sessionUserData = request.session.sessionUser;
            // 获取对应用户所有的建设项目数据
            let projectList = await ProjectModel.getUserProjectData(sessionUserData.ssoId);
            if (projectList === null) {
                throw '没有找到对应的项目数据';
            }
            // 转换mongoose数据
            projectList = JSON.stringify(projectList);
            projectList = JSON.parse(projectList);

            let result = {
                self: [],
                other: []
            };
            for (let index in projectList) {
                // 获取对应建设项目下所有的单位工程id
                let idList = await ProjectModel.getTenderByProjectId(projectList[index].ID);
                if (idList.length <= 0) {
                    continue;
                }

                // 获取对应的单价文件
                let unitPriceFileModel = new UnitPriceFileModel();
                let unitPriceFileData = await unitPriceFileModel.getDataByTenderId(idList);
                projectList[index].unitPriceList = unitPriceFileData;

                // 归类
                if (idList.indexOf(projectId) >= 0) {
                    result.self = unitPriceFileData;
                } else {
                    result.other.push(projectList[index]);
                }
            }
            responseData.data = result;
            response.json(responseData);

        } catch (error) {
            responseData.err = 1;
            response.json(responseData);
        }
    }

    /**
     * 更改单价文件
     *
     * @param {object} request
     * @param {object} response
     * @return {void}
     */
    async changeUnitPriceFile(request, response) {
        let projectId = request.body.project_id;
        let changeUnitPriceId = request.body.change_id;
        let responseData = {
            err: 0,
            msg: ''
        };
        try {
            let currentUnitPriceId = await ProjectModel.getUnitPriceFileId(projectId);

            // 获取即将更改的单价文件信息
            let unitPriceFileModel = new UnitPriceFileModel();
            let targetUnitPriceFile = await unitPriceFileModel.findDataByCondition({id: changeUnitPriceId});
            if (targetUnitPriceFile === null) {
                throw '没有找到对应的单价文件';
            }

            // 查找对应单价文件的项目工料机数据
            let unitPriceModel = new UnitPriceModel();
            let copyResult = await unitPriceModel.copyNotExist(currentUnitPriceId, changeUnitPriceId);
            // 复制成功后更改project数据
            if (!copyResult) {
                throw '复制数据失败';
            }

            let changeUnitPriceFileInfo = {
                id: targetUnitPriceFile.id,
                name: targetUnitPriceFile.name
            };
            let result = ProjectModel.changeUnitPriceFileInfo(projectId, changeUnitPriceFileInfo);
            if (!result) {
                throw '切换单价文件失败!';
            }

        } catch (error) {
            console.log(error);
            responseData.err = 1;
            responseData.msg = error;
        }

        response.json(responseData);
    }

    /**
     * 模拟定额插入
     *
     * @param {object} request
     * @param {object} response
     * @return {void}
     */
    async test(request, response) {
        // 从定额库获取的数据
        let data = {
            glj_id: 17,
            project_id: 1,
            code: '00010201',
            name: '土石方综合工日',
            specs: '',
            unit: '工日',
            type: GLJTypeConst.LABOUR,
            base_price: 50,
            market_price: 50
        };
        try {
            let gljListModel = new GLJListModel();
            let result = await gljListModel.addList(data);

        } catch (error) {
            console.log(error);
        }

        response.end('success');
    }

    /**
     * 模拟定额修改单价
     *
     * @param {object} request
     * @param {object} response
     * @return {void}
     */
    async testModify(request, response) {
        let projectId = request.query.project;
        // 修改数据
        let updateData = {
            code: '36290101',
            market_price: '13',
            name: '水(10)',
            project_id: projectId
        };

        try {
            let gljListModel = new GLJListModel();
            let result = await gljListModel.modifyMarketPrice(updateData);

            console.log(result);
        } catch (error) {
            console.log(error);
        }
        response.end('success');
    }

    /**
     * 测试删除
     *
     * @param {object} request
     * @param {object} response
     * @return {void}
     */
    async delete(request, response) {
        try {
            let gljListModel = new GLJListModel();
            let result = await gljListModel.deleteById(63);

            console.log(result);
        } catch (error) {
            console.log(error);
        }
        response.end('success');
    }
}

export default GLJController;
