import {listFormOption, listPrintTemp, listStartPerm} from "/@/api/jsonflow/form-option";
import {DIC_PROP} from "/@/flow/support/dict-prop";
import {useMessage} from "/@/hooks/message";
import {validateNull} from "/@/utils/validate";
import {PROP_CONST} from "/@/flow/support/prop-const";
import {deepClone} from "/@/utils/other";
import {validateRunFlow} from "/@/flow";

// 处理表单权限
export async function handleFormStartPerm(hiddenFields, disabledFields, formInfo, defFlowId, flowKey, formType) {
    if (!formType) formType = DIC_PROP.FORM_TYPE[1].value
    let resp = await listStartPerm({
        type: DIC_PROP.FORM_DATA_TYPE[1].value, formType: formType,
        defFlowId: defFlowId, flowKey: flowKey
    }).catch(() => {
        useMessage().error("获取表单字段权限失败");
    })
    let data = resp?.data;
    // 表单默认权限及查看时查询打印模板
    if (validateNull(data.columns)) return {elTab: data.tabsOption};
    let widgetList = formInfo ? formInfo.widgetList : null
    // 全部只读部分可编辑
    let callback = () => { handleFormPerms(hiddenFields, disabledFields, widgetList, data.tabsOption, data.columns, data.defFlowId, data.flowNodeId) }
    initIsFormEdit(data.tabsOption, data.columns, data.defFlowId, data.flowNodeId)
    return {elTab: data.tabsOption, callback, widgetList};
}

export async function handleDesignFormPerm(props, formInfo, elTab, formType, formId) {
    let defFlowId = props.currJob.defFlowId;
    let flowInstId = props.currJob.flowInstId;
    let flowNodeId = props.currJob.flowNodeId;
    let resp = await listFormOption({
        type: DIC_PROP.FORM_DATA_TYPE[1].value, formType: formType, formId: formId,
        defFlowId: defFlowId, flowInstId: flowInstId, flowNodeId: flowNodeId, isOnlyCurr: '1'
    }).catch(() => {
        useMessage().error("获取表单字段权限失败");
    })
    if (validateNull(resp.data)) return {};
    // 全部只读部分可编辑
    let callback = () => { handleFormPerms(null, null, formInfo.widgetList, elTab, resp.data, defFlowId, flowNodeId) }
    initIsFormEdit(elTab, resp.data, defFlowId, flowNodeId)
    return {columns: resp.data, callback, widgetList: formInfo.widgetList};
}

export async function handleCustomFormPerm(props, hiddenFields, disabledFields, elTab: Object) {
    let defFlowId = props.currJob.defFlowId;
    let flowInstId = props.currJob.flowInstId;
    let flowNodeId = props.currJob.flowNodeId;
    let resp = await listFormOption({
        type: DIC_PROP.FORM_DATA_TYPE[1].value, formType: DIC_PROP.FORM_TYPE[1].value, formId: elTab.id,
        defFlowId: defFlowId, flowInstId: flowInstId, flowNodeId: flowNodeId, isOnlyCurr: '1'
    }).catch(() => {
        useMessage().error("获取表单字段权限失败");
    })
    if (validateNull(resp.data)) return {};
    // 全部只读部分可编辑
    let callback = () => { handleFormPerms(hiddenFields, disabledFields, null, elTab, resp.data, defFlowId, flowNodeId) }
    initIsFormEdit(elTab, resp.data, defFlowId, flowNodeId)
    return {columns: resp.data, callback};
}

// 查询配置信息
export async function handleFormPrint(form, formType, formId, isOnlyCurr) {
    await listPrintTemp({
        flowInstId: form.flowInstId,
        type: DIC_PROP.FORM_DATA_TYPE[2].value, formType: formType, formId: formId,
        isOnlyCurr: isOnlyCurr
    }).then(resp => {
        let res = resp.data;
        form.printInfo = res.printInfo
    }).catch(() => {
        useMessage().error("获取表单打印模板失败");
    })
}

