<?php

require_once __DIR__ . '/core.php';

// 取出请求参数
$lang = $con->request->get('lang');

// 获取分类
$categories = $con->db->table('cate')->find('id, pid, c_name')->where('c_lang = ? AND c_on = ?', [$lang, 1])->order('c_sort ASC')->all();

if ($con->request->isAjax()) {
    $action = $con->request->post('action');
    switch ($action) {
        case 'list':
            // 获取分页
            $limit = $con->request->post(['page', 'limit'], FILTER_VALIDATE_INT);
            // 查询数据
            $cate = $con->request->get('p_cate', FILTER_VALIDATE_INT);
            $keyword = $con->request->get('keyword');
            if (null != $cate && null != $keyword) {
                $categories = $hel->listTree($categories, $cate);
                foreach ($categories as $index => $category) {
                    $categories[$index] = 'p_cate LIKE \'%,'.$category['id'].',%\'';
                }
                $categories[] = 'p_cate LIKE \'%,'.$cate.',%\'';
                $categories = implode(' OR ', $categories);
                $data = $con->db->table('product')->find('id, p_cate, p_name, p_img, p_price,p_on, p_sa, p_re, p_hot, p_new, p_sort')
                    ->where('p_lang = ? AND ('.$categories.') AND p_name LIKE \'%'.$keyword.'%\'', [$lang])->order('p_sort ASC,id DESC')
                    ->limit(($limit['page'] - 1) * $limit['limit'], $limit['limit'])->all();
                $count = $con->db->table('product')->count('p_lang = ? AND ('.$categories.') AND p_name LIKE \'%'.$keyword.'%\'', [$lang]);
            } else if (null != $cate) {
                $categories = $hel->listTree($categories, $cate);
                foreach ($categories as $index => $category) {
                    $categories[$index] = 'p_cate LIKE \'%,'.$category['id'].',%\'';
                }
                $categories[] = 'p_cate LIKE \'%,'.$cate.',%\'';
                $categories = implode(' OR ', $categories);
                $data = $con->db->table('product')->find('id, p_cate, p_name, p_img, p_price,  p_on, p_sa, p_re, p_hot, p_new, p_sort')
                    ->where('p_lang = ? AND ('.$categories.')', [$lang])->order('p_sort ASC,id DESC')
                    ->limit(($limit['page'] - 1) * $limit['limit'], $limit['limit'])->all();
                $count = $con->db->table('product')->count('p_lang = ? AND ('.$categories.')', [$lang]);
            } else if (null != $keyword) {
                $data = $con->db->table('product')->find('id, p_cate, p_name, p_img, p_price, p_on, p_sa, p_re, p_hot, p_new, p_sort')
                    ->where('p_lang = ? AND p_name LIKE \'%'.$keyword.'%\'', [$lang])->order('p_sort ASC,id DESC')
                    ->limit(($limit['page'] - 1) * $limit['limit'], $limit['limit'])->all();
                $count = $con->db->table('product')->count('p_lang = ? AND p_name LIKE \'%'.$keyword.'%\'', [$lang]);
            } else {
                $data = $con->db->table('product')->find('id, p_cate, p_name, p_img, p_price, p_on, p_sa, p_re, p_hot, p_new, p_sort')
                    ->where('p_lang = ?', [$lang])->order('p_sort ASC,id DESC')
                    ->limit(($limit['page'] - 1) * $limit['limit'], $limit['limit'])->all();
                $count = $con->db->table('product')->count('p_lang = ?', [$lang]);
            }
            // 处理数据
            $products = [];
            foreach ($data as $index => $product) {
                $products[$index]['seq'] = $index + 1;
                $products[$index]['id'] = $product['id'];
                foreach (['name', 'price', 'sales', 'sort'] as $key) {
                    $products[$index][$key] = $product['p_'.$key];
                }

                if(strpos($product['p_img'],',')!==false){
                    $img = strchr($product['p_img'], ',', true);
                }else{
                    $img=$product['p_img'];
                }
	            $products[$index]['img'] = '<img src="'.loadImage($img, $hel).'" alt="产品图片" height="28">';
                foreach (['on', 'sa', 're', 'hot', 'new'] as $key) {
                    switch ($key) {
                        case 'on':$title = '上架';break;
                        case 'sa':$title = '促销';break;
                        case 're':$title = '推荐';break;
                        case 'hot':$title = '热门';break;
                        case 'new':$title = '新品';break;
                        default:$title = '启用';break;
                    }
                    $products[$index][$key] = '<input class="layui-form-switch" type="checkbox" value="'.$title.'" lay-skin="primary" '.(1 == $product['p_'.$key] ? 'checked' : '').'>';
                }
            }
            unset($data);
            // 返回数据
            $data = [
                'msg'   => '',
                'code'  => 0,
                'count' => $count,
                'data'  => $products
            ];
            $con->json($data);
            break;
        case 'drop':
            // 获取唯一标识
            $unique = $con->request->post('unique');
            // 删除数据
            $row = $con->db->table('product')->delete('id = ?', [$unique])->row();
            $code = 1 === $row;
            $con->json(['code' => $code]);
            break;
        case 'edit':
            // 获取唯一标识
            $unique = $con->request->post('unique');
            // 取出数据
            $data = $con->request->post(['p_cate', 'name','metatitle','type', 'sku', 'url', 'kwd', 'des', 'img', 'related', 'details', 'attr', 'ratio', 'on', 'sa', 're', 'hot', 'new', 'sort']);

            // 处理数据
            $product = verify_data($data);
            unset($data);
            if (!is_array($product)) {
                $con->json(['code' => false, 'err' => $product]);
                break;
            }
            $product['p_update'] = date('Y-m-d H:i:s');
            // 修改数据
            $row = $con->db->table('product')->update($product, 'id = ?', [$unique])->row();
            $code = 1 === $row;
            $url = $hel->path() . '/product.php?lang='.$lang;
            if ($code) {
                $con->json(['code' => $code, 'path' => $url]);
            } else {
                $err = 23000 === $row ? '自定义URL重复，请尝试其他URL' : '修改失败';
                $con->json(['code' => $code, 'err' => $err]);
            }
            break;
        case 'insert':
            // 取出数据
            $data = $con->request->post(['p_cate','metatitle', 'name', 'type', 'sku', 'url', 'kwd', 'des', 'img', 'related', 'details', 'price', 'attr', 'ratio', 'on', 'sa', 're', 'hot', 'new', 'sort']);
            // 处理数据
            $product = verify_data($data);
            unset($data);
            if (!is_array($product)) {
                $con->json(['code' => false, 'err' => $product]);
                break;
            }
            $product['p_insert'] = date('Y-m-d H:i:s');
            $product['p_lang'] = $lang;
            // 插入数据
            $row = $con->db->table('product')->insert($product)->row();
            $code = 1 === $row;
            $url = $hel->path() . '/product.php?lang='.$lang;
            if ($code) {
                $con->json(['code' => $code, 'path' => $url]);
            } else {
                $err = 23000 === $row ? '自定义URL重复，请尝试其他URL' : '添加失败';
                $con->json(['code' => $code, 'err' => $err]);
            }
            break;
        case 'delete':
            // 获取唯一标识
            $unique = $con->request->post('unique');
            // 删除数据
            $row = $con->db->table('product')->delete('id IN ('.$unique.')')->row();
            $code = is_numeric($row);
            $con->json(['code' => $code]);
            break;
        case 'upload':
            // 保存文件
            $custom = $con->request->post('custom');
            if ($custom != '') {
                $name = $custom;
                foreach (scandir(PATH.'/file/image/'.date('YmdHis')) as $file) {
                    $file = strchr($file, '.', true);
                    if ($file == $name) {
                        $name .= base64_encode(microtime(true));
                    }
                }
            } else {
                $name = null;
            }
            $image = new \sc\Upload();
            if ($image->isImage()) {
                $path = $image->save('file/image/'.date('YmdHis'), $name);
                if (!$path) {
                    $con->json(['code' => false, 'err' => '保存失败']);
                } else {
                    $con->db->table('file')->insert([
                        'f_type' => 'I',
                        'f_name' => ltrim(strrchr($path, '/'), '/'),
                        'f_path' => $path,
                        'f_time' => date('Y-m-d H:i:s')
                    ])->row();
                    $con->json(['code' => true, 'path' => $path]);

                    // 处理图片
                    if ($path != false) {
                        $conf = $con->db->table('conf')->find('c_image, c_img_w, c_img_h, c_texts, c_txt_c, c_place, c_s_way')->where('id = ?', ['sem-cms'])->one();
                        if ($conf != false) {
                            $image->handle(PATH.'/'.$path, $conf);
                        }
                    }
                }
            } else {
                $con->json(['code' => false, 'err' => '请上传图片文件']);
            }
            break;
        case 'number':
            $number = $con->db->table('product')->count('p_lang = ?', [$lang]);
            $con->json(['number' => $number]);
            break;
        case 'relate':
            // 获取分页
            $limit = $con->request->post(['page', 'limit'], FILTER_VALIDATE_INT);
            // 查询数据
            $data = $con->db->table('product')->find('id, p_name, p_img')
                ->where('p_lang = ?', [$lang])->order('p_sort ASC')
                ->limit(($limit['page'] - 1) * $limit['limit'], $limit['limit'])->all();
            // 处理数据
            $related = [];
            foreach ($data as $index => $datum) {
                $related[$index]['id'] = $datum['id'];
                $related[$index]['img'] = loadImage(strchr($datum['p_img'], ',', true), $hel, false);
                $related[$index]['name'] = $datum['p_name'];
            }
            // 返回数据
            $con->json($related);
            break;
	    case 'attr':
	    	// 获取唯一标识符
			$unique = $con->request->post('unique');
			// 查询数据
			$data = $con->db->table('attr')->find('a_name, a_title, a_type, a_cont')->where('pid = ? AND a_on = ?', [$unique, 1])
				->order('a_sort ASC')->all();
			if (empty($data)) {
				$con->json(['code' => false]);
			}
			$html = '';
			foreach ($data as $datum) {
				$type = $datum['a_type'] == '' || $datum['a_type'] == 'T' ? 'text' : 'image';
				$html .= '<div><span>'.$datum['a_name'].': </span><input type="hidden" name="attr['.$datum['a_title'].'][]" value="'.$type.'">';
				foreach (json_decode($datum['a_cont'], true) as $attr) {
					$html .= '<input type="checkbox" name="attr['.$datum['a_title'].'][]" title="'.$attr['text'].'" value=\''.json_encode($attr).'\' lay-skin="primary">';
				}
				$html .= '</div>';
			}
			$con->json(['code' => true, 'html' => $html]);
	    	break;
	    /*case 'sale':
		    // 获取唯一标识符
		    $unique = $con->request->post('unique');
		    // 查询数据
		    $data = $con->db->table('sale')->find('s_name, s_model')->where('id = ?', [$unique])->one();
		    if (!$data) {
			    $con->json(['code' => false]);
		    }
		    if ($data['s_model'] == '') {
		    	$data['s_model'] = '[]';
		    }
		    $html = '';
		    foreach (json_decode($data['s_model'], true) as $model) {
		    	$html .= '<div><input type="text" class="layui-input count" name="count[]" value="'.$model['count'].'"><input type="number" class="layui-input ratio" name="ratio[]" value="'.$model['ratio'].'"></div>';
		    }
		    $con->json(['code' => true, 'html' => $html]);
	    	break;*/
        case 'on':
        case 'sa':
        case 're':
        case 'hot':
        case 'new':
            // 取出唯一标识
            $unique = $con->request->post('unique');
            // 查询开启状态
            $on = $con->db->table('product')->find('p_'.$action)->where('id = ?', [$unique])->one();
            if (!$on) {
                break;
            }
            if (1 == $on['p_'.$action]) {
                $row = $con->db->table('product')->update(['p_'.$action => 0], 'id = ?', [$unique])->row();
                if (1 == $row) {
                    $con->json(['code' => true, 'stat' => false]);
                } else {
                    $con->json(['code' => false, 'stat' => true, 'err' => '关闭失败']);
                }
            } else {
                $row = $con->db->table('product')->update(['p_'.$action => 1], 'id = ?', [$unique])->row();
                if (1 == $row) {
                    $con->json(['code' => true, 'stat' => true]);
                } else {
                    $con->json(['code' => false, 'stat' => false, 'err' => '开启失败']);
                }
            }
            break;
        default:break;
    }
} else {
    $action = $con->request->get('action');
    // 分类列表树
    $categories = $hel->listTree($categories, 1);
	// 获取属性
	$attributes = $con->db->table('attr')->find('id, a_name')->where('pid = ?', [0])->order('a_sort ASC')->all();
	// 获取折扣模板
	$models = $con->db->table('sale')->find('id, s_name')->order('s_sort ASC')->all();
    if ('edit' == $action) {
        // 获取唯一标识
        $unique = $con->request->get('unique');
        // 查询数据
        $data = $con->db->table('product')->find('*')->where('id = ?', [$unique])->one();
        $product = [];
        $product['id'] = $data['id'];
        $product['cate'] = $data['p_cate'];
        foreach (['name', 'metatitle','type', 'sku', 'url', 'kwd', 'des', 'details', 'price', 'on', 'sa', 're', 'hot', 'new', 'sort'] as $index) {
            $product[$index] = $data['p_'.$index];
        }
        $product['attr'] = '';
        $attrs = '' == $data['p_attr'] ? [] : json_decode($data['p_attr'], true);
        foreach ($attrs as $key => $attr) {
        	$type = array_shift($attr);
	        if (isset($type['type']) && $type['type'] == 'image') {
	        	$type = '显示图片';
	        } else {
	        	$type = '显示文字';
	        }
        	$product['attr'] .= '<div class="attribute"><b>'.$key.'</b>('.$type.'): ';
        	foreach ($attr as $a) {
		        $product['attr'] .= $a['text'].', ';
	        }
	        $product['attr'] = substr($product['attr'], 0, -2).'</div>';
        }
        /*$product['sale'] = '';
        $sale = '' == $data['p_sale'] ? [] : json_decode($data['p_sale'], true);
        foreach ($sale as $s) {
        	$product['sale'] .= '<div class="model"><span class="count"><b>订货量</b>: '.$s['count'].'</span><span class="ratio"><b>折扣</b>: '.$s['ratio'].'</span></div>';
        }*/
        $product['img'] = '' == $data['p_img'] ? [] : explode(',', $data['p_img']);
        foreach ($product['img'] as $index => $img) {
            $product['img'][$index] = loadImage($img, $hel, false);
        }
        $related = '' == $data['p_related'] ? [] : $con->db->table('product')->find('id, p_name, p_img')->where('id IN ('.$data['p_related'].')')->all();
        $product['related'] = [];
        foreach ($related as $rel) {
            $product['related'][] = [
                'id'   => $rel['id'],
                'name' => $rel['p_name'],
                'img'  => loadImage(strchr($rel['p_img'], ',', true), $hel, false)
            ];
        }
        unset($data);
        $con->render('product-edit', [
            'hel'       => $hel,
            'crumb'     => $breadcrumb,
            'select'    => generate_select($categories, 'p_cate', $product['cate']),
            'attribute' => create_select($attributes, 'a_name'),
            'model'    => create_select($models, 's_name'),
            'product'   => $product,
            'host'      => $hel->url(),
            'path'      => $hel->path(),
            'lang'      => $lang
        ]);
    } else if ('insert' == $action) {
        $data = false;
        $con->render('product-edit', [
            'hel'     => $hel,
            'crumb'   => $breadcrumb,
            'select'  => generate_select($categories, 'p_cate', 0),
            'attribute' => create_select($attributes, 'a_name'),
            'model'    => create_select($models, 's_name'),
            'product' => $data,
            'host'    => $hel->url(),
            'path'    => $hel->path(),
            'lang'    => $lang
        ]);
    } else {
        $con->render('product', [
            'crumb'   => $breadcrumb,
            'select'  => generate_select($categories, 'p_cate', 0),
            'host'    => $hel->url(),
            'path'    => $hel->path(),
            'lang'    => $lang
        ]);
    }
}

