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

class FormitemService extends ServiceBase {
    constructor() {
        super("configmag", ServiceBase.getDaoName(FormitemService));
        this.forminfoSve = system.getObject("service.configmag.forminfoSve");
    }


    /**
     * 创建表单项
     * @param pobj
     * @returns {Promise<void>}
     */
    async createItem(pobj) {
        let type_name = await this.getTypeName(pobj.item_type);
        let code = await this.getBusUid('it');
        pobj.item_type_name = type_name;
        pobj.is_enabled = pobj.is_enabled ? 1:0;
        pobj.is_required = pobj.is_required ? 1:0;
        pobj.code = code;
        console.log(pobj)
        //获取表单的表单项
        let form = await this.forminfoSve.findOne({id:pobj.form_id},['form_items']);
        console.log(form)
        if(!form){
            return system.getResult(null,'获取订单信息失败');
        }
        let form_items = form.form_items ? form.form_items + "、" + type_name : type_name;
        //修改表单项字段
        this.forminfoSve.updateByWhere({form_items:form_items},{id:pobj.form_id});
        //保存表单项
        let result = await this.create(pobj);
        return system.getResult(result)
    }

    /**
     * 表单项删除
     * @param pobj
     * @returns {Promise<void>}
     */
    async deleteItem(pobj){
        let item = await this.findOne({id:pobj.id},['form_id','item_type_name']);
        if(!item){
            return system.getResult(null,'获取表单项失败');
        }
        let form = await this.forminfoSve.findOne({id:item.form_id},['form_items']);
        if(!form){
            return system.getResult(null,'获取表单失败');
        }
        let form_items = form.form_items.replace('、'+item.item_type_name,'');
        this.forminfoSve.updateByWhere({form_items:form_items},{id:item.form_id});
        let result = await this.delete(pobj);
        return system.getResult(result);
    }

    /**
     *
     * @param pobj
     * @returns {Promise<void>}
     */
    async updateForm(pobj) {

        return null;
    }

    //根据类型获取类型名称
    async getTypeName(type) {
        let data = {
            "phone": "手机号",
            "singleBtn": "单选按钮",
            "multipleBtn": "多选按钮",
            "downOptions": "下拉选项",
            "singleText": "单行文本",
            "multipleText": "多行文本",
            "dateTime": "日期",
            "area": "省市"
        }
        return data[type];
    }

}

module.exports = FormitemService;