<?php


namespace app\common\repositories\system\serve;

use app\common\dao\system\serve\ServeOrderDao;
use app\common\repositories\BaseRepository;
use app\common\repositories\store\product\ProductCopyRepository;
use ln\services\PayService;
use think\exception\ValidateException;
use think\facade\Cache;
use think\facade\Db;

class ServeOrderRepository extends BaseRepository
{
    protected $dao;

    public function __construct(ServeOrderDao $dao)
    {
        $this->dao = $dao;
    }

    public function QrCode(int $merId, array $data)
    {

        $ret = app()->make(ServeMealRepository::class)->get($data['meal_id']);
        if(!$ret)  throw new ValidateException('数据不存在');
        $key = 'Meal_'.$merId.'_'.$data['meal_id'].'_'.date('YmdH',time());

        $arr = [
            'meal_id' => $ret['meal_id'],
            'name'    => $ret['name'],
            'num'     => $ret['num'],
            'price'   => $ret['price'],
            'type'    => $ret['type'],
        ];
        if(!$result = Cache::store('file')->get($key)){
            $order_sn = $this->setOrderSn();
            $param = [
                'status' => 0,
                'is_del' => 0,
                'mer_id' => $merId,
                'type'   => $ret['type'],
                'meal_id'=> $ret['meal_id'],
                'pay_type' => $data['pay_type'],
                'order_sn' => $order_sn,
                'attach' => 'meal',
                'order_info' => json_encode($arr,JSON_UNESCAPED_UNICODE),
                'pay_price' => $ret['price'],
                'body' => $order_sn,
            ];

            $type = $data['pay_type'] == 1 ? 'weixinQr' : 'alipayQr';
            $service = new PayService($type,$param);
            $code = $service->pay(null);

            $endtime = time() + 1800 ;
            $result = [
                'config' => $code['config'],
                'endtime'=> date('Y-m-d H:i:s',$endtime),
            ];
            Cache::store('file')->set($key,$result,30);
            $param['key'] = $key;
            Cache::store('file')->set($order_sn,$param,60 * 24);
        }
        return $result;
    }

    public function paySuccess($data)
    {
        $dat = Cache::store('file')->get($data['order_sn']);
        $get = $this->dao->getWhere(['order_sn' => $data['order_sn']]);
        if(!$get){
            Db::transaction(function () use($data,$dat){

                $key = $dat['key'];
                unset($dat['attach'],$dat['body'],$dat['key']);

                $dat['status'] = 1;
                $this->dao->create($dat);

                $info = json_decode($dat['order_info']);
                app()->make(ProductCopyRepository::class)->add([
                    'type'  => $dat['type'] == 1 ? 'pay_copy' : 'pay_dump',
                    'num'   => $info->num,
                    'info'   => $dat['order_info'],
                    'message' => $dat['type'] == 1 ? '购买复制商品套餐' : '购买电子面单套餐',
                ],$dat['mer_id']);

                Cache::store('file')->delete($data['order_sn']);
                Cache::store('file')->delete($key);
            });
        }
    }

    public function setOrderSn()
    {
        list($msec, $sec) = explode(' ', microtime());
        $msectime = number_format((floatval($msec) + floatval($sec)) * 1000, 0, '', '');
        $orderId = 'cs' . $msectime . mt_rand(10000, max(intval($msec * 10000) + 10000, 98369));
        return $orderId;
    }

    public function getList(array $where, int $page, int $limit)
    {
        $where['is_del'] = 0;
        $query = $this->dao->getSearch($where)->with([
            'merchant' => function($query){
                $query->field('mer_id,mer_name');
            }
        ])->order('create_time DESC');
        $count = $query->count();
        $list = $query->page($page, $limit)->select();
        return compact('count','list');
    }

}