function generate_name($level)
{
    $name = '';
    while ($level--) {
        if ($level > 0) {
            $name .= '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
        } else {
            $name .= '&nbsp;&nbsp;&nbsp;&nbsp;|__&nbsp;&nbsp;';
        }
    }
    return $name;
}

function generate_select($categories, $name, $cates)
{
    $cates = explode(',', trim($cates, ','));
    $html = '<select name="'.$name.'" lay-filter="'.$name.'" multiple="multiple"><option>请选择</option>';
    foreach ($categories as $category) {
        $html .= '<option value="'.$category['id'].'" '.(in_array($category['id'], $cates) ? 'selected' : '').'>'.generate_name($category['level']).$category['c_name'].'</option>';
    }
    return $html.'</select>';
}

function create_select($data, $name) {
	if ($name == 'a_name') {
		$filter = 'attr';
	} else if ($name == 's_name') {
		$filter = 'sale';
	} else {
		$filter = '';
	}
	$html = '<select lay-filter="'.$filter.'"><option>请选择</option>';
	foreach ($data as $datum) {
		$html .= '<option value="'.$datum['id'].'">'.$datum[$name].'</option>';
	}
	return $html.'</select>';
}

/**
 * 数据验证方法
 *
 * @param array $data
 *
 * @return string|array
 */
