<?php
/**
 * The productf management
 *
 * @package EMLOG
 * @link https://www.emlog.net
 */

/**
 * @var string $action
 * @var object $CACHE
 */

require_once 'globals.php';

$goodsModel = new Goods_Model();
$stockModel = new Stock_Model();
$User_Model = new User_Model();
$MediaSort_Model = new MediaSort_Model();
$Template_Model = new Template_Model();

if($action == 'stock_add_new'){
    $goods_id = Input::getIntVar('goods_id');
    $db = Database::getInstance();
    $db_prefix = DB_PREFIX;
    $sql = "SELECT * FROM `{$db_prefix}goods` WHERE `id` = {$goods_id}";
    $goods = $db->once_fetch_array($sql);

    $skus = $db->fetch_all("select s.goods_id, s.sku, COALESCE(SUM(st.quantity), 0) AS stock_count from " . DB_PREFIX . "skus s left join {$db_prefix}stock st on s.goods_id=st.goods_id and s.sku=st.sku where s.goods_id={$goods_id} group by s.sku");

    $sku = $db->fetch_all("select * from " . DB_PREFIX . "sku_value");

    $sku_list = [];
    foreach($skus as $key => $val){
        $sku_list[$key]['sku_name'] = '';
        $sku_list[$key]['stock_count'] = $val['stock_count'];
        if($val['sku'] == 0){
            continue;
        }
        $sku_list[$key]['goods_id'] = $val['goods_id'];
        $sku_list[$key]['sku'] = $val['sku'];
        $sku_list[$key]['sku_name'] = '';
        $s = explode('-', $val['sku']);
        foreach($sku as $v){
            foreach($s as $sv){
                if($v['id'] == $sv){
                    $sku_list[$key]['sku_name'] .= $v['name'] . "；";
                }
            }
        }

    }


    include View::getAdmView('open_head');
    require_once View::getAdmView('stock_add_new');
    include View::getAdmView('open_foot');
    View::output();
}

if($action == 'edit'){
    $stock_id = Input::getIntVar('stock_id');
    $db = Database::getInstance();
    $db_prefix = DB_PREFIX;
    $sql = "select * from {$db_prefix}stock where id={$stock_id}";
    $stock = $db->once_fetch_array($sql);
    $sql = "SELECT * FROM `{$db_prefix}goods` WHERE `id` = {$stock['goods_id']}";
    $goods = $db->once_fetch_array($sql);

    include View::getAdmView('open_head');
    require_once View::getAdmView('stock_edit');
    include View::getAdmView('open_foot');
    View::output();
}

