<?php

namespace App\Http\Controllers\WeChat\WeChatPush;

use Illuminate\Support\Facades\View;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;

// 个人会员授权绑定
class WeChatMemberPushController extends Controller
{
	// 列表每页显示数据个数
	protected $show_count = 10;
	public function member(Request $request)
	{
		$appid = config('wechat.bjmd.appid');
		$appsecret = config('wechat.bjmd.appsecret');//获取开发者密码
		$input = $request->all();
		if (empty($input['code'])) {
			header("Location:https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".config('apisystem.server_name_https')."/index.php/WeChatMemberPush/member&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect");
			exit;
		} else {
			//获取用户授权信息
			$code = $input['code']; //前端传来的code值
			$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $appid . "&secret=" . $appsecret . "&code=" . $code . "&grant_type=authorization_code";
			//https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxf5d6f1ae7ee63d36&redirect_uri=https://mktest.bluearp.com/index.php/WeChatPush/accredit&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
			$result = file_get_contents($url);
			$jsoninfo = json_decode($result, true);
			if (!empty($jsoninfo['openid'])) {
				//验证该微信是否已经存在未解绑信息
				$adma_id = DB::table('member_weixin')
					->where("mewe_openid", $jsoninfo['openid'])
					->where('mewe_binding_state', '1')
					->select('mewe_id', 'mewe_binding_state', 'mewe_phone as adma_phone', 'mewe_lasttime as adma_lasttime')
					->first();
				$adma_id = $this->objectToArray($adma_id);
				if ($adma_id) {
					$poss = $adma_id;//将查询出的数据赋值给前端页面
					$poss['openid'] = $jsoninfo['openid'];
					$poss['type'] = '3';
				} else {
					//获取用户微信账号信息（昵称，地址，头像）
					$url = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $jsoninfo['access_token'] . "&openid=" . $jsoninfo['openid'] . "&lang=zh_CN";
					$user = file_get_contents($url); //运行curl
					$user = json_decode($user, true);
					$poss['type'] = '1';
					$poss['openid'] = $jsoninfo['openid'];
					if (!empty($user['nickname'])) {
						$poss['nickname'] = $user['nickname'];
						$poss['sex'] = $user['sex'];
						$poss['province'] = $user['province'];
						$poss['city'] = $user['city'];
						$poss['headimgurl'] = $user['headimgurl'];
					} else {
						$poss['nickname'] = '';
						$poss['sex'] = '';
						$poss['province'] = '';
						$poss['city'] = '';
						$poss['headimgurl'] = '';
					}
				}
				//return view('WeChatPush.accredit',['name'=>'aaaaa','openid'=>'bbbbb','nickname'=>'ccccc','sex'=>'ddddd','province'=>'ffffff','city'=>'ggggg','headimgurl'=>'iiiiiii']);
			} else {
				$poss['type'] = '2';
			}
			$poss['config_url'] = config('apisystem.server_name_https');//域名网址
			return view('WeChatPush.member', $poss);
		}
	}