function verify_data($data)
{
    $product['p_cate'] = ','.$data['p_cate'].',';
    if ('' == $data['name']) {
        // 名称为空
        return '产品名称不能为空';
    }
    if ('' != $data['sku']) {
        // SKU不为空
        $product['p_sku'] = $data['sku'];
    }
    $product['p_name'] = $data['name'];
    $product['p_metatitle']=$data['metatitle'];
    if ('' != $data['url']) {
        // URL不为空
        if (is_numeric($data['url'])) {
            return 'URL不能为纯数字';
        }
        $product['p_url'] = preg_replace('/[^-0-9a-zA-Z]+/', '-', $data['url']);
    }
    if ('' != $data['img']) {
        // 图片不为空
        foreach ($data['img'] as $key => $img) {
            // 处理英文逗号(,)
            $data['img'][$key] = str_replace(',', '-', $img);
        }
        $product['p_img'] = implode(',', $data['img']);
    } else {
        $product['p_img'] = '';
    }
    if ('' != $data['related']) {
        // 关联产品不为空
        $product['p_related'] = implode(',', $data['related']);
    } else {
        $product['p_related'] = '';
    }
    foreach (['type', 'kwd', 'des', 'details'] as $index) {
        $product['p_'.$index] = $data[$index];
    }
    foreach (['sort' => '产品排序'] as $index => $prompt) {
        if ((int)$data[$index] < 0) {
            // 数值小于0
            return $prompt.'不能小于0';
        }
        $product['p_'.$index] = $data[$index];
    }
    if ('' != $data['stock']) {
        $product['p_stock'] = $data['stock'];
    }
    foreach (['on', 'sa', 're', 'hot', 'new'] as $index) {
        if ('' == $data[$index]) {
            $product['p_'.$index] = 0;
        } else {
            $product['p_'.$index] = 1;
        }
    }
    if ('' != $data['attr']) {
    	foreach ($data['attr'] as $name => $attrs) {
    		foreach ($attrs as $index => $attr) {
    			if ($index == 0) {
				    $data['attr'][$name][$index] = ['type' => $attr];
			    } else {
				    $data['attr'][$name][$index] = json_decode($attr, true);
			    }
		    }
	    }
    	$product['p_attr'] = json_encode($data['attr']);
    }
	/*if ('' != $data['count']) {
		$model = [];
		foreach ($data['ratio'] as $index => $datum) {
			$model[$index] = [
				'count' => $data['count'][$index],
				'ratio' => $datum
			];
		}
		$product['p_sale'] = json_encode($model);
	}*/

    return $product;
}