<?php

namespace App\Http\Controllers\WeChat\WeChatPush;

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

class WeChatPushController extends Controller
{
	// 列表每页显示数据个数
	protected $show_count = 10;
	// protected $domain_url = 'https://xm.bluearp.com';//域名网址
	protected $domain_url = 'https://xmtest.bluearp.com';//域名网址
	public function accredit(Request $request)
	{
		$input = $request->all();
		if (empty($input['code'])) {
			header("Location:https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx7c45128ab7710f54&redirect_uri=".config('apisystem.server_name_https')."/index.php/WeChatPush/accredit&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect");
			exit;
		} else {
			//获取用户授权信息
			$code = $input['code']; //前端传来的code值
			$appid = "wx7c45128ab7710f54";
			$appsecret = "a92d64dd5fcf2d72cd12df9aeb9c7a5a";
			$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('admin_master')
					->where("adma_openid", $jsoninfo['openid'])
					->where('adma_binding_state', '1')
					->select('adma_id', 'adma_lasttime', 'adma_phone', 'adma_type')
					->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.accredit', $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']) || !isset($input['password'])) {
			return response()->json(['code' => 500, 'msg' => '参数错误', 'data' => '']);
		}
		$data['time'] = date('Y-m-d H:i:s');
		$data['request'] = $input;
		$data['function'] = 'weChatBinding';
		logRecord($data, 'weixin_log', 2);
		if ($request['type'] == 1) {
			// 查询账号id
			$id = DB::table('admin')
				->where("adm_phone", $input['phone'])
				->where("adm_password", md5($input['password'] . 'faster123456'))
				->value('adm_id');
		} else {
			// 查询账号id
			$id = DB::table('business_account')
				->where("buac_phone", $input['phone'])
				->where("buac_password", md5($input['password'] . 'faster123456'))
				->value('buac_id');
		}

		if (empty($id)) {
			return response()->json(['code' => 500, 'msg' => '账号或密码错误', 'data' => '']);
		} else {
			$poss['adma_adm_id'] = $id;
			$poss['adma_openid'] = $input['openid'];
			$poss['adma_phone'] = $input['phone'];
			$poss['adma_lasttime'] = date('Y-m-d H:i:s');

			//验证账号是否存在绑定记录
			$adma_id = DB::table('admin_master')
				->where("adma_openid", $input['openid'])
				->where("adma_adm_id", $id)
				->where("adma_type", $request['type'])
				->select('adma_id', 'adma_binding_state')
				->first();
			if (empty($adma_id)) {
				if (!empty($input['nickname'])) {
					$poss['adma_nickmame'] = $input['nickname'];
					$poss['adma_sex'] = $input['sex'];
					$poss['adma_province'] = $input['province'];
					$poss['adma_city'] = $input['city'];
					$poss['adma_headimgurl'] = $input['headimgurl'];
					$poss['adma_follow'] = '2';
					$poss['adma_type'] = $request['type'];//1技师绑定2合作商用户绑定
				}
				$res = DB::table('admin_master')->insert($poss);
				if ($res) {
					return response()->json(['code' => 200, 'msg' => '添加成功', 'data' => '']);
				} else {
					return response()->json(['code' => 500, 'msg' => '添加失败', 'data' => '']);
				}
			} else {
				$adma_id = $this->objectToArray($adma_id);
				if ($adma_id['adma_binding_state'] == '1') {
					return response()->json(['code' => 200, 'msg' => '添加成功', 'data' => '']);
				} else {
					//解绑记录恢复处理逻辑
					if (!empty($input['nickname'])) {
						$poss['adma_nickmame'] = $input['nickname'];
						$poss['adma_sex'] = $input['sex'];
						$poss['adma_province'] = $input['province'];
						$poss['adma_city'] = $input['city'];
						$poss['adma_headimgurl'] = $input['headimgurl'];
						$poss['adma_follow'] = '2';
					}
					$poss['adma_binding_state'] = '1';
					$res = DB::table('admin_master')
						->where('adma_id', $adma_id['adma_id'])
						->where('adma_type', $request['type'])
						->update($poss);
					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['adma_binding_state'] = '2';
			$res = DB::table('admin_master')
				->where('adma_id', $input['adma_id'])
				->where("adma_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;
	}
}
