<?php
/**
 * lionfish 商城系统
 *
 * ==========================================================================
 * @link      http://www.liofis.com/
 * @copyright Copyright (c) 2015 liofis.com. 
 * @license   http://www.liofis.com/license.html License
 * ==========================================================================
 *
 * @author    fish 353399459@qq.com
 *
 */
namespace Seller\Controller;

/**
 * @author yj
 * @desc 虚拟卡密后台控制器
 * Class VirtualCardController
 * @package Seller\Controller
 */
class VirtualcardController extends CommonController{
	
	protected function _initialize(){
		parent::_initialize();
	}
	
	public function index(){
        $_GET['goods_type'] = 'virtualcard';

        $Goods_controller = A('Goods');

        $Goods_controller->index();
    }

    public function addgoods()
    {
        $_GET['goods_type'] = 'virtualcard';

        $Goods_controller = A('Goods');

        $Goods_controller->addgoods();
    }

    public function edit()
    {
        $_GET['goods_type'] = 'virtualcard';

        $Goods_controller = A('Goods');

        $Goods_controller->edit();
    }

    /**
     * @author yj
     * @desc
     */
    public function config()
    {
        $_GPC = I('request.');

        if (IS_POST) {

            $data = ((is_array($_GPC['parameter']) ? $_GPC['parameter'] : array()));

            $data['isopen_virtualcard'] = isset($data['isopen_virtualcard']) ? $data['isopen_virtualcard']:0;
            //是否参与分销
            $data['virtualcard_is_takecommiss'] = isset($data['virtualcard_is_takecommiss']) ? $data['virtualcard_is_takecommiss']:0;

            //0 横向， 1左右布局
            $data['virtualcard_layout'] = isset($data['virtualcard_layout']) ? $data['virtualcard_layout']:0;

            $data['is_open_virtualcard_show'] = isset($data['is_open_virtualcard_show']) ? $data['is_open_virtualcard_show']:0;
            $data['virtualcard_name_modify'] = isset($data['virtualcard_name_modify']) ? $data['virtualcard_name_modify']:'';
            $data['iscan_virtualcard_refund'] = isset($data['iscan_virtualcard_refund']) ? $data['iscan_virtualcard_refund']:0;
            //兑换 防止刷 分钟
            $data['virtcard_flush_limit_miniter'] = isset($data['virtcard_flush_limit_miniter']) ? $data['virtcard_flush_limit_miniter']:0;
            //兑换错误几次
            $data['virtcard_flush_error_timers'] = isset($data['virtcard_flush_error_timers']) ? $data['virtcard_flush_error_timers']:0;
            //冻结几小时
            $data['virtcard_flush_error_timers'] = isset($data['virtcard_flush_error_timers']) ? $data['virtcard_flush_error_timers']:0;
            //礼品卡首页入口封面
            $data['virtualcard_index_coming_img'] = isset($data['virtualcard_index_coming_img']) ? $data['virtualcard_index_coming_img']:'';

            $data['virtcard_share_title'] = isset($data['virtcard_share_title']) ? $data['virtcard_share_title']:'';
            $data['virtcard_share_img'] = isset($data['virtcard_share_img']) ? $data['virtcard_share_img']:'';
            $data['virtcard_publish'] = isset($data['virtcard_publish']) ? $data['virtcard_publish']:'';
            $data['virtcard_top_banner'] = isset($data['virtcard_top_banner']) ? $data['virtcard_top_banner']:'';

            D('Seller/Config')->update($data);

            show_json(1,  array('url' => $_SERVER['HTTP_REFERER']) );
            die();

        }

        $data = D('Seller/Config')->get_all_config();
        $this->data = $data;

        $this->display();
    }

