<?php
/*
 本代码由 焕岱科技 创建
 技术支持 WX：15285007200
 严禁反编译、逆向等任何形式的侵权行为，违者将追究法律责任
*/

namespace app\api\controller\card;

use app\api\controller\Base;
use think\Db;
use app\common\model\bbfxshop\User;


class Order extends Base
{
    protected $noNeedLogin = ['index'];
    protected $noNeedRight = ['*'];
    
    public $model = null;
    public function _initialize(){
        parent::_initialize();
        $this->model = new \app\common\model\bbfxshop\Card;
    }
    
    public function getList(){
        $list = Db::name("bbfx_member_card_order")->where(["uniacid"=>UNIACID,'user_id'=>$this->user['id'],'status'=>1])->select();
        if(empty($list)){
            __error("暂无记录！");
        }
        
        foreach ($list as $key => &$val){
            $val['createtime'] = date("Y-m-d H:i:s",$val['createtime']);
        }
        unset($val);
        
        __success("操作成功",['list'=>$list]);
    }
    
    public function submit(){
        $params = $this->paramPost(['member_card_id/d']);
        
        $card = Db::name("bbfx_member_card")->where(['id'=>$params['member_card_id']])->find();
        
        if(empty($card)){
            __error("会员不存在");
        }
        
        $card_order = Db::name("bbfx_member_card_order")->where(['uniacid'=>UNIACID,'user_id'=>$this->user['id'],'member_card_id'=>$card['id'],'status'=>1])->find();
        if(!empty($card_order)){
            if($card_order['endtime'] == -1 || $card_order['endtime'] > time()){
                __error("会员卡未到期");
            }
        }
        
        try {
            Db::startTrans();
            $order_no = date('YmdHis').random(8,true);  
            $data = array(
                "uniacid"=>UNIACID,
                "order_no"=>$order_no,
                "user_id"=>$this->user['id'],
                "price"=>$card['price'],
                "title"=>$card['name'],
                "member_card_id"=>$card['id'],
                "info"=>iserializer($card),
                "sup_path"=>$this->user['sup_path'],
                "createtime"=>time()
            );
            
            $order_id = Db::name("bbfx_member_card_order")->insertGetId($data);
            
            Db::commit();
        } 
        catch (\Exception $e) {
            Db::rollback();
        	$msg = $e->getMessage();
        	
        	__error($msg);
        }
        
        \app\common\model\bbfxshop\Fenxiao::settlement($order_id,1);
        
        __success("操作成功",['order_no'=>$order_no]);
    }
}