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

class ForminfoService extends ServiceBase {
    constructor() {
        super("configmag", ServiceBase.getDaoName(ForminfoService));
        this.templateinfoDao = system.getObject("db.template.templateinfoDao");
        this.templatelinkDao = system.getObject("db.template.templatelinkDao");
        this.forminfoDao = system.getObject("db.configmag.forminfoDao");
        this.formitemDao = system.getObject("db.configmag.formitemDao");
    }

    /**
     * 根据company_id 查询
     * @param pobj
     * @returns {Promise<void>}
     */
    async findAllRecord(pobj) {
        let pageSize = Number(pobj.pageInfo.pageSize || 20);
        if (pageSize > 50) {
            pageSize = 50;
        }
        var pageIndex = Number(pobj.pageInfo.pageNo || 1);
        var from = pageIndex == 1 ? 0 : Number((pageIndex - 1) * pageSize);
        let sql = `select record.created_at,info.user_name name,info.notes,record.record_status_name from c_form_submit_record record left join  c_form_info info on info.id = record.form_id where info.deleted_at is NULL`;
        let countSql = `select count(*) count from c_form_submit_record record left join  c_form_info info on info.id = record.form_id where info.deleted_at is NULL`;
        if(pobj.record_status_name){
            sql += ` AND record.record_status_name = '${pobj.record_status_name}'`
            countSql += ` AND record.record_status_name = '${pobj.record_status_name}'`
        }
        sql += ` order by info.id desc LIMIT ${pageSize} OFFSET ${from}`;
        countSql += ` order by info.id desc LIMIT ${pageSize} OFFSET ${from}`;
        let result = await this.customQuery(sql);
        let countResult = await this.customQuery(countSql);
        let resData ={
            results:{
                count:countResult[0].count,
                rows:result
            }
        }
        return system.getResult(resData);
    }
    /**
     * 提交表单记录
     * @param {*} pobj 
     */
    async submitFormRecord(pobj){
        var ab = pobj.actionBody;
        var xctx = pobj.xctx;
        if(!ab){
          return system.getResultFail(-100,"参数错误");
        }
        if(!ab.link_code){
          return system.getResultFail(-101,"模板链接编码不能为空");
        }
        if(!ab.form_id){
          return system.getResultFail(-102,"表单id不能为空");
        }
        //获取模板链接信息
        var linkInfo = await this.templatelinkDao.model.findOne({
          where:{code:ab.link_code},raw:true
        });
        if(!linkInfo || !linkInfo.id){
            return system.getResultFail(-300,"未知模板链接")
        }
        //获取表单信息
        var forminfo = await this.forminfoDao.model.findOne({
            where:{id:ab.form_id},raw:true
        });
        if(!forminfo || !forminfo.id){
            return system.getResultFail(-400,"未知表单")
        }
        //获取表单项
        var formitems = await this.formitemDao.model.findAll({
            where:{form_id:ab.form_id},raw:true
        });
        //校验封装参数
        var res = await this.checkAndPackageFormItems(formitems,ab);
        if(res && res.status && res.status<0){
            return res;
        }
        var params = res;
        var addObj={
            template_id:linkInfo.template_id,templatelink_id:linkInfo.id,
            form_id:forminfo.id,record_status:1,templatelink_snapshot:linkInfo,
            form_snapshot:{forminfo:forminfo,formitems:formitems},
            record_content:params
        }
        await this.dao.create(addObj);//创建记录
        return system.getResultSuccess();
    }
    /**
     * 参数校验
     * @param {*} formitems 表单项
     * @param {*} ab 表单提交数据
     */
    async checkAndPackageFormItems(formitems,ab){
        var params = {};
        for(var i=0;i<formitems.length;i++){
            var item = formitems[i];
            var itemConfig = item.config_params;
            if(item && item.code && item.is_enabled){//显示状态的表单项
                var value = ab[item.code];
                if(item.is_required===1){//必填
                    if(!ab[item.code]){
                        return system.getResultFail(-100,item.name+"参数不能为空");
                    }
                }
                if(itemConfig.mobile_input_length===1){//手机号 1:限定11位 2：限定7-11位
                    if(value && value.length!=11){
                        return system.getResultFail(-101,item.name+"参数限定11位");
                    }
                }
                if(itemConfig.mobile_input_length===2){//手机号 1:限定11位 2：限定7-11位
                    if(value && (value.length<7 || value.length>11)){
                        return system.getResultFail(-102,item.name+"参数限定7-11位");
                    }
                }
                if(itemConfig.input_length && itemConfig.input_length.length==2){//输入长度区间
                    if(value && (value.length<itemConfig.input_length[0] || value.length>itemConfig.input_length[1])){
                        return system.getResultFail(-103,item.name+"参数输入长度为"+itemConfig.input_length[0]+"-"+itemConfig.input_length[1]+"位");
                    }
                }
                params[item.code] = value;
            }
        }
        return params;
    }
}

module.exports = ForminfoService;