<?php

namespace app\api\controller;

use QRcode;
use think\facade\Db;
use think\facade\Lang;

/**
 * ============================================================================
 * DSMall多用户商城
 * ============================================================================
 * 版权所有 2014-2028 长沙德尚网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.csdeshang.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * 代金券控制器
 */
class Voucher extends MobileMember {

    public function initialize() {
        parent::initialize();
    }


    /**
     * @api {POST} api/Voucher/voucher_tpl_list 代金券列表
     * @apiVersion 1.0.0
     * @apiGroup Voucher
     *
     * @apiParam {String} store_id 店铺ID
     * @apiParam {String} gettype 代金券类型
     *
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     * @apiSuccess {Object[]} result.voucher_list  代金券模板列表 （返回字段参考vouchertemplate）
     * @apiSuccess {String} result.voucher_list.vouchertemplate_enddate_text  代金券过期时间描述
     */
    public function voucher_tpl_list() {
        $param = array();
                $param['store_id']=input('param.store_id');
                $param['gettype']=input('param.gettype');
        $voucher_model = model('voucher');
        $templatestate_arr = $voucher_model->getTemplateState();
        $voucher_gettype_array = $voucher_model->getVoucherGettypeArray();

        $where = array();
        $where[]=array('vouchertemplate_state','=',$templatestate_arr['usable'][0]);
        $store_id = intval($param['store_id']);
        if ($store_id > 0) {
            $where[]=array('vouchertemplate_store_id','=',$store_id);
        }
        $where[] = array('vouchertemplate_gettype','in', array($voucher_gettype_array['points']['sign'], $voucher_gettype_array['free']['sign']));
        if ($param['gettype'] && in_array($param['gettype'], array('points', 'free'))) {
            $where[]=array('vouchertemplate_gettype','=',$voucher_gettype_array[$param['gettype']]['sign']);
        }
        $order = 'vouchertemplate_id asc';

        $voucher_list = $voucher_model->getVouchertemplateList($where, '*', 20, 0, $order);
        if ($voucher_list) {
            foreach ($voucher_list as $k => $v) {
                $v['vouchertemplate_limit'] = floatval($v['vouchertemplate_limit']);
                $v['vouchertemplate_enddate_text'] = $v['vouchertemplate_enddate'] ? @date('Y.m.d', $v['vouchertemplate_enddate']) : '';
                $voucher_list[$k] = $v;
            }
        }
        ds_json_encode(10000, '',array('voucher_list' => $voucher_list));
    }

    public function delete(){
        $id = input('param.id');
        $Vrordercode = Db::name('vrordercode');
        $voucher = $Vrordercode->where(['rec_id'=>$id])->find();
        if (!$voucher) {
            ds_json_encode(10001, '参数错误');
        }

        $result = $Vrordercode->where(['rec_id'=>$id])->update(['state'=>0]);
        if (!$result) {
            ds_json_encode(10001, '删除失败');
        }
        ds_json_encode(10000, '删除成功');
    }  
    /**
     * ******************************以下内容为非框架部分******************************************
     */

    /**
     * 测试消费卡券绑定操作
     */
    public function addVoucher()
    {
        $param = ['a'=>1, 'b'=>2, 'c'=>3];
        $buy_logic = model('voucher','logic');
        $memberId = $this->member_info['member_id'];
        $result = $buy_logic->getVoucherListByGood($param,$memberId);
        echo json_encode($result);
    }

