<?php

namespace app\controller\api\warehouse;
use app\common\repositories\store\product\ProductRepository;
use crmeb\basic\BaseController;
use think\facade\Cache;
use think\facade\Db;

class Recommend extends BaseController
{
    public function lsts()
    {
        $today = date('Y-m-d');
        $res = Db::name('Recommend') -> where('status',1) -> where("show_time <= '$today'") -> group('show_time') -> order('show_time desc') -> limit(10) -> field('show_time') -> select() -> toArray();
        $date = array_column($res,'show_time');
        $list = Db::name('Recommend') -> where('status',1) -> whereIn('show_time',$date) -> field("id,recommend_image,show_time") -> select() -> toArray();
        return app('json')->success($this -> order($list,$date));
    }

    public function detail(){
        $data = $this -> request -> params(['id']);
        if(empty($data['id'])){
            return app('json')->fail('参数错误');
        }
        $detail = Db::name('Recommend')
            -> alias('r')
            -> join('StoreProduct sp','r.product_id = sp.product_id')
            -> where('id',$data['id'])
            -> field('r.name,r.product_id,r.show_time,r.recommend_image,r.details,r.images,sp.image,sp.store_name,sp.price,sp.dc_price,sp.type,sp.ot_price')
            -> find();

        $detail['images'] = json_decode($detail['images'],true);
        $ProductRepository=app() -> make(ProductRepository::class);
        $detail['yanglaojin'] =$ProductRepository->yanglaojin($detail['product_id'],0,1);
        return app('json')->success($detail);

    }

    public function share(){
        $data = $this -> request -> params(['id']);
        if(empty($data['id'])){
            return app('json')->fail('参数错误');
        }
        $detail = Db::name('Recommend')
            -> where('id',$data['id'])
            -> field('name,recommend_image,details')
            -> find();

        return app('json')->success($detail);
    }

    public function order($list,$date){
        $new = [];
//        $today = date('Y-m-d');
        foreach($date as $value){
            $news = [];
            $d = explode('-',$value);
            $news['date'] = $d[1].'月'.$d[2].'日';
            foreach ($list as $key => $v){
                if($v['show_time'] == $value){
                    $news['list'][] = $v;
                }
            }
            $new[] = $news;
            unset($news);
        }
        return $new;
    }

    public function get_access_token(){
        $access_token = Cache::get('wx9909df446471d46b_access_token');
        if ($access_token)
            return $access_token;
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx9909df446471d46b&secret=9f1bb3a062b163fa5a780c976092f009";
        $res = curlGet($url);
        Cache::set('wx9909df446471d46b_access_token', $res['access_token'], $res['expires_in']);
        return $res['access_token'];
    }

    public function get_ticket(){
        $ticket = Cache::get('wx9909df446471d46b_ticket');
        if($ticket)
            return $ticket;
        $access_token = $this -> get_access_token();
        $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=$access_token&type=jsapi";
        $res = curlGet($url);
        Cache::set('wx9909df446471d46b_ticket', $res['ticket'], $res['expires_in']);
        return $res['ticket'];
    }

    public function wx_config(){
        $data = $this -> request -> params(['url']);
        if(empty($data['url'])){
            return app('json')->fail('参数错误');
        }
        $noncestr = $this->getRandStr(16);//随机字符串
        $jsapi_ticket = $this -> get_ticket();
        $timestamp = time();
        $url = $data['url'];
        $sign = sha1("jsapi_ticket={$jsapi_ticket}&noncestr={$noncestr}&timestamp={$timestamp}&url={$url}");
        $data = [
            'timestamp' => $timestamp,
            'noncestor' => $noncestr,
            'signature' => $sign,
        ];
        return app('json')->success($data);
    }
    /**
     * 随机字符串
     */
    public function getRandStr($length)
    {
        //字符组合
        $str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $len = strlen($str) - 1;
        $randstr = '';
        for ($i = 0; $i < $length; $i++) {
            $num = mt_rand(0, $len);
            $randstr .= $str[$num];
        }
        return $randstr;
    }

    public function add_madia(){
        $data = $this -> request -> params(['images']);
        if(empty($data['images'])){
            return app('json')->fail('参数错误');
        }
        $images = $data['images'];
        $id = [];
        foreach($images as $value){
            if(strpos($value,'https://cdn.bjtdba.com') !== false || strpos($value,'http://cdn.bjtdba.com') !== false ){
                $image = str_replace('https://cdn.bjtdba.com','/data/store',$value);
                $image = str_replace('http://cdn.bjtdba.com','/data/store',$image);
                $access_token = $this -> get_access_token();
                $url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=$access_token&type=image";
                $data = ['media' =>  new \CURLFile($image)];

                $result = $this -> httpRequest($data,$url);
                $id[] = $result['media_id'] ?? json_encode($result);
            }
        }
        return app('json')->success($id);
    }


    public function httpRequest($data,$url){
//        $data = ['form-data' => $data];
//        if(is_array($data)){
//            $data = json_encode($data);
//        }
//        dump($data);
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER , true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
//        dump(curl_error($curl));
        curl_close($curl);
//        dump($output);
        return json_decode($output, true);

    }
}