    /**
     * @author yj
     * @desc 兑换码记录
     */
    public function exchange_code()
    {
        $_GPC = I('request.');

        $condition = '  ';
        $pindex    = max(1, intval($_GPC['page']));
        $psize     = 20;

        if (!empty($_GPC['keyword'])) {
            $_GPC['keyword'] = trim($_GPC['keyword']);
            $condition .= ' and code_name like "%'.$_GPC['keyword'].'%"';
        }



        $list = M()->query('SELECT * FROM ' . C('DB_PREFIX') . "lionfish_comshop_virtualcard_codes 
			WHERE 1  " . $condition . ' order by  id desc limit ' . (($pindex - 1) * $psize) . ',' . $psize);

        if( !empty($list) )
        {
            foreach( $list as &$val )
            {
                if( $val['effect_type'] == 0 )
                {
                    $val['effect_name'] = '永久有效';
                }else if( $val['effect_type'] == 1 )
                {
                    $val['effect_name'] = '购买后'.$val['effect_days'].'天有效';
                }
                $val['money_format'] = round( $val['code_money'], 2);

                $has_use_count = D('Seller/VirtualCard')->getCodeUsedCount( $val['id'] );
                $un_use_count = D('Seller/VirtualCard')->getCodeUnUseCount( $val['id'] );
                $invalid_count = D('Seller/VirtualCard')->getCodeinvalidCount( $val['id'] );

                $val['has_use_count'] = $has_use_count;
                $val['un_use_count'] = $un_use_count;
                $val['invalid_count'] = $invalid_count;
                $val['goods_count'] = D('Seller/VirtualCard')->getGoodsVirtualCardCountByCodeId( $val['id'] );

            }
        }

        $total_arr = M()->query('SELECT count(1) as count FROM ' . C('DB_PREFIX'). 'lionfish_comshop_virtualcard_codes WHERE 1  ' . $condition );

        $total = $total_arr[0]['count'];

        $pager = pagination2($total, $pindex, $psize);

        $this->list = $list;
        $this->pager = $pager;
        $this->_GPC = $_GPC;

        include $this->display();
    }

    public function changecode()
    {

        $id = I('request.id');

        //ids
        if (empty($id)) {
            $ids = I('request.ids');

            $id = ((is_array($ids) ? implode(',', $ids) : 0));
        }

        if (empty($id)) {
            show_json(0, array('message' => '参数错误'));
        }

        $type  = I('request.type');
        $value = I('request.value');

        if (!(in_array($type, array('state')))) {
            show_json(0, array('message' => '参数错误'));
        }

        $items = M('lionfish_comshop_virtualcard_codes')->where( array('id' => array('in', $id)) )->select();

        foreach ($items as $item) {

            M('lionfish_comshop_virtualcard_codes')->where( array('id' => $item['id']) )->save(  array($type => $value) );
        }

        show_json(1 , array('url' => $_SERVER['HTTP_REFERER']));

    }

    /**
     * @author yj
     * @desc 删除code
     */
    public function deletecode()
    {
        M()->startTrans();

        $id = I('request.id');

        //ids
        if (empty($id)) {
            $ids = I('request.ids');

            $id = ((is_array($ids) ? implode(',', $ids) : 0));
        }

        if (empty($id)) {
            M()->rollback();
            show_json(0, array('message' => '参数错误'));
        }


        $items = M('lionfish_comshop_virtualcard_codes')->where( array('id' => array('in', $id)) )->select();

        foreach ($items as $item) {
            $goods_code_info = D('Seller/VirtualCard')->getGoodsVirtualCardInfoByCodeId( $item['id'] );

            if( !empty($goods_code_info) )
            {
                M()->rollback();
                show_json(0, array('message' => 'code:'.$item['code_name'].' 已关联商品，无法删除'));
            }
            M('lionfish_comshop_virtualcard_codes')->where( array('id' => $item['id']) )->delete();
        }
        M()->commit();

        show_json(1 , array('url' => $_SERVER['HTTP_REFERER']));

    }

    /**
     * @author yj
     * @desc 添加编辑兑换码
     */
    public function addCode()
    {

        $id = I('request.id');
        if (!empty($id)) {
            $item = M('lionfish_comshop_virtualcard_codes')->where( array('id' => $id) )->find();
            $this->item = $item;
        }

        if (IS_POST) {
            $data = I('request.data');

            if( empty($data['code_name']) )
            {
                show_json(0, array('message' => '兑换码名称不能为空' ));
            }

            if( $data['effect_type'] == 1 && ( empty($data['effect_days'])  || $data['effect_days'] < 1 ) )
            {
                show_json(0, array('message' => '兑换码有效期必须大于1天' ));
            }

            if( ( empty($data['code_money'])  || $data['code_money'] <= 0 ) )
            {
                show_json(0, array('message' => '兑换面额必须大于0元' ));
            }

            //show_json(0, array('message' => 'code:'.$item['code_name'].' 已关联商品，无法删除'));

            D('Seller/VirtualCard')->updateCode($data );
            if( empty($id) )
            {
                show_json(1 , array('url' => U('Virtualcard/exchange_code') ));
            }else{
                show_json(1 , array('url' => $_SERVER['HTTP_REFERER']));
            }

        }

        $this->display();
    }

    public function orderlist()
    {
        $_GET['virtualcard_order'] = '1';

        $Goods_controller = A('Order');

        $Goods_controller->index();
    }

    public function exchangerecord()
    {
        $_GPC = I('request.');


        $starttime_arr = I('get.time');

        $starttime = isset($starttime_arr['start']) ? strtotime($starttime_arr['start']) : strtotime(date('Y-m-d'.' 00:00:00')) - 86400  * 30;

        $endtime = isset($starttime_arr['end']) ? strtotime($starttime_arr['end']) : strtotime(date('Y-m-d'.' 23:59:59')) +1;

        $this->starttime = $starttime;
        $this->endtime = $endtime;

        $condition = "  and addtime >= {$starttime}  and addtime < {$endtime} ";
        $pindex    = max(1, intval($_GPC['page']));
        $psize     = 20;

        if (!empty($_GPC['keyword'])) {
            $_GPC['keyword'] = trim($_GPC['keyword']);
            $condition .= ' and code_sn like "%'.$_GPC['keyword'].'%"';
        }

        $code_id = $_GPC['code_id'];
        $this->code_id = $code_id;

        if( isset($code_id) && $code_id > 0 )
        {
            $condition .= "  and code_id = {$code_id} ";
        }

        $list = M()->query('SELECT * FROM ' . C('DB_PREFIX') . "lionfish_comshop_virtualcard_userecord  
			WHERE 1  " . $condition . ' order by id desc limit ' . (($pindex - 1) * $psize) . ',' . $psize);


        $total_arr = M()->query('SELECT count(1) as count FROM ' . C('DB_PREFIX'). 'lionfish_comshop_virtualcard_userecord WHERE 1  ' . $condition );

        $total = $total_arr[0]['count'];

        $pager = pagination2($total, $pindex, $psize);

        if( !empty($list) )
        {
            foreach( $list as $key => $val )
            {
                $order_virtualcard_info = M('lionfish_comshop_order_virtualcard')->where(['code_sn' => $val['code_sn']])->find();
                //buy_user_id
                $buy_user_id = $order_virtualcard_info['buy_user_id'];
                $buy_user_info = M('lionfish_comshop_member')->where(['member_id' => $buy_user_id ])->find();

                $use_user_id = $val['use_user_id'];
                $use_user_info = M('lionfish_comshop_member')->where(['member_id' => $use_user_id ])->find();
                //use_user_id

                $val['buy_user_info'] = $buy_user_info;
                $val['use_user_info'] = $use_user_info;
                $val['adddate'] = date('Y-m-d H:i:s', $val['addtime'] );

                $list[$key] = $val;
            }
        }

        $this->list = $list;
        $this->pager = $pager;
        $this->_GPC = $_GPC;

        include $this->display();
    }

}
?>