    /**
     * 消费卡券列表
     */
    public function voucherList()
    {
        $param = $this->request->param();

        $page = empty($param['page']) ? 1 : $param['page'];
        $limit = empty($param['limit']) ? 10 : $param['limit'];
        $memberId = $this->member_info['member_id'];
//        $userId = $this->member_info['member_id'];
        $where = [];

        $where[] = ['voc.buyer_id','=',$memberId];

        $model = Db::name('vrordercode');

        if(!empty($param['voucher_type']) && $param['voucher_type'] !=0){
            $where[] = ['type','=',$param['voucher_type']];
        }
        $time = time();
        $where[] = ['vr_end_time','>',$time];
        if(isset($param['state'])){
            $where[] = ['voc.state','=',$param['state']];
        }
        if(!empty($param['tag_id'])){
            //商品id不为空
            $where[] = ['voc.order_id','=',$param['tag_id']];
            $count = 0;
            $query = $model->where($where);
        }else{
            $page = empty($param['page']) ? 1 : $param['page'];
            $limit = empty($param['limit']) ? 10 : $param['limit'];
            $count = $model->count();
            $query = $model->where($where)->page($page)->limit($limit);
        }
        $query = $query->order('voc.rec_id desc');
        $query = $query->alias('voc')->join('Vrorder v','v.order_id = voc.order_id');
        $list = $query->field('voc.*,v.order_sn,v.add_time')->select()->toArray();
        // var_dump($query->getLastsql());exit();


//        del_code_tmp();//清除二维码临时文件
//        $data = '哈哈哈你猜';
//        $ewm = ewm($data);
//        echo $ewm;exit;


        if(!empty($list)){
            foreach($list as $k=>$v){

                switch ($v['type']){
                    case 1:
                        $list[$k]['type_name'] = '卡号';
                        break;
                    case 2:
                        $list[$k]['type_name'] = '卡密';
                        break;
                    case 3:
                        $list[$k]['type_name'] = '二维码';
                        //二维码
                        // $this->del_code_tmp();//清除二维码临时文件
                        // $ewm = $this->ewm($v['content']);
                        // $list[$k]['qrcode_url'] = $ewm;
                        break;    
                    case 4:
                        $list[$k]['type_name'] = '条形码';    
                        break;
                    case 5:
                        $list[$k]['type_name'] = '动态码';    
                        break;
                }

                $list[$k]['expire_time'] = date('Y-m-d',$v['vr_end_time']);
                // $list[$k]['create_time'] = date('Y-m-d',$v['create_time']);
                $list[$k]['start_time'] = date('Y-m-d',$v['vr_start_time']);
                $list[$k]['add_time'] = date('Y-m-d',$v['add_time']);

            }
        }

        if (count($list) < $limit) {
            $hasMore = false;
        } else {
            $hasMore = true;
        }
        $data = [
            'count' => $count,
            'list' => $list,
            'hasmore' => $hasMore
        ];
        ds_json_encode(10000, '查询成功', $data);


    }



    
    //生成二维码
    //$type真输出，假返回地址
    function  ewm ($text,$type=true){
        $nums=time().'_'.mt_rand();
        //当前时间戳加随机数
        $size='6';
        $level='H';
        $padding=2;
        $root = $_SERVER['DOCUMENT_ROOT'];
        $QR=$root.'/code/tmp/'.$nums.'.png';
        include_once root_path(). 'extend/qrcode/phpqrcode.php';
        $re=\QRcode::png ($text,$QR,$level,$size,$padding);
        if ($type){
           // ob_end_clean();
            $domain = \think\facade\Request::domain();
            $abc =  $domain.'/code/tmp/'.$nums.'.png';
            return $abc;
        }else {
            return $QR;
        }
    }


    //删除临时二维码
    function  del_code_tmp (){
        //删除时间戳大于1分钟的内容
        $hostdir= 'code/tmp/';
        //获取文件目录的文件夹地址
        $filesnames=scandir($hostdir);
        foreach ($filesnames as $name){
            if (strstr($name,"_")){
                $tmp=explode("_",$name);
                if (time()-$tmp[0]>3600){
                    //如果拆分文件名时间戳大于当前时间30秒则删除
                    unlink($hostdir.$name);
                }
            }
        }
    }




    /**
     * 消费卡券详情
     */
    public function voucherInfo()
    {
        $param = $this->request->param();
        if(empty($param['id'])){
            ds_json_encode(10001, '参数丢失!');
        }
        $model = Db::name('sub_voucher');
        $memberId = $this->member_info['member_id'];
        $info = $model->where([
            ['member_id','=',$memberId],
            ['id','=',$param['id']]
        ])->find();
        $time = time();
        if(empty($info) || $info['expire_time'] < $time){
            ds_json_encode(10001, '卡券不存在或已过期!');
        }

        switch ($info['voucher_type']){
            case 1:
                $info['data_info'] = json_decode($info['content'],true);
                break;
            case 2:
                $info['data_info'] = json_decode($info['content'],true);
                break;
            case 3:
                //二维码
                $this->del_code_tmp();//清除二维码临时文件
                $ewm = $this->ewm($info['content']);
                $info['qrcode_url'] = $ewm;
                break;
        }
        $info['expire_time'] = date('Y-m-d H:i:s',$info['expire_time']);
        $info['start_time'] = date('Y-m-d H:i:s',$info['start_time']);
        ds_json_encode(10000, '查询成功', ['info' => $info]);
    }
}

?>