// 构建字段权限列表
export function buildFieldPerms(formFieldPerms: any[], widgetList: any[], subForm?, isField?) {
    widgetList.forEach(f => {
        // 处理子表单元素、分组元素
        let isSubForm = f.type.indexOf(PROP_CONST.FORM_DESIGN.subForm) !== -1;
        if (isSubForm || f.type.indexOf(PROP_CONST.FORM_DESIGN.group) !== -1) {
            let widgetList = f.props.rule;
            if (validateNull(widgetList)) return;
            if (isSubForm) pushFormFieldPerms(formFieldPerms, f, null, isField)
            let subForm2 = isSubForm ? f.field : subForm
            buildFieldPerms(formFieldPerms, widgetList, subForm2, isField);
        }
        // 处理栅格元素、标签页元素、折叠面板元素
        else if (f.type.indexOf(PROP_CONST.FORM_DESIGN.fcRow) !== -1 || f.type.indexOf(PROP_CONST.FORM_DESIGN.elTabs) !== -1 || f.type.indexOf(PROP_CONST.FORM_DESIGN.elCollapse) !== -1) {
            let cols = f.children;
            if (validateNull(cols)) return;
            cols.forEach(col => {
                if (validateNull(col.children)) return;
                buildFieldPerms(formFieldPerms, col.children, subForm, isField);
            })
        }
        // 处理表格表单元素
        else if (f.type.indexOf(PROP_CONST.FORM_DESIGN.tableForm) !== -1) {
            let cols = f.props.columns;
            if (validateNull(cols)) return;
            pushFormFieldPerms(formFieldPerms, f, null, isField)
            cols.forEach(col => {
                if (validateNull(col.rule)) return;
                buildFieldPerms(formFieldPerms, col.rule, f.field, isField);
            })
        }
        // 处理表格布局元素、卡片元素
        else if (f.type.indexOf(PROP_CONST.FORM_DESIGN.fcTable) !== -1 || f.type.indexOf(PROP_CONST.FORM_DESIGN.elCard) !== -1) {
            let cols = f.children;
            if (validateNull(cols)) return;
            buildFieldPerms(formFieldPerms, cols, subForm, isField);
        }
        else {
            pushFormFieldPerms(formFieldPerms, f, subForm, isField)
        }
    })
}

function pushFormFieldPerms(formFieldPerms, f, subForm?, isField?){
    let label = f.title;
    /*if (f.type.indexOf(PROP_CONST.FORM_DESIGN.subForm) !== -1) {
        label = "(子表单)" + label
    }
    if (f.type.indexOf(PROP_CONST.FORM_DESIGN.tableForm) !== -1) {
        label = "(表单表格)" + label
    }*/
    // 排除无名称字段
    if (!label) return
    formFieldPerms.push({
        propId: f.name,
        prop: f.field,
        label: label,
        subForm: subForm,
        propType: f.type,
        __fc__: isField ? f.__fc__ : null
    })
}

export function handleFormFieldPerms(data, $message, form, prefix) {
    let isDesign = form.type !== DIC_PROP.FORM_TYPE[1].value;
    if (isDesign) {
        if (validateNull(form.formInfo)) {
            data.formFieldPerms = [];
            if ($message) $message.warning("当前选择的设计表单无字段信息，请先在《表单设计器》中设计")
            return true;
        } else {
            buildFormFieldPerms(data, form.formInfo, prefix)
            return true;
        }
    } else {
        let formFieldPerms = form.formFieldPerms;
        if (!validateNull(formFieldPerms)) {
            // 不影响表单设计信息
            data.formFieldPerms = deepClone(formFieldPerms)
            handleFieldProp(data.formFieldPerms, prefix)
            return true;
        }
        // 此处要查询接口
        return false;
    }
}

export function buildSysFieldsFormOption(data, props, $message) {
    let formFieldPerms = deepClone(PROP_CONST.SYS_FIELDS);
    handleFieldProp(formFieldPerms, null)
    data.allFieldPerms = [{label: '系统字段', options: formFieldPerms}]
    validateListFormOption(data, props, $message, () => {
        let options = {label: '表单字段', options: data.formFieldPerms}
        data.allFieldPerms.push(options)
    })
}