	/**|---------------------------------------------------------------------------------
	 * @name 信息绑定
	 * @param Request phone 手机号
	 * @param Request password 密码
	 * @param Request openid 微信标识
	 * @param Request nickname 微信昵称
	 * @param Request sex 性别
	 * @param Request province 用户省份
	 * @param Request city 用户城市
	 * @param Request headimgurl 用户头像
	 * |---------------------------------------------------------------------------------
	 */
	public function weChatBinding(Request $request)
	{
		$input = $request->all();
		if (!isset($input['phone']) || mb_strlen($input['phone']) != 11) {
			return response()->json(['code' => 500, 'msg' => '请输入正确的手机号', 'data' => '']);
		}
		$find_member = DB::table('member_weixin')
			->where("mewe_openid", $input['openid'])
			->select('mewe_id', 'mewe_binding_state', 'mewe_phone')
			->first();
		// $data['time'] = date('Y-m-d H:i:s');
		// $data['request'] = $input;
		// $data['function'] = 'weChatBinding';
		// logRecord($data, 'weixin_log', 2);
		if (!empty($find_member) && $find_member->mewe_binding_state == 1) {
			return response()->json(['code' => 200, 'msg' => '绑定成功', 'data' => '']);
		}
		$mewe_data['mewe_binding_state'] = 1;
		$mewe_data['mewe_lasttime'] = date('Y-m-d H:i:s');
		$mewe_data['mewe_phone'] = $input['phone'];
		$mewe_data['mewe_nickmame'] = $input['nickname'];
		$mewe_data['mewe_headimgurl'] = $input['headimgurl'];
		$mewe_data['mewe_province'] = $input['province'] ? $input['province'] : '';
		$mewe_data['mewe_city'] = $input['city'] ? $input['city'] : '';
		if ($find_member) {
			$res = DB::table('member_weixin')
				->where("mewe_id", $find_member->mewe_id)
				->where("mewe_openid", $input['openid'])
				->update($mewe_data);
		} else {
			$mewe_data['mewe_openid'] = $input['openid'];
			$res = DB::table('member_weixin')->insert($mewe_data);
		}
		if ($res) {
			return response()->json(['code' => 200, 'msg' => '绑定成功', 'data' => '']);
		} else {
			return response()->json(['code' => 500, 'msg' => '绑定失败', 'data' => '']);
		}
	}

	/**|---------------------------------------------------------------------------------
	 * @name 解除绑定
	 * @param Request phone 手机号
	 * @param Request openid 微信标识
	 * @param Request adma_id 数据id
	 * |---------------------------------------------------------------------------------
	 */
	public function removeData(Request $request)
	{
		$input = $request->all();
		if (isset($input['adma_id']) && isset($input['phone']) && isset($input['openid'])) {
			$poss['mewe_binding_state'] = '2';
			$res = DB::table('member_weixin')
				->where('mewe_id', $input['adma_id'])
				->where("mewe_openid", $input['openid'])
				->update($poss);
			// $data['request'] = $input;
			// $data['poss'] = $poss;
			// $data['time'] = date('Y-m-d H:i:s');
			// logRecord($data, 'weixin_log', 2);
			if ($res) {
				return response()->json(['code' => 200, 'msg' => '操作成功', 'data' => '']);
			} else {
				return response()->json(['code' => 500, 'msg' => '操作失败', 'data' => '']);
			}
		} else {
			return response()->json(['code' => 500, 'msg' => '缺少必要参数', 'data' => '']);
		}
	}

