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.formitemDao = system.getObject("db.configmag.formitemDao");
        this.templateDao = system.getObject("db.template.templateinfoDao");
    }

    /**
     * 创建表单
     * @param pobj
     * @returns {Promise<void>}
     */
    async createForm(pobj){
        if(!pobj.name){
            return system.getResultFail(-1,'表单名称不能为空');
        }
        if(!pobj.form_describe){
            return system.getResultFail(-1,'表单描述不能为空');
        }
        var checkFormInfo = await this.dao.model.findOne({
            where:{name:pobj.name},raw:true
        });
        if(checkFormInfo && checkFormInfo.id){
            return system.getResultFail(-300,'表单名称重复，操作失败');
        }
        let code = await this.getBusUid("fm")
        pobj.code = code;
        pobj.user_id = pobj.userid;
        pobj.user_name = pobj.username;
        pobj.form_items = '单行文本,手机号'
        let result = await this.create(pobj);
        if(!result){
            return system.getResultFail(-1,'创建表单失败');
        }
        //默认联系方式 表单项
        let phoneItem = {
            form_id:result.id,
            name:"联系方式",
            code:"contact_mobile",
            config_params:{
                verify_sms:0,
                mobile_input_length:2
            },
            item_type:'phone',
            item_type_name:'手机号',
            is_enabled:1,
            is_required:1,
            sequence:2
        }
        let itRt  = await this.formitemDao.create(phoneItem);
        if(!itRt){
            return system.getResultFail(-1,'创建联系人表单项失败');
        }
        //默认联系人 表单项
        let nameItem = {
            form_id:result.id,
            name:"联系人",
            code:"contact_name",
            config_params:{"input_length": ["2", "40"]},
            item_type:'singleText',
            item_type_name:'单行文本',
            is_enabled:1,
            is_required:1,
            sequence:1
        }
        let itRt2 = await this.formitemDao.create(nameItem);
        this.updateForm(result)
        if(!itRt2){
            return system.getResultFail(-1,'创建联系方式表单失败');
        }
        return system.getResultSuccess();
    }

    /**
     * 表单删除
     * @param pobj
     * @returns {Promise<void>}
     */
    async deleteForm(pobj){
        let template = await this.templateDao.findOne({form_id:pobj.id},[]);
        if(template && template.is_enabled == 1){
            return system.getResultFail(-1,'表单已投入使用，不能删除')
        }
        let del = await this.delete(pobj);
        return system.getResult(del);
    }


    /**
     * 修改方法
     * @param pobj
     * @returns {Promise<void>}
     */
    async updateForm(pobj) {
        let upData = {
            name:pobj.name,
            form_describe: pobj.form_describe
        }
        var checkFormInfo = await this.dao.model.findOne({
            where:{name:pobj.name},raw:true
        });
        if(checkFormInfo && checkFormInfo.id){
            return system.getResultFail(-300,'表单名称重复，操作失败');
        }
        let template = await this.templateDao.findOne({form_id:pobj.id},[]);
        if(template && template.is_enabled == 1){
            return system.getResultFail(-1,'表单已投入使用，不能修改')
        }
        //获取相关表单项
        let itemData = await this.formitemDao.findAll({form_id:pobj.id},[]);
        let form_items = '';
        if(itemData.length>0){
            itemData.forEach(v=>{
                form_items += v.item_type_name + ",";
            })
            form_items = form_items.substring(0,form_items.length-1)
        }
        upData.form_items = form_items;
        //组装form表单
        let form = await this.packageForm(itemData);
        upData.form_table = form;
        let result = await this.updateByWhere(upData,{id:pobj.id})
        return system.getResult(result);
    }

    /**
     * 表单复制
     * @param pobj
     * @returns {Promise<void>}
     */
    async copy(pobj){
        let items = await this.formitemDao.findAll({form_id:pobj.id},[]);
        delete pobj.id;
        delete pobj.created_at;
        let code = await this.getBusUid('fm');
        pobj.code = code;
        pobj.name += "_副本";
        let saveRt = await this.create(pobj);
        items.forEach(async (item) =>{
            delete item.dataValues.id;
            delete item.dataValues.created_at;
            let iCode = await this.getBusUid('it');
            item.code = iCode;
            item.form_id = saveRt.id
            this.formitemDao.create(item.dataValues);
        })
        return system.getResult(saveRt);
    }

    //组装form
    async packageForm(items) {
        let data = {
            "phone": "mobile",
            "singleBtn": "radiogroup",
            "multipleBtn": "checkgroup",
            "downOptions": "dic-select",
            "singleText": "input",
            "multipleText": "textarea",
            "area": "tree-sel"//忽略 4
        }

        let form = {};
        let ctls = [];
        if(items.length>0){
            items.forEach(item=>{
                if(item.is_enabled == 1){
                    let ctl = {}
                    ctl['type'] = data[item.item_type];
                    ctl['label'] = item.name;
                    ctl['prop'] = item.code;
                    let rules = [];
                    //单选框 多选框 下拉选项 添加options属性 结构为  a,b,c
                    if(['singleBtn','multipleBtn','downOptions'].includes(item.item_type) && item.config_params){
                        ctl['options'] = item.config_params.options
                        rules = [{ "required": true, "message": '  ', "trigger": 'change' }];
                    }else{
                        rules = [{ "required": true, "message": '  ', "trigger": 'blur' }];
                    }
                    //单行文本 多行文本 增加校验项 有最小和最大值
                    if(['singleText','multipleText'].includes(item.item_type) && item.config_params){
                        let rule =  { "validator": "validatex", "trigger": "blur","minchars":item.config_params.input_length[0],"maxchars":item.config_params.input_length[1]}
                        rules.push(rule)
                    }
                    //手机号选项 增加校验项 有最大最小值
                    if('phone'== item.item_type){
                        let param = item.config_params;
                        let minchars,maxchars = 11;
                        if(param.mobile_input_length == 2){
                            minchars = 7;
                            maxchars = 11;
                        }
                        let rule = { "validator": "validatex", "trigger": "blur","minchars":minchars,"maxchars":maxchars};
                        rule["verifysms"] = param.verify_sms || 0;
                        rules.push(rule);
                    }
                    //省市选项 增加 ignorelevel属性 忽略区县为4，不忽略为5
                    if('area' == item.item_type){
                        let param = item.config_params;
                        if(param.is_show_county == 0){
                            ctl['ignorelevel'] = 4;
                        }else{
                            ctl['ignorelevel'] = 5;
                        }
                        ctl['archName']= 'regionJSON';
                        ctl['rootName'] = '全国区域';
                    }
                    if(item.is_required ==1){
                        ctl['rules'] = rules;
                    }
                    ctls.push(ctl);
                }
            })
            //组装form 格式表单
            form = {
                name: "xxx",
                main: [
                    {
                        "title": "表单信息",
                        cols:1,
                        ctls: ctls
                    }
                ]
            }
        }
        return form;
    }

    async getFormList (pobj) {
        let res = await this.dao.findAndCountAll(pobj);
        return system.getResult(res);
    }

    async copyFormInfo (pobj) {
        let form = await this.findById(pobj.id);
        if (!form) {
            return system.getResultFail(-1, "表单不存在");
        }
        // console.log(form.dataValues);
        let formCode = await this.getBusUid("fm");
        let formCopyObj = {
            code: formCode,
            name: form.name + "_副本",
            form_items: form.form_items,
            form_describe: form.form_describe,
            notes: form.notes,
            version: form.version,
            // created_at: form.created_at,
            // updated_at: form.updated_at,
            uder_id: form.user_id,
            user_name: form.user_name,
            company_id: form.company_id,
            record_num: form.record_num,
            form_table: form.form_table
        };
        // console.log(formCopyObj);
       // 创建新的表单信息
       let formCopy = await this.create(formCopyObj);
       let formCopyId = formCopy.id;

       // 获取表单相关的表单项，复制并与新的表单关联
       let formItems = await this.formitemDao.findAll({form_id: pobj.id});
       if (formItems.length > 0) {
           formItems.forEach(async (item) => {
               let itemCode = await this.getBusUid("it");
               let itemNew = {
                   form_id: formCopyId,
                   code: itemCode,
                   name: item.name,
                   item_type: item.item_type,
                   item_type_name: item.item_type_name,
                   config_params: item.config_params,
                   id_enabled: item.is_enabled,
                   is_required: item.is_required,
                   sequence: item.sequence,
                   notes: item.notes,
                   version: item.version,
                //    created_at: item.created_at,
                //    updated_at: item.updated_at
               };
               await this.formitemDao.create(itemNew);
           });
       }
       return system.getResultSuccess(formCopy);
    }

    async deleteFormInfo (pobj) {
        let template = await this.templateDao.findOne({"form_id": pobj.id});
        if (template && template.is_enabled === 1) {
            return system.getResultFail(-1, "表单使用中，无法删除");
        }
        let form = await this.delete({"id": pobj.id});
        // let formItems = await this.formitemDao.findAll({"form_id": pobj.id});
        // formItems.forEach(async (item) => await item.destory());
        await this.formitemDao.bulkDeleteByWhere({where: {"form_id": pobj.id}});

        return system.getResultSuccess(form);
    }
}

module.exports = ForminfoService;