export async function validateListFormOption(data, props, $message?, callback?) {
    let form = props.currFlowForm ? props.currFlowForm : {}
    let formId = props.flowData.attrs.formId;
    if (validateNull(props.currFlowForm)) {
        if (!formId) {
            if ($message) $message.warning("流程属性【关联表单】为空，请点击左上角《流程属性》选择");
            return
        }
        form.type = DIC_PROP.FORM_TYPE[1].value
        form.id = formId
    } else {
        let isReturn = handleFormFieldPerms(data, $message, form, PROP_CONST.VAR_KEY_VAL.form);
        if (isReturn) {
            if (callback) callback()
            return
        }
    }
    // 判断流程实例独立配置
    let flowInstId = validateRunFlow(props);
    // 当系统表单没配置时查表数据
    await listFormOption({
        flowInstId: flowInstId, type: DIC_PROP.FORM_DATA_TYPE[0].value,
        formType: form.type, formId: form.id
    }).then(resp => {
        let res = resp.data;
        if (!validateNull(res)) {
            data.formFieldPerms = res
            handleFieldProp(data.formFieldPerms, PROP_CONST.VAR_KEY_VAL.form)
        } else {
            validateFormType(data, form, $message)
        }
        if (callback) callback()
    }).catch(() => {
        $message.error("获取系统表单字段权限失败");
    })
}

function validateFormType(data, form, $message) {
    // 判断系统表单
    if (form.type === DIC_PROP.FORM_TYPE[1].value) {
        data.formFieldPerms = [];
        if ($message) $message.warning("当前选择的系统表单无字段信息，请先在表单设计中录入")
        return;
    }
    buildFormFieldPerms(data, form.formInfo, PROP_CONST.VAR_KEY_VAL.form)
}

function buildFormFieldPerms(data, formInfo, prefix) {
    data.formFieldPerms = []
    buildFieldPerms(data.formFieldPerms, formInfo.widgetList);
    handleFieldProp(data.formFieldPerms, prefix)
}

export function handleFieldProp(formFieldPerms, prefix) {
    if (validateNull(formFieldPerms)) return
    formFieldPerms.forEach(each => {
        // 暂时未用each.prefix
        each.prop = (each.prefix ? each.prefix : prefix) + (each.subForm ? each.subForm + '.' + each.prop : each.prop)
    })
}

// 初始化
function initIsFormEdit(elTab, formPerms, defFlowId, flowNodeId) {
    if (validateNull(formPerms)) return;
    // 判断是否存在
    let formFieldPerms = formPerms.filter(f => f.defFlowId === defFlowId && f.flowNodeId === flowNodeId);
    if (validateNull(formFieldPerms)) return
    // 判断全部只读部分可编辑
    let find = formFieldPerms.find(f => f.permType === '1');
    if (find && elTab.isFormEdit === '0') {
        // 记录初始值
        elTab.defFormEdit = elTab.isFormEdit
        elTab.isFormEdit = '1'
    }
}

// 处理表单字段权限
function handleFormPerms(hiddenFields, disabledFields, columns, elTab, formPerms, defFlowId, flowNodeId) {
    if (validateNull(formPerms)) return;
    // 判断是否存在
    let formFieldPerms = formPerms.filter(f => f.defFlowId === defFlowId && f.flowNodeId === flowNodeId);
    if (validateNull(formFieldPerms)) return
    // 处理权限
    formFieldPerms.forEach(each => {
        if (validateNull(columns)) {
            extractedPermType(hiddenFields, disabledFields, elTab, each, null);
        } else {
            doFormFieldPerms(hiddenFields, disabledFields, columns, each, elTab);
        }
    })
}

