<?php

/**
 * 产品
 */

namespace Module\Product;

use Pyramid\Component\HttpFoundation\Response;
use Pyramid\Component\HttpFoundation\RedirectResponse;
use Exception;

class Product {
    
    /**
     * 列表
     * @access product
     * @route /admin/product
     * @route /admin/product/list
     */
    public static function listproduct($request) {
        $keywords = $request->getParameter('keywords');
        $page = $request->getParameter('page');
        $query = db_select('product', 'p')->extend('Pager')->size(50)->page($page);
        $query->fields('p', array('id'))->orderBy('sortrank', 'ASC')->orderBy('id','ASC');
        $ids   = $query->execute()->fetchCol();
        $pager = $query->fetchPager();
        $data  = entity_load('product', $ids);
        return new Response(render('/admin/product/product.list.html', array(
            'pager' => $pager,
            'data'  => $data,
        )));
    }
    
    /**
     * 添加
     * @access product_add
     * @route /admin/product/add
     */
    public static function productAdd($request) {
        if ($request->post->getParameters()) {
            $product = (object) $request->post->getParameters();
            $product->created = $product->updated = time();
            try {
                entity_insert('product', $product);
                return new RedirectResponse($request->getUriForPath('/admin/product'), 1, '添加成功');
            } catch (Exception $e) {
                return new RedirectResponse($request->getUriForPath('/admin/product'), 4, $e->getMessage());
            }
        }
        $texing = db_query("select keyv,name from {taxonomy} where status=1 and category='产品特性'")->fetchAllKeyed();
        $pishu = db_query("select keyv,name from {taxonomy} where status=1 and category='匹数'")->fetchAllKeyed();
        return new Response(render('/admin/product/product.add.html', array(
            'option_texing' => $texing,
            'option_pishu' => $pishu,
        )));
    }
    
    /**
     * 修改
     * @access product_edit
     * @route /admin/product/edit/{id}
     */
    public static function productEdit($request) {
        $id = $request->route->getParameter('id');
        if (!$id) {
            return new RedirectResponse($request->getUriForPath('/admin/product'), 4, '无此记录');
        }
        if (!$product = entity_object('product', $id)) {
            return new RedirectResponse($request->getUriForPath('/admin/product'), 4, '无此记录');
        }
        if ($request->post->getParameters()) {
            $product = (object) $request->post->getParameters();
            $product->id = $id;
            $product->updated = time();
            try {
                entity_update('product', $product);
                return new RedirectResponse($request->getUriForPath('/admin/product'), 1, '更新成功');
            } catch (Exception $e) {
                return new RedirectResponse($request->getUriForPath('/admin/product'), 4, $e->getMessage());
            }
        }
        $texing = db_query("select keyv,name from {taxonomy} where status=1 and category='产品特性'")->fetchAllKeyed();
        $pishu = db_query("select keyv,name from {taxonomy} where status=1 and category='匹数'")->fetchAllKeyed();
        return new Response(render('/admin/product/product.edit.html', array(
            'data' => $product,
            'option_texing' => $texing,
            'option_pishu' => $pishu,
        )));
    }

    /**
     * 删除
     * @access product_delete
     * @route /admin/product/delete/{id}
     */
    public static function productDelete($request) {
        validateRequestToken($request, 600);
        $id = $request->route->getParameter('id');
        if (!$id) {
            return new RedirectResponse($request->getUriForPath('/admin/product'), 4, '无此记录');
        }
        if (!$product = entity_object('product', $id)) {
            return new RedirectResponse($request->getUriForPath('/admin/product'), 4, '无此记录');
        }
        $storeUpdate = (object) array('id'=>$product->id,'status'=>0);
        entity_update('product', $storeUpdate);            
        return new RedirectResponse($request->getUriForPath('/admin/product'), 1, '操作成功');
    }


