const system = require("../../../system");
const ServiceBase = require("../../sve.base");
const settings = require("../../../../config/settings");

class FormitemService extends ServiceBase {
    constructor() {
        super("configmag", ServiceBase.getDaoName(FormitemService));
    }

    async getFormItemListByFormId(pobj){
        if(!pobj || !pobj.form_id){
            return system.getResultFail(-101,"表单id不能为空");
        }
        var list = await this.dao.model.findAll({
            attributes:[["code","key"],["name","title"]],
            where:{form_id:pobj.form_id},
            raw:true,
            order:[["sequence","asc"]]
        });
        return system.getResultSuccess(list);
    }
    /**
     * 创建表单项
     * @param pobj
     * @returns {Promise<void>}
     */
    async createItem(pobj) {
        if(!pobj.name){
            return system.getResultFail(-1,'表单项名称不能为空');
        }
        if(!pobj.sequence){
            return system.getResultFail(-1,'排序不能为空')
        }
        let config_params = await this.packageConfigParams(pobj);
        let code = await this.getBusUid('it');
        pobj.config_params = config_params;
        pobj.item_type_name = pobj.item_type_name;
        pobj.code = code;
        //保存表单项
        let result = await this.create(pobj);
        return system.getResult(result)
    }

    /**
     * 修改表表单项
     * @param pobj
     * @returns {Promise<void>}
     */
    async updateItem(pobj) {
        //参数重组
        if(!pobj.name){
            return system.getResultFail(-1,'表单名称不能为空');
        }
        if(!pobj.form_describe){
            return system.getResultFail(-1,'表单描述不能为空')
        }
        let config_params = await this.packageConfigParams(pobj);
        pobj.config_params = config_params;
        let upResult = await this.update(pobj);
        return system.getResult(upResult);
    }

    /**
     * 组装表单项参数
     * @param pobj
     * @returns {Promise<void>}
     */
    async packageConfigParams(pobj){
        let config_params = {};
        switch (pobj.item_type) {
            case "phone":
                config_params["mobile_input_length"]=pobj.mobile_input_length =="specific" ?1:2;
                config_params["verify_sms"]=pobj.verify_sms==true?1:0;
                break;
            case "singleBtn":
            case "multipleBtn":
            case "downOptions":
                config_params["options"] = pobj.options;
                break;
            case "singleText":
            case "multipleText":
                let length = []
                length.push(pobj.input_les);
                length.push(pobj.input_lar);
                config_params["input_length"] = length;
                break;
            case "area":
                config_params["is_show_county"] = pobj.is_show_county;
                break;
            default:
                break;
        }
        return config_params;
    }
}

module.exports = FormitemService;