const express = require("express");
const router = express.Router();
const { instanceNumberBuilder } = require("../manager/instance_number_rules");
const objectql = require('@steedos/objectql');
const _ = require('lodash');
const UUFlowManager = require('../manager/uuflow_manager');
const { requireAuthentication } = require("@steedos/auth");

// 获取用户当前的 approve
const getUserApprove = ({ instance, userId }) => {
    const currentTrace = _.find(instance.traces, (trace) => {
        return trace.is_finished != true;
    });
    let currentApprove = null;
    if (currentTrace) {
        currentApprove = _.find(currentTrace.approves, (approve) => {
            return approve.is_finished != true && approve.handler == userId;
        });
    }

    //传阅的approve返回最新一条
    if (!currentApprove || currentApprove.type == "cc") {
        // 当前是传阅
        _.each(instance.traces, function (t) {
            _.each(t.approves, function (a) {
                if (a.type == "cc" && a.handler == userId && a.is_finished == false) {
                    currentApprove = a;
                }
            });
        });
    }

    if (!currentApprove) return;

    if (currentApprove._id) {
        currentApprove.id = currentApprove._id;
    }
    return currentApprove;
};

// 获取可编辑的自动编号字段
const getEditableAutoNumberFields = async (step, formId, formVersion) => {
    const permissions = step.permissions || {};
    const form = await UUFlowManager.getForm(formId);
    const formV = await UUFlowManager.getFormVersion(form, formVersion);
    
    const autoNumberFields = [];
    
    // 检查字段是否是自动编号字段（通过 formula 判断）
    const isAutoNumberField = (field) => {
        return field.default_value && typeof field.default_value === 'string' && field.default_value.trim().startsWith('auto_number(');
    };
    
    // 从 formula 中提取自动编号规则名称
    const extractAutoNumberName = (formula) => {
        // 匹配 auto_number("xxx") 或 auto_number('xxx') 或 auto_number(xxx)
        const match = formula.match(/auto_number\s*\(\s*['"]?([^'"()]+?)['"]?\s*\)/);
        return match ? match[1].trim() : null;
    };
    for (const field of formV.fields || []) {
        
        if (field.type === "section") {
            // 处理 section 中的字段
            for (const sectionField of field.fields || []) {
                if (isAutoNumberField(sectionField) && permissions[sectionField.code] === "editable") {
                    const autoNumberName = extractAutoNumberName(sectionField.default_value);
                    if (autoNumberName) {
                        autoNumberFields.push({
                            code: sectionField.code,
                            auto_number_name: autoNumberName
                        });
                    }
                }
            }
        } else {
            // 处理普通字段
            if (isAutoNumberField(field) && permissions[field.code] === "editable") {
                const autoNumberName = extractAutoNumberName(field.default_value);
                if (autoNumberName) {
                    autoNumberFields.push({
                        code: field.code,
                        auto_number_name: autoNumberName
                    });
                }
            }
        }
    }
    
    return autoNumberFields;
};

router.post('/api/workflow/v2/auto_number', requireAuthentication, async function (req, res) {
    try {
        const userSession = req.user;
        const userId = userSession.userId;
        const { instanceId } = req.body;
        
        if (!instanceId) {
            return res.status(200).send({
                error: '缺少必填参数: instanceId'
            });
        }

        // 获取 instance 信息
        const instancesCollection = await objectql.getObject('instances');
        const instance = await instancesCollection.findOne(instanceId);
        
        if (!instance) {
            return res.status(200).send({
                error: '未找到该实例'
            });
        }

        // 获取当前用户的 approve
        const currentApprove = getUserApprove({ instance, userId });
        
        if (!currentApprove) {
            return res.status(200).send({
                error: '未找到当前用户的审批节点'
            });
        }

        // 如果是传阅类型，则不处理自动编号
        if (currentApprove.type === 'cc') {
            return res.status(200).send({
                success: true,
                message: '传阅节点不处理自动编号'
            });
        }

        // 查找当前 trace 和 approve 的位置
        let traceIndex = -1;
        let approveIndex = -1;
        
        for (let i = 0; i < instance.traces.length; i++) {
            const trace = instance.traces[i];
            if (trace.approves && trace.approves.length > 0) {
                const index = trace.approves.findIndex(app => app._id === currentApprove._id);
                if (index !== -1) {
                    traceIndex = i;
                    approveIndex = index;
                    break;
                }
            }
        }

        if (traceIndex === -1 || approveIndex === -1) {
            return res.status(200).send({
                error: '未找到对应的 trace 和 approve'
            });
        }

        const currentTrace = instance.traces[traceIndex];
        
        // 获取当前 step
        const flowsCollection = await objectql.getObject('flows');
        const flow = await flowsCollection.findOne(instance.flow);
        
        if (!flow) {
            return res.status(200).send({
                error: '未找到对应的流程'
            });
        }

        let step = null;
        if (flow.current && flow.current.steps) {
            step = flow.current.steps.find(s => s._id === currentTrace.step);
        }
        
        if (!step && flow.historys) {
            for (const h of flow.historys) {
                step = h.steps.find(s => s._id === currentTrace.step);
                if (step) break;
            }
        }

        if (!step) {
            return res.status(200).send({
                error: '未找到对应的步骤'
            });
        }

        // 获取可编辑的自动编号字段
        const autoNumberFields = await getEditableAutoNumberFields(step, instance.form, instance.form_version);
        
        if (autoNumberFields.length === 0) {
            return res.status(200).send({
                success: true,
                message: '当前步骤没有可编辑的自动编号字段'
            });
        }

        // 为每个自动编号字段生成编号
        const result = {};
        const updateObj = {};
        
        for (const field of autoNumberFields) {
            // 检查字段是否已有值
            if (currentApprove.values && currentApprove.values[field.code]) {
                result[field.code] = currentApprove.values[field.code];
                continue;
            }
            
            // 生成自动编号
            const autoNumber = await instanceNumberBuilder(instance.space, field.auto_number_name);
            
            if (autoNumber && autoNumber._error) {
                throw autoNumber._error;
            }
            
            result[field.code] = autoNumber;
            updateObj[`traces.${traceIndex}.approves.${approveIndex}.values.${field.code}`] = autoNumber;
        }

        // 更新 approve 的 values
        if (Object.keys(updateObj).length > 0) {
            await instancesCollection.update(instanceId, updateObj);
        }

        res.status(200).send({
            success: true,
            fields: result
        });
    } catch (error) {
        console.error(error);
        res.status(200).send({
            error: error.message
        });
    }
});


exports.default = router;