<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <script type="text/javascript" src="{$smarty.const.CSS_URL}/js/jquery-1.8.1.min.js"></script>
    <script type="text/javascript" src="{$smarty.const.CSS_URL}/js/jquery.form.js"></script>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>添加药方</title>
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <link href="{$smarty.const.CSS_URL}/css/global.css?v={$smarty.const.CSS_JS_VERSION}" media="screen" rel="stylesheet" type="text/css">
    <script src="{$smarty.const.CSS_URL}/js/common.js?v={$smarty.const.CSS_JS_VERSION}"></script>
</head>
<body>

<div id="page">
    {include file="admin/include/header.html"}
    <div class="container">
        <aside id="sidebar" class="sidebar">
            <div id="search" class="domain-search module">
                {include file="admin/include/leftmenu.html"}
            </div>
        </aside>
        <section id="main">
            <div id="main-content">
                <div>
                    <div class="header">
                        <ul class="tabs">
                            <li class="active"><a href="javascript:;">添加药方</a></li>
                            {if $data.id}
                            <div style="display:inline-block;float: right;">
                                <button class="button link" onclick="to_delete({$data.id},1)">删除</button>
                            </div>
                            {/if}
                        </ul>
                    </div>
                </div>

                <div id="domain-list">
                    <div class="entry">
                        <div class="modal-body">
                            <div class="wizard-container"><div>
                            <div class="inputs">
                                <div id="form_area">
                                    <form id="prescription-form" onsubmit="submitForm(event)">
                                        <input id="id" name="id" type="hidden" value="{$data.id}">

                                        <div class="row">&nbsp;</div>

                                        <div class="row">
                                            <label for="name">药方名称<font color='red'>*</font>:</label>
                                            <input type="text" id="name" name="name" maxlength="" style="width:280px" value="{$data.name}">
                                        </div>

                                        <div class="row">&nbsp;</div>

                                        <div class="row">
                                            <label for="source">药方来源<font color='red'>*</font>:</label>
                                            <input type="text" id="source" name="source" maxlength="" style="width:280px" value="{if $data.source}{$data.source}{else}伤寒杂病论{/if}">
                                        </div>

                                        <div class="row">&nbsp;</div>

                                        <div class="row">
                                            <label for="method">用法<font color='red'></font>:</label>
                                            <textarea rows="3" cols="80" id="method" name="method">{$data.method}</textarea>
                                        </div>

                                        <div class="row">&nbsp;</div>

                                        <div class="row" style="position:relative;">
                                            <label>药材<font color='red'>*</font>:</label>
                                            <button class="add-button" type="button" onclick="addIngredient()">+</button>
                                        </div>

                                        <div id="ingredient-list" class="row">
                                            {foreach from=$data.formula key=key item=item}
                                            <div class="row">
                                                <label>&nbsp;</label>
                                                <div class="herb_input">
                                                    <input type="text" name="herb_name[]" value="{$item.name}" placeholder="药材名" required/>
                                                    <input type="text" name="herb_desc[]" value="{$item.desc}" placeholder="炮制方法"/>
                                                    <input type="text" name="herb_num[]" value="{$item.num_str}"
                                                           placeholder="用量" required/>
<!--                                                        /-->
<!--                                                        <input style="width: 80px" type="text" value="{$item.num}克" disabled/>-->

                                                    <button class="" type="button" onclick="removeIngredient(this)">X</button>
                                                </div>
                                            </div>
                                            {/foreach}

                                        </div>

                                        <div class="row">&nbsp;</div>

                                        <div class="row" id="" style="position:relative;">
                                            <label>&nbsp;</label>

                                            <button class="button primary next submitlock" id="submitbtn" onclick="submitForm()"><span class="tdesc_text" style="color:white;">提交</span></button>
                                        </div>

                                        <div class="row">&nbsp;</div>
                                    </form>
                                </div>
                            </div>
                        </div>
                        <div style="display: none;" id="formtips">
                            <div class="alert-message block-message info" style="color:red;"></div>
                        </div>
                    </div>
                    <!--end of a domain entry-->
                </div>
                <!-- 批量上传 <div id="onetickupload"></div> -->
            </div>
        </div>
        <textarea cols="300" rows="30" style="margin-top: 20px"></textarea>
    <!--end of main section-->
    </div><!--end of container-->
</section><!--end of #page-->

{literal}
<script type="text/javascript">
    function to_delete(id,status) {
        if (!confirm("确定要删除吗?")) {
            return false;
        }

        const data = {
            id: id,
            is_delete: status,
        };

        $.ajax({
            url: '/admin/ajax_delete_formula', // 替换为你的服务器端处理文件
            type: 'POST',
            data: data,
            dataType: 'json',
            success: function (response) {
                if (response.status == true) {
                    showAlert('删除成功', document.referrer)
                    return true;
                }

                if(response.data.code == 40002){
                    showAlert('请登录','/admin/login')
                    return true;
                }

                showAlert(response.info)
            },
            error: function (xhr, status, error) {
                console.error('错误:', response);
                alert('提交失败,请重试。');
            }
        });
    }

    // 动态添加药材输入字段
    function addIngredient() {
        const ingredientList = document.getElementById('ingredient-list');
        const ingredientDiv = document.createElement('div');
        ingredientDiv.classList.add('row');

        ingredientDiv.innerHTML = `
                <label>&nbsp;</label>
                <div class="herb_input">
                    <input type="text" name="herb_name[]" placeholder="药材名" required />
                    <input type="text" name="herb_desc[]" placeholder="炮制方法"/>
                    <input type="text" name="herb_num[]" placeholder="药量" required />
                    <button class="" type="button" onclick="removeIngredient(this)">X</button>
                </div>
            `;
        ingredientList.appendChild(ingredientDiv);
    }

    // 移除药材输入字段
    function removeIngredient(button) {
        button.parentElement.parentElement.remove();
    }

    function submitForm(e) {
        e.preventDefault(); // 阻止默认表单提交

        const form = document.getElementById('prescription-form');
        const formData = new FormData(form);

        const id = formData.get('id')

        const data = {
            id: formData.get('id'),
            name: formData.get('name'),
            source: formData.get('source'),
            method: formData.get('method'),
            herbs: ""
        };

        // 收集所有药材名称和重量
        const herb_name = formData.getAll('herb_name[]');
        const herb_num = formData.getAll('herb_num[]');
        const herb_desc = formData.getAll('herb_desc[]');

        const herbs = [];
        herb_name.forEach((name, index) => {
            herbs.push({
                name: name,
                num: herb_num[index],
                desc: herb_desc[index]
            });
        });

        data.herbs = JSON.stringify(herbs);
        $.ajax({
            url: '/admin/ajax_save_formula', // 替换为你的服务器端处理文件
            type: 'POST',
            data: data,
            dataType: 'json',
            success: function (response) {
                if (response.status == true) {
                    if(id){
                        showAlert('保存成功',document.referrer)
                    }else{
                        showAlert('添加成功',document.referrer)
                    }
                    return true;
                }

                if(response.data.code == 40002){
                    showAlert(response.info,"/admin/login")
                    return true;
                }

                showAlert(response.info)
            },
            error: function (xhr, status, error) {
                console.error('错误:', response);
                alert('提交失败,请重试。');
            }
        });
    }

</script>
<style>
    .add-button {
        width: 20px;
        height: 20px;
        background-color: #DD4B38;
        border: none;
        border-radius: 50px;
        color: #fff;
    }
</style>
{/literal}

</body>
</html>