<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use think\Exception;

class UserCoupons extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = Db::name('user_coupons');
    }

    /**
     * 列表
     * @return void
     */
    public function getList()
    {
        try {
            $status = $this->request->param('status',1);//状态:1待使用,2已失效
            $userId = $this->auth->id;
            $companyId = $this->auth->company_id;
            $field = 'id,coupon_name,coupon_info,endtime,number,remain';
            $where['user_id'] = $userId;
            $where['company_id'] = $companyId;
            $whereOr = [];
            if ($status == 1) {
                $where['remain'] = ['gt',0];
            } else {
                $whereOr['remain'] = ['elt',0];
                $whereOr['endtime'] = ['lt',time()];
            }
            $result = $this->model->field($field)->where($where)->where(function($query) use ($whereOr){
                $query->whereOr($whereOr);
            })->order('createtime desc')->autopage()->select();

            if (!empty($result)) {
                foreach ($result as $key => &$value) {
                    !empty($value['endtime']) && $value['endtime'] = date('Y.m.d H:i:s',$value['endtime']);
                }
            }
            $this->success('获取成功',$result);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 核销码
     * @return void
     */
    public function writeOff()
    {
        try {
            $id = $this->request->param('id',0);
            $companyId = $this->auth->company_id;
            $userId = $this->auth->id;
            $where['id'] = $id;
            $where['company_id'] = $companyId;
            $where['user_id'] = $userId;
            $where['remain'] = ['gt',0];
            $modelData = $this->model->where($where)->find();
            if (empty($modelData)) {
                throw new Exception('未找到相关信息');
            }
            //验证
            if ($modelData['endtime'] < time() || $modelData['remain'] < 1) {
                throw new Exception('该券已无法使用');
            }
            $text = 'hexiaocoupon_'.$id;
            $logo = '';
            $filRoute = '/uploads/temp/';
            $saveDir = ROOT_PATH.'public\uploads\temp'.DS;
            $fileStr = md5('coupon_'.$id);
            $localpng = $saveDir.$fileStr.'.png';
            //验证存在直接返回
            $userCouponsUrl = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].$filRoute.$fileStr.'.png';
            if (!file_exists($localpng)) {
                build_qrcode($text, $logo, $saveDir,$fileStr);
            }
            $result = [
                'url' => $userCouponsUrl,
            ];
            $this->success('获取成功',$result);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }
}