shr.defineClass("shr.ats.Econtarct", shr.empContract.EmpContractCompsitQueryList, {
    protocolData: {},
    signerCount: 1,
    contractName: "",
    selectedRowsData: {},
    initalizeDOM: function () {
        shr.ats.Econtarct.superClass.initalizeDOM.call(this);
        this.changeEntrys();
    },
    sendSignAction: function () {
        $('#field').shrPromptBox("setFilter", "eSignFile.state = 1");
        $("#field").shrPromptBox("open");
    },
    changeEntrys: function () {
        var _this = this;

        // 绑定签署方类型切换事件（使用事件委托）
        $(document).on('change', '.type-select', function () {
            _this.changeSignerType(this);
        });

        // 绑定签署顺序验证事件（使用事件委托）
        $(document).on('input', '.order-input', function () {
            _this.validateOrder(this);
        });

        let lastCheckedRadio = null;

        $(document).on('click', '[name="signer-radio-orgname"]', function (a, e) {
            const $this = $(this);
            // 判断当前点击的元素是否是上一次选中的元素
            if ($this[0] === lastCheckedRadio) {
                // 取消选中
                $this.prop('checked', false);
                lastCheckedRadio = null; // 清空记录
            } else {
                // 原生已自动选中当前元素，只需更新记录（同组其他项已被原生取消）
                lastCheckedRadio = $this[0];
            }
            if ($('[name="signer-radio-orgname"').size() > 1) {
                $('[name="signer-radio-orgname"').prop('checked', false)
                lastCheckedRadio = null;
                shr.showWarning({
                    'message': "多个公司签署不允许使用电子签"
                });
            }
        });


        $('#field').shrPromptBox('option', {
            afterOnSelectRowHandler: function (a, b) {
                var l = $("#grid").jqGrid("getSelectedRowsData");
                if (l.length !== 1) {
                    shr.showWarning({
                        'message': "请选择一条元数据！！注意：只能选择一条数据！"
                    });
                    return
                }
                var number = b.value.number;
                _this.contractName = b.value.name;
                if (number) {
                    _this.selectedRowsData = $("#grid").jqGrid("getSelectedRowsData")[0];
                    var id = _this.selectedRowsData ? _this.selectedRowsData.id : '';
                    shr.callHandler({
                        action: "getTableData",
                        param: { "number": number, "id": id },
                        type: "POST",
                        success: function (res) {
                            _this.protocolData = _this.sortFieldsBySeq(res.data);
                            var eSignTemplateId;
                            for (var key in _this.protocolData) {
                                _this.protocolData[key];
                                if (_this.protocolData[key]) {
                                    eSignTemplateId = _this.protocolData[key].eSignTemplateNum
                                    break;
                                }

                            }
                            _this.renderAllTablesByColumns();
                            _this.resetSigners(eSignTemplateId);
                            $('#popup-overlay').css('display', 'flex');
                        }
                    });
                } else {
                    shr.showWarning({
                        'message': "未获取到e签宝映射编码！！！"
                    });
                    return
                }
            }
        });

        // 弹窗控制
        $('#open-popup').click(function () {
            $('#popup-overlay').css('display', 'flex');
        });

        $('#close-popup').click(function () {
            $('#popup-overlay').hide();
        });

        // $('#popup-overlay').click(function (e) {
        //     if (e.target === this) {
        //         $(this).hide();
        //     }
        // });

        $('#addSigner').click(function () {
            _this.signerCount++;

            // 创建新签署方卡片
            var newSigner = '<div class="signer-card" data-id="' + _this.signerCount + '">' +
                '<div class="card-header">' +
                '<div class="card-info">' +
                '<select class="type-select type-personal" id="signer-' + _this.signerCount + '-type" name="signer-' + _this.signerCount + '-type" disabled>' +
                '<option value="personal" >个人</option>' +
                '<option value="company">企业</option>' +
                '<option value="copy" selected>抄送</option>' +
                '</select>' +
                '<span class="signer-name" id="signername_index' + _this.signerCount + '" ">签署方' + _this.signerCount + '</span>' +
                '<span class="signer-role">签署</span>' +
                '<input type="number" min="1" max="255" value="' + _this.signerCount + '" class="order-input" id="signer-' + _this.signerCount + '-order" name="signer-' + _this.signerCount + '-order">' +
                '</div>' +
                '<div class="card-actions">' +
                '<span class="action-link delete-signer"><span class="icon"></span>删除</span>' +
                '</div>' +
                '</div>' +
                '<div class="form-grid signer-fields">' +
                '<div class="form-group">' +
                '<input type="text" placeholder="真实姓名" class="input-field" id="signer-' + _this.signerCount + '-name" name="signer-' + _this.signerCount + '-name">' +
                '<span class="input-marker" id="name-tip-' + _this.signerCount + '">ⓘ</span>' +
                '<input type="hidden" id="signer-' + _this.signerCount + '-person-f7" name="signer-' + _this.signerCount + '-person-f7">' +
                '</div>' +
                '<div class="form-group">' +
                '<input type="text" placeholder="请输入手机号/邮箱" class="input-field" id="signer-' + _this.signerCount + '-account" name="signer-' + _this.signerCount + '-account">' +
                '</div>' +
                '</div>' +
                '</div>';

            // 添加到容器
            $('#signersContainer').append(newSigner);
            // 初始化F7选择器
            _this.initPersonF7(_this.signerCount);
            $('#signer-' + _this.signerCount + '-type').val('copy').trigger('change');

        });

        // 删除签署方
        $(document).on('click', '.delete-signer', function () {
            var card = $(this).closest('.signer-card');
            card.addClass('fade-out');

            setTimeout(function () {
                card.remove();
                // 更新序号
                _this.updateSignerNumbers();
            }, 300);
        });


        $('#getData').click(function () {
            var data = _this.getSignerData();
            console.log(data);
        });


        // 确认按钮事件
        $('#global-confirm').click(function () {
            $.block.show({
                text: '正在发送合同，请稍等...'
            });
            var data = _this.collectAllTableData();
            var data1 = _this.getSignerData();
            var signFlowTitle = $("#popup_title").attr("value");
            var sourceId = _this.selectedRowsData ? _this.selectedRowsData.id : '';
            var personId = _this.selectedRowsData['employee.id'];
            var d = {};
            d.signInfo = data1;
            d.templateInfo = data;
            d.signFlowTitle = signFlowTitle;
            d.sourceId = "劳动合同" + "_" + sourceId;
            d.personId = personId
            console.log(d);
            var param = {}
            param.data = d;
            //param.mack="preview";
            // 调用服务获取字段数据
            window.setTimeout(function () {
                shr.callService({
                    serviceName: 'create_by_fileOSF',
                    param: param,
                    success: function (data) {
                        console.log("========调用合同返回参数=========")
                        console.log(data)
                        if (data.code === 0) {
                            $('#popup-overlay').hide();
                            shr.showInfo({
                                'message': "发送成功！！！"
                            });
                        } else {
                            shr.showError({
                                'message': data.message
                            });
                        }
                        $.block.hide();
                    },
                    error: function (e) {
                        shr.showError({
                            'message': e
                        });
                        $.block.hide();
                    }
                });
            }, 300)
        });
    },
    /**
 * 处理字段排序：按seq升序排列（从小到大）
 * @param {Object} data - 原始文档数据
 * @returns {Object} 排序后的文档数据
 */
    sortFieldsBySeq: function (data) {
        const sortedData = {};
        // 遍历每个文档
        Object.entries(data).forEach(([docId, docInfo]) => {
            // 深拷贝文档信息，避免修改原对象
            const newDocInfo = JSON.parse(JSON.stringify(docInfo));
            // 提取fields的键值对数组，并按seq升序排序
            const fieldsArr = Object.entries(newDocInfo.fields);
            const sortedFieldsArr = fieldsArr.sort((a, b) => {
                // a[1] 和 b[1] 是字段对象，取seq属性比较
                return a[1].seq - b[1].seq; // 升序（从小到大）；降序则改为 b[1].seq - a[1].seq
            });
            // 将排序后的数组转回对象（ES6+ 保留顺序）
            newDocInfo.fields = Object.fromEntries(sortedFieldsArr);
            // 存入排序后的数据对象
            sortedData[docId] = newDocInfo;
        });
        return sortedData;
    },

    renderAllTablesByColumns: function () {
        var _this = this;
        if (_this.contractName !== "") {
            $("#popup_title").attr("value", _this.contractName);
        }
        var wrapper = $('#tables-wrapper');
        wrapper.empty();

        $.each(_this.protocolData, function (protocolKey, protocolInfo) {
            var tableContainer = $('<div>').addClass('table-container');
            // 表格标题和预览按钮
            var tableTitle = $('<div>').addClass('table-title');
            tableTitle.append($('<span>').text(protocolInfo.name || '未命名模板'));
            var previewBtn = $('<button>').addClass('preview-btn').text('预览');
            previewBtn.click(function () {
                _this.previewTableData(protocolKey);
            });
            tableTitle.append(previewBtn);

            var table = $('<table>').addClass('data-table').attr('id', 'table-' + protocolKey);

            var fieldNames = [];
            var fieldValues = [];
            $.each(protocolInfo.fields || {}, function (fieldKey, fieldInfo) {
                if (fieldInfo.dataType !== "签署区" && fieldInfo.dataType !== "骑缝签署区" && fieldInfo.dataType !== "签署日期") {
                    fieldNames.push(fieldInfo.name || '未命名字段');
                    fieldValues.push({
                        fieldKey: fieldKey,
                        value: fieldInfo.value === null ? '' : fieldInfo.value,
                        dataType: fieldInfo.dataType || '单行文本',
                        dataFormat: fieldInfo.dataFormat,
                        isRequired: fieldInfo.isRequired
                    });
                }
            });

            // 表头渲染
            var thead = $('<thead>');
            var headerTr = $('<tr>');
            $.each(fieldNames, function (index, name) {
                headerTr.append($('<th>').text(name));
            });
            thead.append(headerTr);
            table.append(thead);

            // 内容渲染
            var tbody = $('<tbody>');
            var dataTr = $('<tr>');
            $.each(fieldValues, function (index, fieldData) {
                var inputHtml;

                // 处理日期类型
                if (fieldData.dataType === "日期") {
                    var inputType = _this.getInputType(fieldData.dataFormat);
                    var formattedValue = _this.formatDateForInput(fieldData.value, fieldData.dataFormat);
                    if (fieldData.isRequired) {
                        inputHtml = '<input style="background-color: #D9EDF7;" type="' + inputType + '" value="' + formattedValue + '" placeholder="请输入值">';
                    } else {
                        inputHtml = '<input type="' + inputType + '" value="' + formattedValue + '" placeholder="请输入值">';
                    }

                } else if (fieldData.dataType === "勾选框") {
                    if (fieldData.value == 1 || fieldData.value == "1") {
                        inputHtml = '<input type="Checkbox" checked>';
                    } else {
                        inputHtml = '<input type="Checkbox">';
                    }

                } else {
                    // 非日期类型使用普通文本输入

                    if (fieldData.isRequired) {
                        inputHtml = '<input style="background-color: #D9EDF7;" type="text" value="' + fieldData.value + '" placeholder="请输入值">';
                    } else {
                        inputHtml = '<input type="text" value="' + fieldData.value + '" placeholder="请输入值">';
                    }
                }
                if (fieldData.dataType !== "签署区" && fieldData.dataType !== "骑缝签署区" && fieldData.dataType !== "签署日期") {
                    dataTr.append($(
                        '<td data-field-key="' + fieldData.fieldKey + '" ' +
                        'data-data-type="' + fieldData.dataType + '"' +
                        'data-data-format="' + fieldData.dataFormat + '">' +
                        inputHtml +
                        '</td>'
                    ));
                }
            });
            tbody.append(dataTr);
            table.append(tbody);

            tableContainer.append(tableTitle).append(table);
            wrapper.append(tableContainer);
        });
    },
    formatDateForInput: function (value, dataFormat) {
        if (!value) return '';

        // 补零工具函数：保证数字为两位（兼容ES5及以上）
        function padZero(num) {
            return num < 10 ? '0' + num : num;
        }

        // 尝试解析各种可能的日期格式
        var date;
        if (value instanceof Date) {
            date = value;
        } else {
            // 替换常见分隔符（包括中文年、月、日），统一为 '-' 和 'T'（兼容ISO格式）
            var normalizedValue = value
                .replace(/[./年]/g, '-')    // 将 . / 年 替换为 -
                .replace(/月/g, '-')        // 将 月 替换为 -
                .replace(/日/g, '')         // 移除 日
                .replace(/\s+/, 'T')        // 空格替换为T（衔接时分秒）
                .replace(/:/g, ':');        // 保留冒号（时分秒分隔符）

            date = new Date(normalizedValue);

            // 如果解析失败，尝试其他格式
            if (isNaN(date.getTime())) {
                // 处理类似 "2025-11" 这样的年月格式
                if (value.match(/^\d{4}-\d{2}$/)) {
                    date = new Date(value + '-01');
                } else {
                    console.warn('无法解析日期: ' + value);
                    return value; // 解析失败时返回原始值
                }
            }
        }

        // 根据dataFormat返回对应格式
        if (dataFormat.indexOf('yyyy-MM-dd HH:mm:ss') !== -1) {
            return date.toISOString().slice(0, 19).replace('T', ' '); // 注意：原代码slice(0,19)是"2025-11-12T13:45:30"，这里替换T为空格更符合常规
        } else if (dataFormat.indexOf('yyyy-MM-dd HH:mm') !== -1) {
            return date.toISOString().slice(0, 16).replace('T', ' ');
        } else if (dataFormat.indexOf('yyyy-MM-dd') !== -1) {
            return date.toISOString().slice(0, 10);
        } else if (dataFormat.indexOf('yyyy年MM月dd日') !== -1) {
            // 基础中文日期格式：yyyy年MM月dd日
            const year = date.getFullYear();
            const month = padZero(date.getMonth() + 1); // 月份是0-based（0-11），需+1
            const day = padZero(date.getDate());
            let result = `${year}年${month}月${day}日`;

            // 扩展：处理时分秒
            if (dataFormat.indexOf('HH:mm:ss') !== -1) {
                const hour = padZero(date.getHours());
                const minute = padZero(date.getMinutes());
                const second = padZero(date.getSeconds());
                result += ` ${hour}:${minute}:${second}`;
            } else if (dataFormat.indexOf('HH:mm') !== -1) {
                const hour = padZero(date.getHours());
                const minute = padZero(date.getMinutes());
                result += ` ${hour}:${minute}`;
            }
            return result;
        }

        // 未知格式，返回原始值
        return value;
    },
    getInputType: function (dataFormat) {
        // 添加对dataFormat的检查，无值时默认使用"yyyy-MM-dd"
        if (!dataFormat) {
            dataFormat = "yyyy-MM-dd";
        }

        // 处理中文日期格式：yyyy年MM月dd日（包括扩展格式）
        if (dataFormat.indexOf('yyyy年MM月dd日') !== -1) {
            return 'text';
        }

        // 简化原有逻辑：合并HH:mm:ss和HH:mm的判断
        if (dataFormat.indexOf('HH:mm') !== -1) { // 同时匹配HH:mm和HH:mm:ss
            return 'datetime-local';
        } else if (dataFormat.indexOf('yyyy-MM-dd') !== -1) {
            return 'date';
        }

        // 未知格式返回text
        return 'text';
    },

    // 预览单个表格数据
    previewTableData: function (protocolKey) {
        var _this = this;
        var protocolInfo = _this.protocolData[protocolKey] || {};
        var tableData = {};
        tableData[protocolKey] = {
            "name": protocolInfo.name || protocolKey,
            "id": protocolInfo.id || protocolKey,
            "fields": {}
        };

        $('#table-' + protocolKey + ' tbody tr td').each(function (index) {
            var fieldKey = $(this).data('field-key');
            var fieldName = $('#table-' + protocolKey + ' thead th:eq(' + index + ')').text() || '字段' + (index + 1);
            var value = $(this).find('input').val() || null;

            var dataType = "单行文本";
            if (protocolInfo.fields && protocolInfo.fields[fieldKey]) {
                dataType = protocolInfo.fields[fieldKey].dataType || "单行文本";
            }
            if (dataType === "勾选框") {
                value = "" + $(this).find('input').is(':checked') + ""
            }

            tableData[protocolKey].fields[fieldKey] = {
                name: fieldName,
                dataType: dataType,
                value: value
            };
        });
        var param = {}
        param.data = tableData;
        param.mack = "preview";
        $.block.show({
            text: '正在获取预览地址，请稍等...'
        });
        window.setTimeout(function () {
            // 调用服务获取字段数据
            shr.callService({
                serviceName: 'create_by_fileOSF',
                param: param,
                success: function (data) {
                    console.log("========调用合同返回参数=========")
                    console.log(data)
                    if (data.code !== 0) {
                        shr.showError({
                            'message': data.message
                        });
                    } else {
                        window.open(data.data.fileDownloadUrl, '_blank');
                    }
                    $.block.hide();
                },
                error: function (e) {
                    shr.showError({
                        'message': e
                    });
                    $.block.hide();
                }
            });
        }, 300)

    },
    // 收集所有表格数据
    collectAllTableData: function () {
        var allData = {};
        var _this = this;
        $.each(_this.protocolData, function (protocolKey, protocolInfo) {
            // var tableData = {
            //     tableName: protocolInfo.name,
            //     tableId: protocolInfo.id,
            //     fields: protocolInfo.fields
            // };
            var tableData = protocolInfo
            $('#table-' + protocolKey + ' tbody tr td').each(function (index) {
                var fieldKey = $(this).data('field-key');
                var fieldName = $('#table-' + protocolKey + ' thead th:eq(' + index + ')').text();
                var dataType = $(this).data('data-type');
                var dataFormat = $(this).data('data-format');
                tableData.fields[fieldKey].name = fieldName;
                tableData.fields[fieldKey].dataType = dataType;
                tableData.fields[fieldKey].dataFormat = dataFormat;
                var value = ""
                if (dataType == "勾选框") {
                    value = "" + $(this).find('input').is(':checked') + ""
                } else {
                    value = $(this).find('input').val() || null;
                }
                tableData.fields[fieldKey].value = value;
                // tableData.fields[fieldKey] = {
                //     name: fieldName,
                //     dataType: dataType,
                //     dataFormat: dataFormat,
                //     value: value
                // };
            });

            allData[protocolKey] = tableData;
        });
        console.log('===== 所有表格数据 =====');
        console.log(JSON.stringify(allData, null, 2));
        return allData;
    },
    // 验证签署顺序输入值
    validateOrder: function (input) {
        var value = parseInt(input.value);
        if (isNaN(value) || value < 1) {
            input.value = 1;
        } else if (value > 255) {
            input.value = 255;
        }
    },

    // 切换签署方类型
    changeSignerType: function (selectElement) {
        var type = selectElement.value;
        var card = $(selectElement).closest('.signer-card');
        var cardId = card.attr('data-id');
        var fieldsContainer = card.find('.signer-fields');
        var orderInput = card.find('.order-input');
        var roleElement = card.find('.signer-role');

        var nameElement = card.find('.signer-name');

        // 更新选择框样式和颜色
        if (type === 'personal') {
            $(selectElement).removeClass('type-company type-copy').addClass('type-personal');
            // 显示个人字段和签署顺序
            fieldsContainer.html(
                '<div class="form-group">' +
                '<input type="text" placeholder="真实姓名" class="input-field" id="signer-' + cardId + '-name" name="signer-' + cardId + '-name">' +
                '<span class="input-marker" id="name-tip-' + cardId + '">ⓘ</span>' +
                '<input type="hidden" id="signer-' + cardId + '-person-f7" name="signer-' + cardId + '-person-f7">' +
                '</div>' +
                '<div class="form-group">' +
                '<input type="text" placeholder="请输入手机号/邮箱" class="input-field" id="signer-' + cardId + '-account" name="signer-' + cardId + '-account">' +
                '</div>'
            );
            nameElement.text('签署方' + cardId)
            roleElement.text('签署');
            $('#span-' + cardId + '').remove();
            orderInput.show();
            // 初始化F7选择器
            this.initPersonF7(cardId);
        } else if (type === 'company') {
            $(selectElement).removeClass('type-personal type-copy').addClass('type-company');
            $('#signer-' + cardId + '-order').after('<span id="span-' + cardId + '" style="display: none;"> 自动签 <input type="radio" placeholder="" class="" id="signer-' + cardId + '-radio" name="signer-radio-orgname"></span>');
            // 显示企业字段和签署顺序
            fieldsContainer.html(
                '<div class="form-group">' +
                '<input type="text" placeholder="请输入企业完整名称" class="input-field" id="signer-' + cardId + '-orgname" name="signer-' + cardId + '-orgname">' +
                '</div>' +
                '<div class="form-group">' +
                '<input readonly type="text" placeholder="企业章" class="input-field" id="signer-' + cardId + '-orgnId" name="signer-' + cardId + '-orgnId">' +
                '<span class="input-marker" id="name-orgId-' + cardId + '">ⓘ</span>' +
                '<input type="hidden" id="signer-' + cardId + '-orgnId-f7" name="signer-' + cardId + '-orgnId-f7">' +
                '</div>' +
                '<div class="form-group">' +
                '<input type="text" placeholder="真实姓名" class="input-field" id="signer-' + cardId + '-name" name="signer-' + cardId + '-name">' +
                '<span class="input-marker" id="name-tip-' + cardId + '">ⓘ</span>' +
                '<input type="hidden" id="signer-' + cardId + '-person-f7" name="signer-' + cardId + '-person-f7">' +
                '</div>' +
                '<div class="form-group">' +
                '<input type="text" placeholder="请输入手机号/邮箱" class="input-field" id="signer-' + cardId + '-account" name="signer-' + cardId + '-account">' +
                '</div>'
            );
            nameElement.text('签署方' + cardId)
            roleElement.text('签署');
            orderInput.show();
            // 初始化F7选择器
            this.initPersonF7(cardId);
        } else if (type === 'copy') {
            // 处理抄送类型
            $(selectElement).removeClass('type-personal type-company').addClass('type-copy');
            $('#span-' + cardId + '').remove();
            // 显示抄送字段，隐藏签署顺序
            fieldsContainer.html(
                '<div class="form-group">' +
                '<input type="text" placeholder="真实姓名" class="input-field" id="signer-' + cardId + '-name" name="signer-' + cardId + '-name">' +
                '<span class="input-marker" id="name-tip-' + cardId + '">ⓘ</span>' +
                '<input type="hidden" id="signer-' + cardId + '-person-f7" name="signer-' + cardId + '-person-f7">' +
                '</div>' +
                '<div class="form-group">' +
                '<input type="text" placeholder="请输入手机号/邮箱" class="input-field" id="signer-' + cardId + '-account" name="signer-' + cardId + '-account">' +
                '</div>'
            );
            nameElement.text('抄送方' + cardId)
            roleElement.text('抄送');
            orderInput.hide(); // 隐藏签署顺序
            // 初始化F7选择器
            this.initPersonF7(cardId);
        }
    },

    // 初始化人员选择F7
    initPersonF7: function (cardId) {
        var grid_f7_json = {
            id: 'signer-' + cardId + '-person-f7',
            name: 'signer-' + cardId + '-person-f7'
        };
        grid_f7_json.subWidgetName = 'shrPromptGrid';
        grid_f7_json.subWidgetOptions = {
            title: "员工",
            uipk: "com.kingdee.eas.custom.entryconfig.app.person.F7",
            query: "",
            filter: "",
            domain: "",
            multiselect: false,
            treeFilterConfig: '',
            permItemId: "",
            isHasMultileDialog: false,
            isTree: false,
            treeUrl: "",
            isContainLowerOrg: false,
            isAdminOrg: false,
            pgSizes: true,
            f7SearchConfig: { "displayField": [], "filterFields": "" },
            dataShowMode: "layout"
        };
        grid_f7_json.readonly = '';
        grid_f7_json.validate = '{required:false}';
        grid_f7_json.value = { 'id': "", 'name': "" };
        grid_f7_json.isHROrg = "false";
        grid_f7_json.isAdminOrg = "false";
        grid_f7_json.searchLikePattern = "any";

        // 初始化F7选择器
        $('#signer-' + cardId + '-person-f7').shrPromptBox(grid_f7_json);

        // 绑定选择事件，将选择的姓名回填到真实姓名输入框
        $('#signer-' + cardId + '-person-f7').shrPromptBox('option', {
            afterOnSelectRowHandler: function (a, data) {
                $('#signer-' + cardId + '-name').val(data.value.name);
                $('#signer-' + cardId + '-account').val(data.value.cell);
                console.log(data);
            }
        });
        $('#name-tip-' + cardId).click(function () {
            $('#signer-' + cardId + '-person-f7').shrPromptBox("open");
        });
        $('#signer-' + cardId + '-person-f7').parent().parent().parent().hide();




        id = "signer-' + cardId + '-orgnId-f7"


        var grid_f7_json = {
            id: 'signer-' + cardId + '-orgnId-f7',
            name: 'signer-' + cardId + '-orgnId-f7'
        };
        grid_f7_json.subWidgetName = 'shrPromptGrid';
        grid_f7_json.subWidgetOptions = {
            title: "印章",
            uipk: "com.kingdee.eas.custom.esign.app.Seal.list",
            query: "",
            filter: "",
            domain: "",
            multiselect: false,
            treeFilterConfig: '',
            permItemId: "",
            isHasMultileDialog: false,
            isTree: false,
            treeUrl: "",
            isContainLowerOrg: false,
            isAdminOrg: false,
            pgSizes: true,
            f7SearchConfig: { "displayField": [], "filterFields": "" },
            dataShowMode: "layout"
        };
        grid_f7_json.readonly = '';
        grid_f7_json.validate = '{required:false}';
        grid_f7_json.value = { 'id': "", 'name': "" };
        grid_f7_json.isHROrg = "false";
        grid_f7_json.isAdminOrg = "false";
        grid_f7_json.searchLikePattern = "any";

        // 初始化F7选择器
        $('#signer-' + cardId + '-orgnId-f7').shrPromptBox(grid_f7_json);

        $('#signer-' + cardId + '-orgnId-f7').shrPromptBox('option', {
            afterOnSelectRowHandler: function (a, data) {
                $('#signer-' + cardId + '-orgnId').val(data.value.sealId);
                console.log(data);
            }
        });
        $('#name-orgId-' + cardId).click(function () {
            $('#signer-' + cardId + '-orgnId-f7').shrPromptBox("open");
        });

        $('#signer-' + cardId + '-orgnId-f7').parent().parent().parent().hide();
    },

    // 更新签署方序号
    updateSignerNumbers: function () {
        var _this = this;
        $('.signer-card').each(function (index, element) {
            var newNumber = index + 1;
            var oldId = $(element).attr('data-id');

            // 更新卡片ID
            $(element).attr('data-id', newNumber);

            // 更新显示名称
            $(element).find('.signer-name').text('签署方' + newNumber);

            // 更新所有相关元素的ID和name属性
            $(element).find('[id^="signer-' + oldId + '-"]').each(function () {
                var field = $(this).attr('id').split('-').pop();
                $(this).attr('id', 'signer-' + newNumber + '-' + field);
                var name = $(this).attr('name');
                if (name !== "signer-radio-orgname") {
                    $(this).attr('name', 'signer-' + newNumber + '-' + field);
                }
            });

            // 重新初始化F7组件（因为ID发生了变化）
            _this.initPersonF7(newNumber);

            // 如果没有设置过顺序值，自动填充序号（只对非抄送类型生效）
            var orderInput = $(element).find('.order-input');
            var typeSelect = $(element).find('.type-select');

            if (typeSelect.val() !== 'copy' && (!orderInput.val() || orderInput.val() < 1)) {
                orderInput.val(newNumber);
            }
        });
        _this.signerCount = $('.signer-card').length;
    },

    // 获取数据方法
    getSignerData: function () {
        var result = {
            signers: [],
            copiers: []
        };

        // 遍历所有签署方卡片
        $('.signer-card').each(function () {
            var cardId = $(this).attr('data-id');
            var type = $(this).find('#signer-' + cardId + '-type').val();
            // 获取F7选择的完整数据
            var f7Data = $('#signer-' + cardId + '-person-f7').shrPromptBox('getValue') || {};

            if (type === 'personal') {
                // 个人签署方
                result.signers.push({
                    psnSignerInfo: {
                        psnAccount: $(this).find('#signer-' + cardId + '-account').val() || '',
                        psnName: $(this).find('#signer-' + cardId + '-name').val() || '',
                        signOrder: $(this).find('#signer-' + cardId + '-order').val() || '1',
                        f7Data: f7Data, // 包含F7选择的完整数据
                        signName: $(this).find('#signername_index' + cardId).text() || '',
                    }
                });
            } else if (type === 'company') {
                // 企业签署方
                result.signers.push({
                    orgSignerInfo: {
                        orgName: $(this).find('#signer-' + cardId + '-orgname').val() || '',
                        psnName: $(this).find('#signer-' + cardId + '-name').val() || '',
                        psnAccount: $(this).find('#signer-' + cardId + '-account').val() || '',
                        signOrder: $(this).find('#signer-' + cardId + '-order').val() || '1',
                        f7Data: f7Data, // 包含F7选择的完整数据
                        sealId: $(this).find('#signer-' + cardId + '-orgnId').val() || '',
                        isRadio: $('#signer-' + cardId + '-radio').is(":checked"),
                        signName: $(this).find('#signername_index' + cardId).text() || '',
                    }
                });
            } else if (type === 'copy') {
                // 抄送方
                result.copiers.push({
                    psnAccount: $(this).find('#signer-' + cardId + '-account').val() || '',
                    psnName: $(this).find('#signer-' + cardId + '-name').val() || '',
                    f7Data: f7Data, // 包含F7选择的完整数据
                    signName: $(this).find('#signername_index' + cardId).text() || '',
                });
            }
        });

        return result;
    },
    // 重置参与方设置
    resetSigners: function (eSignTemplateId) {
        var _this = this;
        // 清空现有签署方卡片
        $('#signersContainer').empty();
        // 重置签署方计数
        this.signerCount = 1;
        // 隐藏结果区域
        $('#resultArea').hide();
        var param = {}
        param.mack = "getTemplate";
        param.eSignTemplateNum = eSignTemplateId
        shr.callService({
            serviceName: 'create_by_fileOSF',
            param: param,
            success: function (data) {
                console.log("========签署信息=========")
                console.log(data)
                if (data.data.length <= 0) {
                    shr.showWarning({
                        'message': "未获取到设置签署信息请自行设置签署人！注：需要和e签宝保持一致。"
                    });
                }
                var d = data.data
                for (let i = 0; i < d.length; i++) {
                    var entry = d[i];
                    //签署类型 1 公司签署 2 个人签署 3 抄送人
                    var type = entry.participantType;

                    var defaultSigner = "";

                    if (type == 1 || type == "1") {
                        var participantFlag = entry.participantFlag;
                        var orgParticipant = entry.orgParticipant
                        var participantSetMode = entry.participantSetMode
                        if (participantSetMode == 2 ) {
                            continue;
                        }
                        defaultSigner = '<div class="signer-card" data-id="' + _this.signerCount + '">' +
                            '<div class="card-header">' +
                            '<div class="card-info"><select class="type-select type-company" id="signer-' + _this.signerCount + '-type" name="signer-' + _this.signerCount + '-type" disabled>' +
                            '<option value="personal" >个人</option>' +
                            '<option value="company" selected >企业</option>' +
                            '<option value="copy">抄送</option>' +
                            '</select>' +
                            '<span class="signer-name" id="signername_index' + _this.signerCount + '">' + participantFlag + '</span><span class="signer-role">签署</span>' +
                            '<input type="number" min="1" max="255" value="' + _this.signerCount + '" class="order-input"id="signer-' + _this.signerCount + '-order" name="signer-' + _this.signerCount + '-order" style="">' +
                            '<span id="span-' + _this.signerCount + '" style="display: none;"> 自动签 <input type="radio"placeholder="" class="" id="signer-' + _this.signerCount + '-radio" name="signer-radio-orgname"></span>' +
                            '</div>' +
                            '<!--div class="card-actions"><span class="action-link delete-signer"><span class="icon"></span>删除</span></div-->' +
                            '</div>' +
                            '<div class="form-grid signer-fields">'
                        if (orgParticipant != null) {
                            var orgName = orgParticipant.orgName;
                            //disabled
                            if (orgName != null && orgName != undefined && orgName != "") {
                                defaultSigner += '<div class="form-group"><input type="text" placeholder="请输入企业完整名称" value="' + orgParticipant.orgName + '" class="input-field" id="signer-' + _this.signerCount + '-orgname"name="signer-' + _this.signerCount + '-orgname"></div>'
                            } else {
                                defaultSigner += '<div class="form-group"><input type="text" placeholder="请输入企业完整名称" value="' + orgParticipant.orgName + '" class="input-field" id="signer-' + _this.signerCount + '-orgname"name="signer-' + _this.signerCount + '-orgname" disabled ></div>'
                            }
                        } else {
                            defaultSigner += '<div class="form-group"><input type="text" placeholder="请输入企业完整名称" value="" class="input-field" id="signer-' + _this.signerCount + '-orgname"name="signer-' + _this.signerCount + '-orgname"></div>'
                        }

                        defaultSigner += '<div class="form-group"><input readonly="" type="text" placeholder="企业章" class="input-field"id="signer-' + _this.signerCount + '-orgnId" name="signer-' + _this.signerCount + '-orgnId"><span class="input-marker" id="name-orgId-' + _this.signerCount + '">ⓘ</span>' +
                            '<div class="ui-promptBox-frame" style="display: none;">' +
                            '<div class="ui-promptBox-layout">' +
                            '<div class="ui-promptBox-inputframe"><input type="hidden" id="signer-' + _this.signerCount + '-orgnId-f7_el" name="hidd_name_signer-' + _this.signerCount + '-orgnId-f7" value=""><input type="hidden" id="signer-' + _this.signerCount + '-orgnId-f7"name="signer-' + _this.signerCount + '-orgnId-f7" ctrlrole="promptBox" autocomplete="off" value="" title=""></div>' +
                            '<div class="ui-promptBox-icon"><img style="cursor:pointer;" src="/shr/styles/images/seniorf7.png">' +
                            '</div>' +
                            '</div>' +
                            '</div>' +
                            '</div>';
                        if (orgParticipant != null) {
                            var transactor = orgParticipant.transactor;
                            if (transactor != null && transactor != undefined) {
                                defaultSigner += '<div class="form-group"><input type="text" placeholder="真实姓名" value="' + transactor.transactorName + '" class="input-field" id="signer-' + _this.signerCount + '-name" name="signer-' + _this.signerCount + '-name"><span class="input-marker" id="name-tip-' + _this.signerCount + '">ⓘ</span>'
                            } else {
                                defaultSigner += '<div class="form-group"><input type="text" placeholder="真实姓名" class="input-field" id="signer-' + _this.signerCount + '-name" name="signer-' + _this.signerCount + '-name"><span class="input-marker" id="name-tip-' + _this.signerCount + '">ⓘ</span>'

                            }

                        } else {
                            defaultSigner += '<div class="form-group"><input type="text" placeholder="真实姓名" class="input-field" id="signer-' + _this.signerCount + '-name" name="signer-' + _this.signerCount + '-name"><span class="input-marker" id="name-tip-' + _this.signerCount + '">ⓘ</span>'
                        }
                        defaultSigner += '<div class="ui-promptBox-frame" style="display: none;">' +
                            '<div class="ui-promptBox-layout">' +
                            '<div class="ui-promptBox-inputframe"><input type="hidden" id="signer-' + _this.signerCount + '-person-f7_el" name="hidd_name_signer-' + _this.signerCount + '-person-f7" value=""><input type="hidden" id="signer-' + _this.signerCount + '-person-f7"' +
                            ' name="signer-' + _this.signerCount + '-person-f7" ctrlrole="promptBox" autocomplete="off" value="" title=""></div>' +
                            '<div class="ui-promptBox-icon"><img style="cursor:pointer;" src="/shr/styles/images/seniorf7.png">' +
                            '</div>' +
                            '</div>' +
                            '</div>' +
                            '</div>';
                        if (orgParticipant != null) {
                            var transactor = orgParticipant.transactor;
                            if (transactor != null && transactor != undefined) {
                                defaultSigner += '<div class="form-group"><input type="text" placeholder="请输入手机号/邮箱" value="' + transactor.transactorPsnAccount + '" class="input-field" id="signer-' + _this.signerCount + '-account" name="signer-' + _this.signerCount + '-account"></div>';
                            } else {
                                defaultSigner += '<div class="form-group"><input type="text" placeholder="请输入手机号/邮箱" class="input-field" id="signer-' + _this.signerCount + '-account" name="signer-' + _this.signerCount + '-account"></div>';

                            }

                        } else {
                            defaultSigner += '<div class="form-group"><input type="text" placeholder="请输入手机号/邮箱" class="input-field" id="signer-' + _this.signerCount + '-account" name="signer-' + _this.signerCount + '-account"></div>';
                        }
                        defaultSigner += '</div>' +
                            '</div>';
                    } else if (type == 2 || type == "2") {
                        var participantFlag = entry.participantFlag;
                        var psnParticipant = entry.psnParticipant
                        var participantSetMode = entry.participantSetMode
                        if (participantSetMode == 2 ) {
                            continue;
                        }
                        // 添加默认的第一个签署方卡片 默认个人
                        defaultSigner = '<div class="signer-card" data-id="' + _this.signerCount + '">' +
                            '<div class="card-header">' +
                            '<div class="card-info">' +
                            '<select class="type-select type-personal" id="signer-' + _this.signerCount + '-type" name="signer-' + _this.signerCount + '-type" disabled>' +
                            '<option value="personal" selected >个人</option>' +
                            '<option value="company" >企业</option>' +
                            '<option value="copy">抄送</option>' +
                            '</select>' +
                            '<span class="signer-name" id = "signername_index' + _this.signerCount + '">' + participantFlag + '</span>' +
                            '<span class="signer-role">签署</span>' +
                            '<input type="number" min="1" max="255" value="' + _this.signerCount + '" class="order-input" id="signer-' + _this.signerCount + '-order" name="signer-' + _this.signerCount + '-order">' +
                            '</div>' +
                            '<!--div class="card-actions">' +
                            '<span class="action-link delete-signer"><span class="icon"></span>删除</span>' +
                            '</div-->' +
                            '</div>' +
                            '<div class="form-grid signer-fields">' +
                            '<div class="form-group">';
                        if (psnParticipant != null && psnParticipant != undefined) {
                            defaultSigner += '<input type="text" placeholder="真实姓名" value="' + psnParticipant.psnName + '" class="input-field" id="signer-' + _this.signerCount + '-name" name="signer-' + _this.signerCount + '-name">';
                        } else {
                            defaultSigner += '<input type="text" placeholder="真实姓名" class="input-field" id="signer-' + _this.signerCount + '-name" name="signer-' + _this.signerCount + '-name">';
                        }
                        defaultSigner += '<span class="input-marker" id="name-tip-' + _this.signerCount + '">ⓘ</span>' +
                            '<input type="hidden" id="signer-' + _this.signerCount + '-person-f7" name="signer-' + _this.signerCount + '-person-f7">' +
                            '</div>' +
                            '<div class="form-group">';
                        if (psnParticipant != null && psnParticipant != undefined) {
                            defaultSigner += '<input type="text" placeholder="请输入手机号/邮箱" value="' + psnParticipant.psnAccount + '" class="input-field" id="signer-' + _this.signerCount + '-account" name="signer-' + _this.signerCount + '-account">';
                        } else {
                            defaultSigner += '<input type="text" placeholder="请输入手机号/邮箱" class="input-field" id="signer-' + _this.signerCount + '-account" name="signer-' + _this.signerCount + '-account">';
                        }
                        defaultSigner += '</div>' +
                            '</div>' +
                            '</div>';
                    } else if (type == 3 || type == "3") {
                        var copierPsnInfo = entry.copierPsnInfo;
                        defaultSigner = '<div class="signer-card" data-id="' + _this.signerCount + '">' +
                            '<div class="card-header">' +
                            '<div class="card-info"><select class="type-select type-copy" id="signer-' + _this.signerCount + '-type" name="signer-' + _this.signerCount + '-type" disabled>' +
                            '<option value="personal">个人</option>' +
                            '<option value="company">企业</option>' +
                            '<option value="copy" selected >抄送</option>' +
                            '</select>' +
                            '<span class="signer-name" id="signername_index' + _this.signerCount + '" > 抄送方' + _this.signerCount + '</span><span class="signer-role">抄送</span>' +
                            '<input type="number" min="1" max="255" value="' + _this.signerCount + '" class="order-input" id="signer-' + _this.signerCount + '-order" name="signer-' + _this.signerCount + '-order" style="display: none;"></div>' +
                            '<!--div class="card-actions"><span class="action-link delete-signer"><span class="icon"></span>删除</span></div-->' +
                            '</div>' +
                            '<div class="form-grid signer-fields">' +
                            '<div class="form-group">';
                        if (copierPsnInfo != null && copierPsnInfo != undefined) {
                            defaultSigner += '<input type="text" placeholder="真实姓名" value="' + copierPsnInfo.psnName + '" class="input-field" id="signer-' + _this.signerCount + '-name" name="signer-' + _this.signerCount + '-name">';

                        } else {
                            defaultSigner += '<input type="text" placeholder="真实姓名" class="input-field" id="signer-' + _this.signerCount + '-name" name="signer-' + _this.signerCount + '-name">';
                        }
                        defaultSigner += '<span class="input-marker" id="name-tip-' + _this.signerCount + '">ⓘ</span>' +
                            '<div class="ui-promptBox-frame" style="display: none;">' +
                            '<div class="ui-promptBox-layout">' +
                            '<div class="ui-promptBox-inputframe">' +
                            '<input type="hidden" id="signer-' + _this.signerCount + '-person-f7_el" name="hidd_name_signer-' + _this.signerCount + '-person-f7" value="">' +
                            '<input type="hidden" id="signer-' + _this.signerCount + '-person-f7" name="signer-' + _this.signerCount + '-person-f7" ctrlrole="promptBox" autocomplete="off" value="" title="">' +
                            '</div>' +
                            '<div class="ui-promptBox-icon"><img style="cursor:pointer;" src="/shr/styles/images/seniorf7.png">' +
                            '</div>' +
                            '</div>' +
                            '</div>' +
                            '</div>' +
                            '<div class="form-group">';
                        if (copierPsnInfo != null && copierPsnInfo != undefined) {
                            defaultSigner += '<input type="text" placeholder="请输入手机号/邮箱" value="' + copierPsnInfo.psnAccount + '" class="input-field" id="signer-' + _this.signerCount + '-account" name="signer-' + _this.signerCount + '-account">';

                        } else {
                            defaultSigner += '<input type="text" placeholder="请输入手机号/邮箱" class="input-field" id="signer-' + _this.signerCount + '-account" name="signer-' + _this.signerCount + '-account">';
                        }
                        defaultSigner += '</div>' +
                            '</div>' +
                            '</div>';

                    } else {
                        shr.showWarning({
                            'message': "获取到设置签署信息失败！请自行设置签署人！注：需要和e签宝保持一致。"
                        });
                    }
                    $('#signersContainer').append(defaultSigner);
                    _this.initPersonF7(_this.signerCount);
                    _this.signerCount++
                }

            },
            error: function (e) {
                shr.showError({
                    'message': e
                });
            }
        });
    }
});