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

class FormsubmitrecordService extends ServiceBase {
    constructor() {
        super("configmag", ServiceBase.getDaoName(FormsubmitrecordService));
        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");
        this.fqUtilsSve = system.getObject("service.common.fqUtilsSve");
    }

    /**
     * 提交表单记录
     * @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不能为空");
        }
        if(!ab.ali_code){
          return system.getResultFail(-103,"校验编码不能为空");
        }
        //获取模板链接信息
        var linkInfo = await this.templatelinkDao.model.findOne({
          where:{code:ab.link_code},raw:true
        });
        if(!linkInfo || !linkInfo.id){
            return system.getResultFail(-300,"未知模板链接");
        }
        if(!linkInfo.template_id){
            return system.getResultFail(-301,"链接模板信息错误")
        }
        var templateinfo = await this.templateinfoDao.model.findOne({
            where:{id:linkInfo.template_id},raw:true,
            attributes:["id","business_code"]
        });
        if(!templateinfo || !templateinfo.id){
            return system.getResultFail(-500,"未知模板信息");
        }
        //获取表单信息
        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,order:[["sequence","asc"]]
        });
        //校验封装参数
        var res = await this.checkAndPackageFormItems(formitems,ab);
        if(res && res.status && res.status<0){
            return res;
        }
        var params = res;
        var addObj={
            ali_code:ab.ali_code,
            template_id:linkInfo.template_id,templatelink_id:linkInfo.id,
            form_id:forminfo.id,record_status:1,templatelink_snapshot:linkInfo,
            form_snapshot:forminfo,
            record_content:params,business_code:templateinfo.business_code,
            push_status:0
        }
        // if(ab.push_status==1){
        //     addObj.push_status=1;
        // }
        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] || ab[item.code].length<1){
                        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;
    }

    //将需求信息推送至蜂擎
    async pushFormInfo2Fq(){
        var limit = 100;
        var formRecords = await this.dao.model.findAll({
            attributes:["id","templatelink_snapshot","form_snapshot","ali_code","record_content"],
            where:{
                push_status:0,
                ali_code:{[this.db.Op.ne]:null},form_snapshot:{[this.db.Op.ne]:null},
                ali_code:{[this.db.Op.ne]:''},templatelink_snapshot:{[this.db.Op.ne]:null},
                record_content:{[this.db.Op.ne]:null}
            },
            limit:limit,
            order:[["id","asc"]],
            raw:true
        });
        var recordList = await this.packageRecordList(formRecords);
        for(var a=0;a<recordList.length;a++){
            var pushRes = await this.fqUtilsSve.pushNeedInfo2Fq(recordList[a],recordList[a].code);
            console.log(pushRes,"pushRes############################3");
            if(pushRes && pushRes.data && pushRes.data=="success"){//推送成功
                await this.dao.update({id:recordList[a].id,push_status:1});
            }else{
                await this.dao.update({id:recordList[a].id,push_status:2});
            }
        }
    }

    //封装表单记录信息
    async packageRecordList(formRecords){
        var recordList=[];
        for(var i=0;i<formRecords.length;i++){
            var fr = formRecords[i];
            var rc = fr.record_content;
            var linkinfo = fr.templatelink_snapshot;
            var forminfo = fr.form_snapshot;
            if(forminfo && forminfo.form_table && forminfo.form_table.main && forminfo.form_table.main[0] && forminfo.form_table.main[0].ctls ){
                var ctls = forminfo.form_table.main[0].ctls;
                var pushInfo = {
                    id:fr.id,
                    customer_name:rc.contact_name,customer_phone:rc.contact_mobile,source:"marketplat",
                    source_type:linkinfo.name || "未知",code:fr.ali_code
                };
                var advisory_content="";
                for(var j=0;j<ctls.length;j++){
                    var ctl = ctls[j];
                    if(ctl.label && ctl.prop && rc[ctl.prop]){
                        advisory_content = advisory_content+ctl.label+":"+rc[ctl.prop]+";"
                    }
                }
                pushInfo["advisory_content"] = advisory_content || "未知"; 
                recordList.push(pushInfo);
            }

        }
        return recordList;
    }
}

module.exports = FormsubmitrecordService;