	/**|---------------------------------------------------------------------------------
	 * @name 添加推送信息
	 * @param Request pushtype 推送类型
	 * @param Request wor_number 工单号
	 * @param Request ord_number 订单单号
	 * @param Request order_type 工单类型
	 * @param Request admid 会员id
	 * @param Request user_name 用户姓名
	 * @param Request user_phone 用户电话
	 * @param Request user_dress 用户地址
	 * |---------------------------------------------------------------------------------
	 */
	public function inforPush(Request $request)
	{
		$input = $request->all();
		if (isset($input['pushtype'])) {
			//验证推送类型
			$pushtype = [1, 2]; //推送类型：1新订单2催单
			if (!in_array($input['pushtype'], $pushtype)) {
				return response()->json(['code' => 500, 'msg' => 'pushtype参数错误', 'data' => '']);
			}
			//新订单推送
			if ($input['pushtype'] == '1') {
				$master = DB::table('admin_master')
					->where("adma_adm_id", $input['adm_id'])
					->where("adma_follow", '2')
					->where("adma_binding_state", '1')
					->select("adma_openid")
					->get();
				if (!$master) {
					//无绑定信息添加记录
					$data['wep_wor_number'] = $input['wor_number'];
					$data['wep_ord_number'] = $input['ord_number'];
					$data['wep_adm_id'] = $input['adm_id'];
					$data['wep_weixindata'] = '无绑定微信';
					$data['wep_type'] = $input['pushtype'];
					DB::table('weixin_push')->insert($data);
					return response()->json(['code' => 500, 'msg' => '无绑定微信', 'data' => '']);
				} else {
					//验证微信授权
					//$redis = new Redis();
					//$redis->connect('127.0.0.1',6379);
					//$access_token= $redis->get('access_token');
					//if($access_token && $_GET['type']=='1'){
					//    $obj['access_token']=$access_token;
					//}else {
					$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxf5d6f1ae7ee63d36&secret=94f3ba89ebed9e2f86c9b8a045d0bf75'; //生产环境
					$output = file_get_contents($url); //运行curl
					$obj = json_decode($output, true);
					//    if(!empty($obj['access_token'])){
					//        $redis->set('access_token',$obj['access_token']);
					//        $redis->expire('access_token', 6480);
					//    }
					//}
					//$redis->close();
					if (empty($obj['access_token'])) {
						//授权失败处理逻辑
						$data['wep_wor_number'] = $input['wor_number'];
						$data['wep_ord_number'] = $input['ord_number'];
						$data['wep_adm_id'] = $input['adm_id'];
						//$data['wep_openid']='无绑定微信';
						$data['wep_weixindata'] = 'token错误';
						$data['wep_type'] = $input['pushtype'];
						DB::table('weixin_push')->insert($data);
						return response()->json(['code' => 500, 'msg' => 'token错误', 'data' => '']);
					} else {
						//生成模板信息
						$url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $obj['access_token'];
						$poss['template_id'] = "chXAuZp-iFAi6LAGLoV4GMJOIveoOEuu08DARAxM_j8";
						$first['value'] = "您有新的工单";
						$keyword1['value'] = $input['wor_number'];
						$keyword2['value'] = $input['order_type'];
						$keyword3['value'] = $input['user_name'];
						$keyword4['value'] = $input['user_phone'];
						$remark['value'] = $input['user_dress'];
						$data['first'] = $first;
						$data['keyword1'] = $keyword1;
						$data['keyword2'] = $keyword2;
						$data['keyword3'] = $keyword3;
						$data['keyword4'] = $keyword4;
						$data['remark'] = $remark;
						$poss['data'] = $data;
						$master = $this->objectToArray($master);
						$push = 1;
						foreach ($master as $k => $v) {
							$poss['touser'] = $v['adma_openid'];
							$res = $this->https_post($url, json_encode($poss));
							//保存推送结果
							$datas['wep_wor_number'] = $input['wor_number'];
							$datas['wep_ord_number'] = $input['ord_number'];
							$datas['wep_adm_id'] = $input['adm_id'];
							$datas['wep_openid'] = $v['adma_openid'];
							$datas['wep_weixindata'] = $res;
							$datas['wep_type'] = $input['pushtype'];
							$rea = DB::table('weixin_push')->insert($datas);
							if ($rea) {
								$push = 2;
							}
						}
						if ($push == 2) {
							return response()->json(['code' => 200, 'msg' => '推送成功', 'data' => '']);
						} else {
							return response()->json(['code' => 500, 'msg' => '推送失败', 'data' => '']);
						}
					}
				}
			}
		} else {
			return response()->json(['code' => 500, 'msg' => '缺少pushtype', 'data' => '']);
		}
	}

	/**|---------------------------------------------------------------------------------
	 * @name  对象转数组
	 * @param $object 对象数据
	 * @return \Illuminate\Http\JsonResponse
	 * @author dou <2020/9/30 16:35>
	 * |---------------------------------------------------------------------------------
	 */
	public function objectToArray($object)
	{
		//先编码成json字符串，再解码成数组
		return json_decode(json_encode($object), true);
	}

	/**|---------------------------------------------------------------------------------
	 * @name  https协议post传参
	 * @param $url 请求链接
	 * @param $data 请求数据
	 * @return \Illuminate\Http\JsonResponse
	 * @author dou <2020/11/9 17:10>
	 * |---------------------------------------------------------------------------------
	 */
	public function https_post($url, $data)
	{
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		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);
		curl_close($curl);
		return $output;
	}
}