if($action == 'index_ws'){
    $goods_id = Input::getIntVar('goods_id');
    $db = Database::getInstance();
    $db_prefix = DB_PREFIX;
    $sql = "SELECT * FROM `{$db_prefix}goods` WHERE `id` = {$goods_id}";
    $goods = $db->once_fetch_array($sql);



    $skus = $db->fetch_all("select s.goods_id, s.sku, COALESCE(SUM(st.quantity), 0) AS stock_count from " . DB_PREFIX . "skus s left join {$db_prefix}stock st on s.goods_id=st.goods_id and s.sku=st.sku where s.goods_id={$goods_id} group by s.sku");

    $sku = $db->fetch_all("select * from " . DB_PREFIX . "sku_value");

    $sku_list = [];
    foreach($skus as $key => $val){
        $sku_list[$key]['sku_name'] = '';
        $sku_list[$key]['stock_count'] = $val['stock_count'];
        if($val['sku'] == 0){
            continue;
        }
        $sku_list[$key]['goods_id'] = $val['goods_id'];
        $sku_list[$key]['sku'] = $val['sku'];
        $sku_list[$key]['sku_name'] = '';
        $s = explode('-', $val['sku']);
        foreach($sku as $v){
            foreach($s as $sv){
                if($v['id'] == $sv){
                    $sku_list[$key]['sku_name'] .= $v['name'] . "；";
                }
            }
        }
    }




    include View::getAdmView('open_head');
    require_once View::getAdmView('stock_index_ws');
    include View::getAdmView('open_foot');
    View::output();
}
if($action == 'index_ws_ajax'){
    $db = Database::getInstance();
    $db_prefix = DB_PREFIX;

    $order_by = "order by ";
    $field = Input::getStrVar('field');
    $order_type = Input::getStrVar('order');
    if(!empty($order_type)){
        $order_by .= "s.{$field} {$order_type}, ";
    }

    $order_by .= "s.id asc";

    $sql = "SELECT * FROM `{$db_prefix}goods` where delete_time is null and is_on_shelf=1 order by id asc";
    $goods_json = [];
    $goods = $db->fetch_all($sql);
    foreach($goods as $val){
        $goods_json[] = [
            'text' => $val['title'],
            'value' => $val['id']
        ];
    }

    $goods_json = json_encode($goods_json);
    $goods_id = Input::getIntVar('goods_id');
    $keyword = Input::getStrVar('keyword');
    $sku = Input::getStrVar('sku');


    $page = Input::getIntVar('page', 1);
    $limit = Input::getIntVar('limit');

    $where = "g.id={$goods_id}";

    if(!empty($sku)){
        $where .= " and s.sku = '{$sku}'";
    }
    if(!empty($keyword)){
        $where .= " and s.content like '%{$keyword}%'";
    }

//echo $where;die;


    $start_limit = !empty($page) ? ($page - 1) * $limit : 0;
    $limit = "LIMIT $start_limit, " . $limit;

    $sql = "SELECT 
    g.title, s.content, s.create_time, g.delete_time, g.type, s.quantity, s.sku, s.id stock_id, g.type goods_type 
FROM " . DB_PREFIX . "stock as s 
JOIN " . DB_PREFIX . "goods as g 
    ON s.goods_id = g.id 
WHERE 
    {$where}
GROUP BY s.id 
{$order_by} {$limit} ";
//    echo $sql;die;

    $list = $db->fetch_all($sql);

    $sku = $db->fetch_all("select * from " . DB_PREFIX . "sku_value");

    foreach($list as $key => $val){
        $list[$key]['sku_name'] = '';
        $list[$key]['create_time'] = date('Y-m-d H:i', $val['create_time']);
        if($val['sku'] == 0){
            continue;
        }
        $s = explode('-', $val['sku']);
        foreach($sku as $v){
            foreach($s as $sv){
                if($v['id'] == $sv){
                    $list[$key]['sku_name'] .= $v['name'] . "；";
                }
            }
        }

    }
    $res = $db->once_fetch_array("SELECT 
    COUNT(DISTINCT s.id) AS total 
FROM " . DB_PREFIX . "stock as s 
JOIN " . DB_PREFIX . "goods as g 
    ON s.goods_id = g.id 
WHERE 
    {$where}
    ; ");

    $total = $res['total'];
    output::data($list, $res['total']);
}

if ($action == 'index_ys_ajax') {

    $db = Database::getInstance();
    $db_prefix = DB_PREFIX;

    $sql = "SELECT * FROM `{$db_prefix}goods` where delete_time is null and is_on_shelf=1 order by id asc";
    $goods_json = [];
    $goods = $db->fetch_all($sql);
    foreach($goods as $val){
        $goods_json[] = [
            'text' => $val['title'],
            'value' => $val['id']
        ];
    }

    $goods_json = json_encode($goods_json);
    $goods_id = Input::getIntVar('goods_id', 0);
    $keyword = Input::getStrVar('keyword', '');

    $page = Input::getIntVar('page', 1);


    $where = "g.type NOT IN ('post', 'xuni') and d.delete_time is null";
    if(!empty($goods_id)){
        $where .= " and g.id={$goods_id}";
    }
    if(!empty($keyword)){
        $where .= " and (d.content LIKE '%{$keyword}%' or skv.name LIKE '%{$keyword}%')";
    }


    $start_limit = !empty($page) ? ($page - 1) * Option::get('admin_article_perpage_num') : 0;
    $limit = "LIMIT $start_limit, " . Option::get('admin_article_perpage_num');

    if(empty($keyword) && empty($keyword)){
        $sql = "select 
                d.*, g.title, g.delete_time goods_delete_time, g.type goods_type, ol.sku
            from " . DB_PREFIX . "deliver d
            left join " . DB_PREFIX . "order_list ol on d.order_list_id=ol.id 
            left join " . DB_PREFIX . "goods g on ol.goods_id=g.id
            where {$where}
            order by id desc {$limit}";
    }else{
        $sql = "SELECT 
    d.*, 
    g.title, 
    g.delete_time goods_delete_time, 
    g.type goods_type, ol.sku, 
    GROUP_CONCAT(DISTINCT skv.name SEPARATOR ', ') AS sku_names
FROM " . DB_PREFIX . "deliver d
LEFT JOIN " . DB_PREFIX . "order_list ol ON d.order_list_id = ol.id 
LEFT JOIN " . DB_PREFIX . "goods g ON ol.goods_id = g.id
LEFT JOIN " . DB_PREFIX . "sku_value skv 
    ON FIND_IN_SET(skv.id, REPLACE(ol.sku, '-', ',')) > 0
WHERE {$where}
GROUP BY d.id
ORDER BY d.id DESC {$limit};";
    }


    $list = $db->fetch_all($sql);



    $sku = $db->fetch_all("select * from " . DB_PREFIX . "sku_value");

    foreach($list as $key => $val){
        $list[$key]['sku_name'] = '';
        $list[$key]['create_time'] = date('Y-m-d H:i', $val['create_time']);
        if(empty($val['sku'])){
            continue;
        }
        $s = explode('-', $val['sku']);
        foreach($sku as $v){
            foreach($s as $sv){
                if($v['id'] == $sv){
                    $list[$key]['sku_name'] .= $v['name'] . "；";
                }
            }
        }
    }

//    d($list);die;

    if(empty($keyword) && empty($keyword)){
        $res = $db->once_fetch_array("select 
                count(d.id) total
            from " . DB_PREFIX . "deliver d
            left join " . DB_PREFIX . "order_list ol on d.order_list_id=ol.id 
            left join " . DB_PREFIX . "goods g on ol.goods_id=g.id
            where {$where}");
    }else{
        $sql = "select 
                count(d.id) total
            from " . DB_PREFIX . "deliver d
            left join " . DB_PREFIX . "order_list ol on d.order_list_id=ol.id 
            left join " . DB_PREFIX . "goods g on ol.goods_id=g.id
            LEFT JOIN " . DB_PREFIX . "sku_value skv ON FIND_IN_SET(skv.id, REPLACE(ol.sku, '-', ',')) > 0
            where {$where}";
//echo $sql;die;

        $res = $db->once_fetch_array($sql);
    }

    output::data($list, $res['total']);



}

if($action == 'export_page'){
    $goods_id = Input::getIntVar('goods_id');
    $db = Database::getInstance();
    $db_prefix = DB_PREFIX;
    $sql = "SELECT * FROM `{$db_prefix}goods` WHERE `id` = {$goods_id}";
    $goods = $db->once_fetch_array($sql);
    include View::getAdmView('open_head');
    require_once View::getAdmView('stock_export');
    include View::getAdmView('open_foot');
    View::output();
}

if($action == 'export_log'){
    $goods_id = Input::getIntVar('goods_id');
    $db = Database::getInstance();
    $db_prefix = DB_PREFIX;
    $sql = "SELECT * FROM `{$db_prefix}goods` WHERE `id` = {$goods_id}";
    $goods = $db->once_fetch_array($sql);
    include View::getAdmView('open_head');
    require_once View::getAdmView('stock_export_log');
    include View::getAdmView('open_foot');
    View::output();
}
if($action == 'export_log_ajax'){
    $db = Database::getInstance();
    $db_prefix = DB_PREFIX;
    $page = Input::getIntVar('page', 1);
    $page_num = Input::getIntVar('limit', 10);
    $start = ($page - 1) * $page_num;
    $limit = "limit {$start}, {$page_num}";
    $order_field = Input::getStrVar('field', 'id');
    $order_type = Input::getStrVar('order', 'desc');
    $order_by = "order by l.{$order_field} {$order_type}";

    $sql = "select l.*, g.title from {$db_prefix}stock_export_log as l 
left join {$db_prefix}goods as g on g.id=l.goods_id 
 {$order_by} {$limit}";
    $list = $db->fetch_all($sql);
    foreach($list as $key => $val){
        $list[$key]['create_time'] = date('Y-m-d H:i:s', $val['create_time']);
    }
    $sql = "select count(distinct id) as count from {$db_prefix}stock_export_log";
    $total = $db->once_fetch_array($sql)['count'];

    output::data($list, $total);
}

if($action == 'index_ys'){
    $goods_id = Input::getIntVar('goods_id');
    $db = Database::getInstance();
    $db_prefix = DB_PREFIX;
    $sql = "SELECT * FROM `{$db_prefix}goods` WHERE `id` = {$goods_id}";
    $goods = $db->once_fetch_array($sql);
    include View::getAdmView('open_head');
    require_once View::getAdmView('stock_index_ys');
    include View::getAdmView('open_foot');
    View::output();
}

if(empty($action) || $action == 'sales'){
    $br = '<ol class="breadcrumb">
        <li class="breadcrumb-item"><a href="./">控制台</a></li>
        <li class="breadcrumb-item"><a href="./goods.php">商品管理</a></li>
        <li class="breadcrumb-item active" aria-current="page">库存管理</li>
    </ol>';
}

if (empty($action)) {

    $db = Database::getInstance();
    $db_prefix = DB_PREFIX;

    $sql = "SELECT * FROM `{$db_prefix}goods` where delete_time is null and is_on_shelf=1 order by id asc";
    $goods_json = [];
    $goods = $db->fetch_all($sql);
    foreach($goods as $val){
        $goods_json[] = [
            'text' => $val['title'],
            'value' => $val['id']
        ];
    }

    $goods_json = json_encode($goods_json);
    $goods_id = Input::getIntVar('goods_id', 0);
    $keyword = Input::getStrVar('keyword', '');


	$page = Input::getIntVar('page', 1);


    $where = "";
    if(!empty($goods_id)){
        $where .= "g.id={$goods_id}";
    }
    if(!empty($keyword)){
        if(empty($where)){
            $where .= "s.content LIKE '%{$keyword}%' or skv.name LIKE '%{$keyword}%'";
        }else{
            $where .= " and (s.content LIKE '%{$keyword}%' or skv.name LIKE '%{$keyword}%')";
        }
    }
//echo $where;die;

    $start_limit = !empty($page) ? ($page - 1) * Option::get('admin_article_perpage_num') : 0;
    $limit = "LIMIT $start_limit, " . Option::get('admin_article_perpage_num');
    if(empty($goods_id) && empty($keyword)){
        $sql = "SELECT s.create_time, g.title, s.content, g.delete_time, g.type goods_type, s.quantity, s.sku, s.id stock_id FROM " . DB_PREFIX . "stock as s join " . DB_PREFIX . "goods as g on s.goods_id=g.id order by s.id desc {$limit}";
    }else{

        $sql = "SELECT 
    g.title, s.content, s.create_time, g.delete_time, g.type, s.quantity, s.sku, s.id stock_id, g.type goods_type 
FROM " . DB_PREFIX . "stock as s 
JOIN " . DB_PREFIX . "goods as g 
    ON s.goods_id = g.id 
LEFT JOIN " . DB_PREFIX . "sku_value as skv 
    ON FIND_IN_SET(skv.id, REPLACE(s.sku, '-', ',')) > 0 
WHERE 
    {$where}
GROUP BY s.id 
ORDER BY s.id DESC {$limit} ";
    }
//echo $sql;die;
//    OR s.content LIKE '%{$keyword}%'
//    OR skv.name LIKE '%{$keyword}%'

    $list = $db->fetch_all($sql);
//echo 1;die;

    $sku = $db->fetch_all("select * from " . DB_PREFIX . "sku_value");

    foreach($list as $key => $val){
        $list[$key]['sku_name'] = '';
        if($val['sku'] == 0){
            continue;
        }
        $s = explode('-', $val['sku']);
        foreach($sku as $v){
            foreach($s as $sv){
                if($v['id'] == $sv){
                    $list[$key]['sku_name'] .= $v['name'] . "；";
                }
            }
        }
    }
    if(empty($goods_id) && empty($keyword)){
        $res = $db->once_fetch_array("SELECT count(s.id) total FROM " . DB_PREFIX . "stock as s join " . DB_PREFIX . "goods as g on s.goods_id=g.id");
    }else{
        $res = $db->once_fetch_array("SELECT 
    COUNT(DISTINCT s.id) AS total 
FROM " . DB_PREFIX . "stock as s 
JOIN " . DB_PREFIX . "goods as g 
    ON s.goods_id = g.id 
LEFT JOIN " . DB_PREFIX . "sku_value as skv 
    ON FIND_IN_SET(skv.id, REPLACE(s.sku, '-', ',')) > 0 
WHERE 
    {$where}
    ; ");
    }

    $total = $res['total'];


    $subPage = '';
    foreach ($_GET as $key => $val) {
        $subPage .= $key != 'page' ? "&$key=$val" : '';
    }
    $pageurl = pagination($total, Option::get('admin_article_perpage_num'), $page, "stock.php?{$subPage}&page=");

    $Sort_Model = new Sort_Model();
    $sorts = $Sort_Model->getSorts('goods');
    $goods = $db->fetch_all("select * from " . DB_PREFIX . "goods where delete_time is null order by id desc");

    $skus = $db->fetch_all("select goods_id, sku from " . DB_PREFIX . "skus");

    $sku_list = [];
    foreach($skus as $key => $val){
        $sku_list[$key]['sku_name'] = '';
        if($val['sku'] == 0){
            continue;
        }
        $sku_list[$key]['goods_id'] = $val['goods_id'];
        $sku_list[$key]['sku'] = $val['sku'];
        $sku_list[$key]['sku_name'] = '';
        $s = explode('-', $val['sku']);
        foreach($sku as $v){
            foreach($s as $sv){
                if($v['id'] == $sv){
                    $sku_list[$key]['sku_name'] .= $v['name'] . "；";
                }
            }
        }
    }


    include View::getAdmView(User::haveEditPermission() ? 'header' : 'uc_header');
    require_once View::getAdmView('stock');
    include View::getAdmView(User::haveEditPermission() ? 'footer' : 'uc_footer');
    View::output();
}

if($action == 'export_ajax'){
    $goods_id = Input::postStrVar('goods_id');
    $sku = Input::postStrVar('sku');
    $export_range = Input::postStrVar('export_range');
    $export_num = Input::postIntVar('export_num', 0);
    $is_delete = Input::postStrVar('is_delete');

    $start_time = Input::postStrVar('start_time', null);
    $end_time = Input::postStrVar('end_time', null);


    if($export_range == 'time'){
        if(empty($start_time) || empty($end_time)){
            output::error('请选择卡密添加时间');
        }
        if($start_time > $end_time){
            output::error('开始时间不能大于截止时间');
        }
    }

    $where = '';
    if($sku != 0 && !empty($sku)){
        $where .= " and sku='{$sku}'";
    }
    if($export_range == 'time'){
        $start_time .= ' 00:00:00';
        $end_time .= ' 23:59:59';
        $where .= " and create_time BETWEEN UNIX_TIMESTAMP('{$start_time}') and UNIX_TIMESTAMP('{$end_time}')";
    }

    $sql = "select * from " . DB_PREFIX . "stock where goods_id={$goods_id} {$where} order by id asc;";


    $db = Database::getInstance();
    $stock = $db->fetch_all($sql);

    if(empty($stock)){
        emMsg('暂无库存', 'javascript:window.close();');
    }

    $sku_value = $db->fetch_all("select * from " . DB_PREFIX . "sku_value");

    $data = [];
    foreach($stock as $val){
        if($val['sku'] == 0){
            if($export_range == 'num'){
                if(!empty($data['默认规格']) && count($data['默认规格']) >= $export_num){
                    continue;
                }
            }
            $data['默认规格'][] = [
                'content' => $val['content'],
                'id' => $val['id']
            ];
        }else{


            $temp = explode('-', $val['sku']);
            $sku_name = "";
            foreach($temp as $v){
                foreach($sku_value as $sv){
                    if($v == $sv['id']){
                        $sku_name .= $sv['name'] . "；";
                    }
                }
            }

            if($export_range == 'num'){
                if(!empty($data[$sku_name]) && count($data[$sku_name]) >= $export_num){
                    continue;
                }
            }

            $data[$sku_name][] = [
                'content' => $val['content'],
                'id' => $val['id']
            ];
        }
    }
    $goods = $db->once_fetch_array("select * from " . DB_PREFIX . "goods where id = {$goods_id}");

    $timestamp = time();

    header('Content-Type: application/json; charset=utf-8');
    header('Cache-Control: no-cache, no-store, must-revalidate');
    $filename = "导出卡密_{$timestamp}_{$goods_id}.txt";
    $saveDir = EM_ROOT . '/content/em_temp/';
    if (!is_dir($saveDir)) {
        mkdir($saveDir, 0755, true);
    }
    $filePath = $saveDir . $filename;
    // 循环数组并写入文件
    $fileHandle = fopen($filePath, 'w');
    if ($fileHandle) {
        // 遍历数组，将每个卡密写入文件
        foreach ($data as $key => $val) {
            fwrite($fileHandle, "---- " . $key . "\n");
            foreach ($val as $v) {
                fwrite($fileHandle, $v['content'] . "\n");
            }
        }
        fclose($fileHandle);

        // 删除卡密
        if($is_delete == 1){
            $ids = [];
            foreach($data as $val){
                foreach($val as $v){
                    $ids[] = $v['id'];
                }
            }
            $ids = implode(',', $ids);
            $db->query("delete from " . DB_PREFIX . "stock where id in({$ids})");
        }
        // 保存库存导出记录

        $sql = "INSERT INTO `" . DB_PREFIX . "stock_export_log` (`filename`, `goods_id`, `create_time`) VALUES ('{$filename}', {$goods_id}, {$timestamp})";
        $db->query($sql);

        // 生成下载地址
        output::ok(EM_URL . 'admin/download.php?filename=' . $filename);
    } else {
        output::error('文件权限不足，请设置网站目录权限为755');
    }


}



if($action == 'del'){
    $ids = Input::postStrVar('ids');
    $sql = "DELETE FROM " . DB_PREFIX . "stock WHERE id IN ({$ids})";
    $db = Database::getInstance();
    $db->query($sql);
    output::ok();
}
if($action == 'del_export_log'){
    $ids = Input::postStrVar('ids');
    $sql = "DELETE FROM " . DB_PREFIX . "stock_export_log WHERE id IN ({$ids})";
    $db = Database::getInstance();
    $db->query($sql);
    output::ok();
}

if($action == 'delete_sales'){
    $ids = Input::postStrVar('ids');
    $timestamp = time();
    $sql = "update " . DB_PREFIX . "deliver set delete_time = '{$timestamp}' WHERE id IN ({$ids})";

    $db = Database::getInstance();
    $db->query($sql);
    output::ok();
}

if ($action === 'add_ajax') {
    $goods_id = Input::postIntVar('goods_id', null);
    if($goods_id){
        $timestamp = time();
        $goods = $goodsModel->getOneGoodsForAdmin($goods_id);
        if($goods['is_sku'] == 'n'){
            if($goods['type'] == 'guding'){ // 固定卡密
                $is_stock = $stockModel->isStock(Input::postIntVar('goods_id'), '0');
                if($is_stock){
                    $update = [
                        'content' => Input::postStrVar('content', null),
                        'quantity' => Input::postIntVar('quantity', 0),
                    ];
                    $stockModel->updateStock($update, $goods_id, '0');
                }else{
                    $insert = [
                        'goods_id' => Input::postIntVar('goods_id'),
                        'sku' => '0',
                        'content' => Input::postStrVar('content', null),
                        'create_time' => $timestamp,
                        'quantity' => Input::postIntVar('quantity', 0),
                    ];
                    $stockModel->addStock($insert);
                }

            }
            if($goods['type'] == 'xuni'){ // 虚拟服务
                $is_stock = $stockModel->isStock(Input::postIntVar('goods_id'), '0');
                if($is_stock){
                    $update = [
                        'create_time' => $timestamp,
                        'quantity' => Input::postIntVar('quantity', 0),
                    ];
                    $stockModel->updateStock($update, $goods_id, '0');

                }else{
                    $insert = [
                        'goods_id' => Input::postIntVar('goods_id'),
                        'sku' => '0',
                        'create_time' => $timestamp,
                        'quantity' => Input::postIntVar('quantity', 0),
                    ];
                    $stockModel->addStock($insert);
                }
            }
            if($goods['type'] == 'post'){ // 自定义访问接口
                $is_stock = $stockModel->isStock(Input::postIntVar('goods_id'), '0');
                if($is_stock){
                    $update = [
                        'create_time' => $timestamp,
                        'quantity' => Input::postIntVar('quantity', 0),
                    ];
                    $stockModel->updateStock($update, $goods_id, '0');

                }else{
                    $insert = [
                        'goods_id' => Input::postIntVar('goods_id'),
                        'sku' => '0',
                        'create_time' => $timestamp,
                        'quantity' => Input::postIntVar('quantity', 0),
                    ];
                    $stockModel->addStock($insert);
                }
            }
            if($goods['type'] == 'duli'){ // 独立卡密
                $stock = Input::postStrVar('content');
                $stock = array_filter(explode("\n", $stock));
                $db_prefix = DB_PREFIX;
                $db = Database::getInstance();

                if(!empty($stock)){
                    // 每批次插入数量（可根据实际情况调整，建议500-2000之间）
                    $batchSize = 1000;
                    $total = count($stock);
                    $batches = array_chunk($stock, $batchSize); // 分割数组为多个批次

                    foreach($batches as $batch){
                        $content = [];
                        foreach($batch as $v){
                            $content[] = "({$goods_id}, '0', '{$v}', '{$timestamp}', 1)";
                        }

                        // 执行当前批次的批量插入
                        $sql = "INSERT INTO {$db_prefix}stock 
                    (goods_id, sku, content, create_time, quantity) 
                    VALUES " . implode(',', $content);
                        $db->query($sql);

                        // 释放当前批次内存
                        unset($content, $batch);
                    }
                }
            }
        }
        if($goods['is_sku'] == 'y'){
            $sku = Input::postStrVar('sku');
            if(empty($sku)){
                output::error('请选择商品规格');
            }
            if($goods['type'] == 'duli'){
                $stock = Input::postStrVar('content');
                $stock = array_filter(explode("\n", $stock));
                if(!empty($stock)){
                    foreach($stock as $v){
                        $insert = [
                            'goods_id' => Input::postStrVar('goods_id'),
                            'sku' => $sku,
                            'content' => $v,
                            'create_time' => $timestamp,
                            'quantity' => 1,
                        ];
                        $stockModel->addStock($insert);
                    }
                }
            }
            if($goods['type'] == 'guding'){
                $sku = Input::postStrVar('sku');
                $is_stock = $stockModel->isStock(Input::postIntVar('goods_id'), $sku);
                if($is_stock){
                    $update = [
                        'content' => Input::postStrVar('content', null),
                        'quantity' => Input::postIntVar('quantity', 0),
                    ];
                    $stockModel->updateStock($update, $goods_id, $sku);

                }else{
                    $insert = [
                        'goods_id' => Input::postIntVar('goods_id'),
                        'sku' => $sku,
                        'content' => Input::postStrVar('content', null),
                        'create_time' => $timestamp,
                        'quantity' => Input::postIntVar('quantity', 0),
                    ];
                    $stockModel->addStock($insert);
                }
            }
            if($goods['type'] == 'xuni'){
                $sku = Input::postStrVar('sku');
                $is_stock = $stockModel->isStock(Input::postIntVar('goods_id'), $sku);
                if($is_stock){
                    $update = [
                        'quantity' => Input::postIntVar('quantity', 0),
                    ];
                    $stockModel->updateStock($update, $goods_id, $sku);

                }else{
                    $insert = [
                        'goods_id' => Input::postIntVar('goods_id'),
                        'sku' => $sku,
                        'create_time' => $timestamp,
                        'quantity' => Input::postIntVar('quantity', 0),
                    ];
                    $stockModel->addStock($insert);
                }
            }
            if($goods['type'] == 'post'){
                $sku = Input::postStrVar('sku');
                $is_stock = $stockModel->isStock(Input::postIntVar('goods_id'), $sku);
                if($is_stock){
                    $update = [
                        'quantity' => Input::postIntVar('quantity', 0),
                    ];
                    $stockModel->updateStock($update, $goods_id, $sku);

                }else{
                    $insert = [
                        'goods_id' => Input::postIntVar('goods_id'),
                        'sku' => $sku,
                        'create_time' => $timestamp,
                        'quantity' => Input::postIntVar('quantity', 0),
                    ];
                    $stockModel->addStock($insert);
                }
            }
        }
        output::ok();
    }


    $goods_id = Input::getIntVar('goods_id', -1);
    $goods = $goodsModel->getOneGoodsForAdmin($goods_id);
//    d($goods);die;
    $db = Database::getInstance();
    if($goods['is_sku'] == 'y'){
        $get_sku = Input::getStrVar('get_sku', null);
        $sql = "select * from " . DB_PREFIX . "skus where goods_id={$goods['id']}";
        $result = $db->fetch_all($sql);
        $data = [];
        foreach($result as $key => $val){
            $sku_values = explode('-', $val['sku']);
            $data[$key]['sku_name'] = '';
            $data[$key]['sku_value'] = $val['sku'];
            foreach($sku_values as $v){
                $sql = "select * from " . DB_PREFIX . "sku_value where id={$v}";
                $sku_value = $db->once_fetch_array($sql);
                $data[$key]['sku_name'] .= $sku_value['name'] . '-';
            }
            $data[$key]['sku_name'] = rtrim($data[$key]['sku_name'], '-');
        }
        if($goods['type'] == 'guding'){
            $sql = "SELECT * FROM `" . DB_PREFIX . "stock` where goods_id={$goods['id']} and sku='{$get_sku}' limit 1;";
            $stock = $db->once_fetch_array($sql);
        }
        if($goods['type'] == 'xuni'){
            $sql = "SELECT * FROM `" . DB_PREFIX . "stock` where goods_id={$goods['id']} and sku='{$get_sku}' limit 1;";
            $stock = $db->once_fetch_array($sql);
        }
        if($goods['type'] == 'post'){
            $sql = "SELECT * FROM `" . DB_PREFIX . "stock` where goods_id={$goods['id']} and sku='{$get_sku}' limit 1;";
            $stock = $db->once_fetch_array($sql);
        }
//        d($data);die;
    }else{
        $sql = "SELECT * FROM `" . DB_PREFIX . "skus` where goods_id={$goods['id']} and sku='0' limit 1;";
        $skus = $db->once_fetch_array($sql);
        if($goods['type'] == 'xuni'){
            $sql = "SELECT * FROM `" . DB_PREFIX . "stock` where goods_id={$goods['id']} and sku='0' limit 1;";
            $stock = $db->once_fetch_array($sql);
        }
        if($goods['type'] == 'guding'){
            $sql = "SELECT * FROM `" . DB_PREFIX . "stock` where goods_id={$goods['id']} and sku='0' limit 1;";
            $stock = $db->once_fetch_array($sql);
        }
        if($goods['type'] == 'post'){
            $sql = "SELECT * FROM `" . DB_PREFIX . "stock` where goods_id={$goods['id']} and sku='0' limit 1;";
            $stock = $db->once_fetch_array($sql);
        }

    }


    $br = '<ol class="breadcrumb">
        <li class="breadcrumb-item"><a href="./">控制台</a></li>
        <li class="breadcrumb-item"><a href="./goods.php">商品管理</a></li>
        <li class="breadcrumb-item"><a href="./stock.php">库存管理</a></li>
        <li class="breadcrumb-item active" aria-current="page">添加库存 - ' . $goods['title'] . '</li>
    </ol>';



    include View::getAdmView(User::haveEditPermission() ? 'header' : 'uc_header');
    require_once(View::getAdmView('stock_add'));
    include View::getAdmView(User::haveEditPermission() ? 'footer' : 'uc_footer');
    View::output();
}

if ($action === 'edit_ajax') {
    $stock_id = Input::postIntVar('stock_id');
    $quantity = Input::postIntVar('quantity');
    $content = Input::postStrVar('content');
    $db = Database::getInstance();
    $db_prefix = DB_PREFIX;
    $sql = "UPDATE `{$db_prefix}stock` SET `content` = '{$content}', `quantity` = {$quantity} WHERE `id` = {$stock_id}";
    $db->query($sql);
    Output::ok();
}