function doFormFieldPerms(hiddenFields, disabledFields, columns, each, elTab) {
    let find = columns.find(f => each.propId ? f.name === each.propId : f.field === each.prop)
    if (find) {
        extractedPermType(hiddenFields, disabledFields, elTab, each, find);
        return
    }
    columns.forEach(f => {
        // 处理子表单元素、分组元素
        let isSubForm = f.type.indexOf(PROP_CONST.FORM_DESIGN.subForm) !== -1;
        if (isSubForm || f.type.indexOf(PROP_CONST.FORM_DESIGN.group) !== -1) {
            let widgetList = f.props.rule;
            if (validateNull(widgetList)) return;
            doFormFieldPerms(hiddenFields, disabledFields, widgetList, each, elTab)
        }
        // 处理栅格元素、标签页元素、折叠面板元素
        else if (f.type.indexOf(PROP_CONST.FORM_DESIGN.fcRow) !== -1 || f.type.indexOf(PROP_CONST.FORM_DESIGN.elTabs) !== -1 || f.type.indexOf(PROP_CONST.FORM_DESIGN.elCollapse) !== -1) {
            let cols = f.children;
            if (validateNull(cols)) return;
            cols.forEach(col => {
                if (validateNull(col.children)) return;
                doFormFieldPerms(hiddenFields, disabledFields, col.children, each, elTab)
            })
        }
        // 处理表格表单元素
        else if (f.type.indexOf(PROP_CONST.FORM_DESIGN.tableForm) !== -1) {
            let cols = f.props.columns;
            if (validateNull(cols)) return;
            cols.forEach(col => {
                if (validateNull(col.rule)) return;
                doFormFieldPerms(hiddenFields, disabledFields, col.rule, each, elTab)
            })
        }
        // 处理表格布局元素、卡片元素
        else if (f.type.indexOf(PROP_CONST.FORM_DESIGN.fcTable) !== -1 || f.type.indexOf(PROP_CONST.FORM_DESIGN.elCard) !== -1) {
            let cols = f.children;
            if (validateNull(cols)) return;
            doFormFieldPerms(hiddenFields, disabledFields, cols, each, elTab)
        }
    })
}

function extractedPermType(hiddenFields, disabledFields, elTab, each, find) {
    if (elTab.type === DIC_PROP.FORM_TYPE[1].value) {
        let propDef = each.subForm ? each.subForm + '.' + each.prop : each.prop;
        if (each.permType === '-1') {
            hiddenFields[propDef] = true
        } else if (each.permType === '1') {
            disabledFields[propDef] = false
        } else if (each.permType === '0') {
            disabledFields[propDef] = true
        }
    } else {
        if (each.permType === '-1') {
            find.hidden = true
        } else if (each.permType === '1') {
            if (!find.props) find.props = {}
            find.props.disabled = false
        } else if (each.permType === '0') {
            if (!find.props) find.props = {}
            find.props.disabled = true
        }
    }
}

export function disabledAllFormFields(columns, permType) {
    if (validateNull(columns)) return
    columns.forEach(f => {
        // 处理子表单元素、分组元素
        let isSubForm = f.type.indexOf(PROP_CONST.FORM_DESIGN.subForm) !== -1;
        if (isSubForm || f.type.indexOf(PROP_CONST.FORM_DESIGN.group) !== -1) {
            let widgetList = f.props.rule;
            if (validateNull(widgetList)) return;
            if (isSubForm) disabledFormField(f, permType)
            disabledAllFormFields(widgetList, permType)
        }
        // 处理栅格元素、标签页元素、折叠面板元素
        else if (f.type.indexOf(PROP_CONST.FORM_DESIGN.fcRow) !== -1 || f.type.indexOf(PROP_CONST.FORM_DESIGN.elTabs) !== -1 || f.type.indexOf(PROP_CONST.FORM_DESIGN.elCollapse) !== -1) {
            let cols = f.children;
            if (validateNull(cols)) return;
            cols.forEach(col => {
                if (validateNull(col.children)) return;
                disabledAllFormFields(col.children, permType)
            })
        }
        // 处理表格表单元素
        else if (f.type.indexOf(PROP_CONST.FORM_DESIGN.tableForm) !== -1) {
            let cols = f.props.columns;
            if (validateNull(cols)) return;
            disabledFormField(f, permType)
            cols.forEach(col => {
                if (validateNull(col.rule)) return;
                disabledAllFormFields(col.rule, permType)
            })
        }
        // 处理表格布局元素、卡片元素
        else if (f.type.indexOf(PROP_CONST.FORM_DESIGN.fcTable) !== -1 || f.type.indexOf(PROP_CONST.FORM_DESIGN.elCard) !== -1) {
            let cols = f.children;
            if (validateNull(cols)) return;
            disabledAllFormFields(cols, permType)
        } else {
            disabledFormField(f, permType)
        }
    })
}

function disabledFormField(find, permType) {
    if (permType === '-1') {
        find.hidden = true
    } else if (permType === '1') {
        if (!find.props) find.props = {}
        find.props.disabled = false
    } else if (permType === '0') {
        if (!find.props) find.props = {}
        find.props.disabled = true
    }
}