    /**
     * 首页产品
     * @access product
     * @route /admin/product/homerank
     */
    public static function listhomeproduct($request) {
        $data = db_query("select * from {homeproduct}")->fetchAll();
        foreach($data as $v) {
            $ids = explode(',', $v->products?$v->products:'');
            $pts = entity_load('product', $ids);
            $v->products_name = implode(', ', pyramid_array_column($pts,'name'));
        }
        return new Response(render('/admin/product/productrank.list.html', array(
            'data'  => $data,
        )));
    }
    
    /**
     * 首页产品修改
     * @access product
     * @route /admin/product/homerank/edit/{id}
     */
    public static function edithomeproduct($request) {
        $id = $request->route->getParameter('id');
        if (!$id) {
            return new RedirectResponse($request->getUriForPath('/admin/product/homerank'), 4, '无此记录');
        }
        $data = db_query("select * from {homeproduct} where id=:id", array(':id'=>$id))->fetchObject();
        if (!$data) {
            return new RedirectResponse($request->getUriForPath('/admin/product/homerank'), 4, '无此记录');
        }
        if ($request->post->getParameters()) {
            $productids = $request->post->getParameter('productids', array());
            $productids = array_filter($productids);
            db_update('homeproduct')
                ->fields(array(
                    'products' => implode(',', $productids),
                ))
                ->condition('id', $id)
                ->execute();
            return new RedirectResponse($request->getUriForPath('/admin/product/homerank'), 1, '更新成功');
        }
        $allproducts = db_query("select id, name||'-'||category as text from {product} where status=1")->fetchAllKeyed();
        $ids = explode(',', $data->products?$data->products:'');
        $pts = entity_load('product', $ids);
        $selected = array();
        foreach($pts as $v) {
            $selected[] = array('id'=>$v->id,'text'=>$v->name);
        }
        return new Response(render('/admin/product/productrank.edit.html', array(
            'data' => $data,
            'selected' => $selected,
            'allproducts' => $allproducts,
        )));
    }
   
    /**
     * 产品选项
     * @access product
     * @route /admin/product/taxonomy
     */
    public static function taxonomy($request) {
        $all = db_query("select * from {taxonomy} where status=1")->fetchAll();
        $data = array();
        foreach($all as $v) {
            if (!isset($data[$v->category])) {
                $data[$v->category] = array();
            }
            $data[$v->category][$v->keyv] = $v->name;
        }
        
        if ($request->post->getParameters()) {
            $category = $request->post->getParameter('category', '');
            $keys = $request->post->getParameter('keys', array());
            $values = $request->post->getParameter('values', array());
            if (!$exists = db_query("select * from {taxonomy} where category=:category", array(':category'=>$category))->fetchObject()) {
                return new RedirectResponse($request->getUriForPath('/admin/product/taxonomy'), 4, '无此分类');
            }
            $fields = array();
            foreach($keys as $i=>$key) {
                $key = trim($key);
                $key = str_replace(array(',',' '),'',$key);
                if ($key !== '') {
                    $fields[$key] = $values[$i];
                }
            }
            db_query("update {taxonomy} set status=0 where category=:category", array(':category'=>$category));
            foreach($fields as $keyv=>$name) {
                db_merge('taxonomy')
                    ->key(array(
                        'category' => $category,
                        'keyv' => $keyv,
                    ))
                    ->fields(array(
                        'name' => $name,
                        'status' => 1,
                    ))
                    ->execute();
            }
            return new RedirectResponse($request->getUriForPath('/admin/product/taxonomy'), 1, '更新成功');
        }

        return new Response(render('/admin/product/taxonomy.html', array(
            'data'  => $data,
        )));
    }
    
}


permission_register(array(
    'product' => array(
        'bundle'        => '产品管理',
        'title'         => '产品管理',
        'description'   => '产品一览',
    ),
    'product_add' => array(
        'bundle'        => '产品管理',
        'title'         => '添加产品',
        'description'   => '',
    ),
    'product_edit' => array(
        'bundle'        => '产品管理',
        'title'         => '修改产品',
        'description'   => '',
    ),
    'product_delete' => array(
        'bundle'        => '产品管理',
        'title'         => '删除产品',
        'description'   => '',
    ),
));

