<?php

namespace Addons\Inqunbao\Controller\Admin;

use Addons\Fission\Controller\H5\Fission;
use Models\BaseModel as Model;
use Session;
use Addons\Inqunbao\Helper;
use Addons\QyWechat\Helper as QyHelper;
use Addons\QyWechat\Services\QyWechatApi;
use Addons\QyWechat\Services\ProvidersApi;

class Inqunbao extends BaseAdmin
{

	public function create_mission()
	{
		$wid = Session::get('wid');
		$QyWechatApi = QyWechatApi::getInstance();
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid' => $wid]);
		$etApp = $QyWechatApi->get_qy_app($qyConfig->corp_id, $qyConfig->externalcontact_secret);
		$qyFission = new Model('qy_inqunbao');
		// dump($qyFission);die;
		$id = \Request::get(1);
		// dump($id);
		// die;
		if ($id) {
			$qyFission->find(['wid' => $wid, 'id' => $id]);
		}
		if (is_post()) {
			// dump($_POST);
			// // die;
			setApi();
			$type = 2;
			$scene = 2; //2-通过二维码联系
			$users = explode(',', $_POST['selectedUser']);
			if ($qyFission->id) {
				$qyFission->wid = $wid;
			} else {
				$qyFission->wid = $wid;
				$qyFission->state = '';
				$qyFission->config_id = '';
				$qyFission->qr_code = '';
				$qyFission->ctime = date('Y-m-d H:i:s');
			}
			$qyFission->name = $_POST['name'];
			$qyFission->users = json_encode($users, 320);
			$qyFission->skip_verify = $_POST['skip_verify'] ? 1 : 0;
			$qyFission->auto_label = $_POST['auto_label'] ? 1 : 0;
			$qyFission->select_label = json_encode(explode(',', $_POST['seleckedLable']), 320);
			$qyFission->end_time = strtotime($_POST['end_time']);
			$qyFission->target_number = $_POST['target_number'];
			$qyFission->new_friends = $_POST['new_friends'] ? 1 : 0;
			$qyFission->del_friends = $_POST['del_friends'] ? 1 : 0;
			$qyFission->lj_mode = $_POST['lj_mode'];
			$qyFission->lj_lxr = json_encode(explode(',', $_POST['lj_lxr']), 320);
			$qyFission->lj_qrcode = $_POST['lj_qrcode'];
			$qyFission->lj_link = $_POST['lj_link'];
			$qyFission->poster_avatar = $_POST['poster_avatar'] ? 1 : 0;
			$qyFission->poster_nickname = $_POST['poster_nickname'] ? 1 : 0;
			$qyFission->poster_imgurl = $_POST['poster_imgurl'];
			$qyFission->poster_coordinate = json_encode($_POST['coordinate']);
			$qyFission->forward_set = $_POST['forward_set'] ? 1 : 0;
			$qyFission->forward_text = $_POST['forward_text'];
			$qyFission->hy_text_content = $_POST['hy_text_content'];
			$qyFission->hy_link_title = $_POST['hy_link_title'];
			$qyFission->hy_link_desc = $_POST['hy_link_desc'];
			$qyFission->hy_link_picurl = $_POST['hy_link_picurl'];
			$qyFission->push_staff = $_POST['push_staff'] ? 1 : 0;
			$qyFission->push_customer = $_POST['push_customer'] ? 1 : 0;
			$qyFission->push_text_content = $_POST['push_text_content'];
			$qyFission->invitation_check = $_POST['invitation_check'];
			$qyFission->invitation_range = $_POST['invitation_range'];
			$qyFission->selected_et = json_encode(explode(',', $_POST['selected_et']), 320);
			$qyFission->invitation_text = $_POST['invitation_text'];
			$qyFission->invitationLink_title = $_POST['invitationLink_title'];
			$qyFission->invitationLink_desc = $_POST['invitationLink_desc'];
			$qyFission->invitationLink_pic = $_POST['invitationLink_pic'];
			$qyFission->qun_imgurl = $_POST['qun_imgurl'];
			$qyFission->sex = $_POST['sex'];
			$qyFission->poster_fontstyle = json_encode($_POST['poster_fontstyle']);  //昵称大小 位置 颜色
			$qyFission->save();
			//生成链接
			/**$filename = '/' . $_POST['name'] . $qyFission->id . '.png';
			if (!is_dir('inqunbao')) {
				mkdir('inqunbao', 0777, true);
			}
			$url = $this->createPoster($_POST, $qyFission->id, 'inqunbao' . $filename);*/
			// DUMP($url);die;
			if (!$id) {
				
				if ($_POST['invitation_check'] == 1) {
					$etArr = [];
					if ($_POST['invitation_range'] == 1) {
						$etList = (new Model('qy_externalcontact_list'))->field('external_userid')->where(['wid' => $wid])->list_all_array();
						foreach ($etList as $et) {
							$etArr[] = $et['external_userid'];
						}
					} else {
						if ($_POST['selected_et']) {
							$etArr = explode(',', $_POST['selected_et']);
						}
					}
					/**$uurl="http://".$_SERVER['HTTP_HOST'].ltrim($url,'.');
					$upres=$etApp->media->uploadImage($uurl);*/
					$uurl = $qyFission->poster_imgurl;
					if ($etArr) {
						$msg['external_userid'] = $etArr;
						$msg['image'] = ['media_id' => $etApp->media->uploadImage($uurl)['media_id']];
						$msg['text'] = ['content' => $_POST['invitation_text']];
						$msg['link'] = [
							'title' => $_POST['name'],
							'picurl' => $uurl,
							'desc' => $_POST['invitationLink_desc'],
							'url' => $uurl,
							// 'url' => Helper::getInstance()->get_http_server_name() . '/Addons/Fission/H5/Fission/activity_fission.html?fid=' . $id
						];
						try {
							$messageRes = $etApp->external_contact_message->submit($msg);
						} catch (\Exception $e) {
							return ['status' => 'error', 'msg' => $e->getMessage()];
						}
						// dump($messageRes);die;
					}
				}
				// $this->invitation_et($_POST, $qyFission->id, $url);
			}
			sendSuccess('操作成功');
		}
		// dump($qyFission);die;
		$poster_fontstyle = json_decode($qyFission->poster_fontstyle);

		$this->assign("h", QyHelper::getInstance());
		$this->assign("qyFission", $qyFission);
		$this->assign("poster_fontstyle", $poster_fontstyle);
		return $this->show();
	}
	public function createPoster($data, $id, $filename)
	{
		// $fuserid = \Request::get(1);
		// $fuser = (new Model('qy_fission_user'))->find($fuserid);
		// $bind_user = (new Model('qy_externalcontact_list'))->find($fuser->bind_uid);
		$fission = (new Model('qy_fission'))->find($id);
		if ($fission->poster_coordinate) {
			$coordinate = json_decode($fission->poster_coordinate, 1);
			$imgurl_left = $coordinate['imgurl_left'];
			$imgurl_top = $coordinate['imgurl_top'];
		} else {
			$imgurl_left = 162;
			$imgurl_top = 338;
		}

		if ($fission->poster_fontstyle) {
			$poster_fontstyle = json_decode($fission->poster_fontstyle, 1);
			$color = $poster_fontstyle['color'];
			$size = $poster_fontstyle['size'];
			$left = $poster_fontstyle['left'];
			$top = $poster_fontstyle['top'];
		}
		$config = [];
		$config['background'] = [
			'background' => $data['poster_imgurl'],
			'width' => 800,
			'height' => 1300
		];
		$config['image'][0] = [
			'url' => $data['qun_imgurl'],
			'left' => $imgurl_left * (590 / 162),
			'top' => $imgurl_top * (1090 / 338),
			'right' => 0,
			'stream' => 0,
			'bottom' => 0,
			'width' => 200,
			'height' => 200,
			'opacity' => 100
		];

		return Helper::getInstance()->createPoster($config, $filename);
		exit;
	}
	/**
	 * RGB转 十六进制
	 * @param $rgb RGB颜色的字符串 如：rgb(255,255,255);
	 * @return string 十六进制颜色值 如：#FFFFFF
	 */
	function RGBToHex($rgb)
	{
		$regexp = "/^rgb\(([0-9]{0,3})\,\s*([0-9]{0,3})\,\s*([0-9]{0,3})\)/";
		$re = preg_match($regexp, $rgb, $match);
		$re = array_shift($match);
		$hexColor = "#";
		$hex = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F');
		for ($i = 0; $i < 3; $i++) {
			$r = null;
			$c = $match[$i];
			$hexAr = array();
			while ($c > 16) {
				$r = $c % 16;
				$c = ($c / 16) >> 0;
				array_push($hexAr, $hex[$r]);
			}
			array_push($hexAr, $hex[$c]);
			$ret = array_reverse($hexAr);
			$item = implode('', $ret);
			$item = str_pad($item, 2, '0', STR_PAD_LEFT);
			$hexColor .= $item;
		}
		return $hexColor;
	}
	/**
	 * 十六进制 转 RGB
	 */
	function hex2rgb($hexColor)
	{
		$color = str_replace('#', '', $hexColor);
		if (strlen($color) > 3) {
			$rgb = array(
				'r' => hexdec(substr($color, 0, 2)),
				'g' => hexdec(substr($color, 2, 2)),
				'b' => hexdec(substr($color, 4, 2))
			);
		} else {
			$color = $hexColor;
			$r = substr($color, 0, 1) . substr($color, 0, 1);
			$g = substr($color, 1, 1) . substr($color, 1, 1);
			$b = substr($color, 2, 1) . substr($color, 2, 1);
			$rgb = array(
				'r' => hexdec($r),
				'g' => hexdec($g),
				'b' => hexdec($b)
			);
		}
		return $rgb;
	}


	public function select_et()
	{
		$wid = Session::get('wid');
		/**if(\Request::get('etname')){
			$where['name@~'] = \Request::get('etname');
		}
		$where['wid'] = $wid;
		$etList = (new Model('qy_externalcontact_list'))->where($where)->list_all_array();*/
		$sql = "select * from qvmh_qy_externalcontact_list where wid = {$wid}";
		if (\Request::get('etname')) {
			$sql .= " and name like '%" . \Request::get('etname') . "%'";
		}
		$sql .= " group by external_userid";
		$etList = db_query($sql);
		$this->assign("etList", $etList);
		$this->assign("count", count($etList));
		$this->assign("etname", \Request::get('etname'));
		return $this->show();
	}

	public function download_inqunbao()
	{
		$id = \Request::get(1);
		$fission = (new Model('qy_inqunbao'))->find($id);
		//设置头信息
		$filename = $fission->name . $id . '.png';
		// echo $filename;die;
		$files = $_SERVER['HTTP_HOST'] . '/pub/inqunbao/' . $filename;
		// header('Content-Disposition:attachment;filename=' . $filename);
		// // header('Content-Length:' . filesize('http://'.$_SERVER['HTTP_HOST'].'/pub/inqunbao/' . $filename));
		// header('location:http://' . $_SERVER['HTTP_HOST'] . '/pub/inqunbao/' . $filename);
		// header("Content-Disposition:attachment;filename = " . $filename);
		header("Content-type:application/octet-stream");
		header('content-Disposition:attachment;filename=" ' . $filename . ' " ');
		readfile($files);
	}
	public function mission_list()
	{
		$wid = Session::get('wid');
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid' => $wid]);
		/**$ppc = (new Model('qy_providers_permanent_code'))->find(['corpid' => $qyConfig->corp_id]);
		$h = Helper::getInstance();
		if (!$ppc->permanent_code) {
			$ProvidersApi = ProvidersApi::getInstance();
			$redirect_uri = urlencode($h->get_http_server_name() . '/Addons/Fission/Admin/Fission/finish_auth.html');
			try {
				$url = $ProvidersApi->get_rebind_url($redirect_uri);
			} catch (\Exception $e) {
				$url = '';
			}
			//return "<script>location.href='" . $url . "'</script>";
			$this->assign("url", $url);
			return $this->show('Admin/Inqunbao/auth');
		}*/
		$fission = new Model('qy_inqunbao');
		$p = new \Pagination();
		$res = $p->model_list($fission->where(['wid' => $wid])->order('id desc'));
		foreach ($res as $k => $v) {
			// $res[$k]->allCustomer = (new Model('qy_fission_user'))->where(['wid' => $wid, 'fid' => $v->id])->count();  //客总数
		}

		//数据统计
		$missionArr = (new Model('qy_inqunbao'))->where(['wid' => $wid])->map_array('id', 'name');
		$missionFirst = (new Model('qy_inqunbao'))->find(key($missionArr));
		// $allCustomer = (new Model('qy_fission_user'))->where(['wid' => $wid, 'fid' => $missionFirst->id])->count(); //客总数
		// $newCustomer = (new Model('qy_fission_user'))->where(['wid' => $wid, 'fid' => $missionFirst->id, 'is_new_friend' => 1])->count(); //新客总数

		$this->assign("missionArr", $missionArr);
		$this->assign("missionFirst", $missionFirst);


		$this->assign("p", $p);
		$this->assign("P", $GLOBALS['P']);
		$this->assign("res", $res);
		$this->assign("h", QyHelper::getInstance());
		return $this->show();
	}
	public function del_mission()
	{
		setApi();
		$wid = Session::get('wid');
		$QyWechatApi = QyWechatApi::getInstance();
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid' => $wid]);
		$etApp = $QyWechatApi->get_qy_app($qyConfig->corp_id, $qyConfig->externalcontact_secret);
		$id = $_POST['id'];
		if ($id) {
			$fission = (new Model('qy_inqunbao'))->find($id);
		} else {
			sendError('参数错误');
		}
		$configId = $fission->config_id;
		// $deleteRes = $etApp->contact_way->delete($configId?$configId:'');

		$fission->delete();
		sendSuccess('操作成功');
	}
	public function invitation_et($data, $id, $url)
	{
		$wid = Session::get('wid');
		$QyWechatApi = QyWechatApi::getInstance();
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid' => $wid]);
		$etApp = $QyWechatApi->get_qy_app($qyConfig->corp_id, $qyConfig->externalcontact_secret);
		if ($data['invitation_check'] == 1) {
			$etArr = [];
			if ($data['invitation_range'] == 1) {
				$etList = (new Model('qy_externalcontact_list'))->field('external_userid')->where(['wid' => $wid])->list_all_array();
				foreach ($etList as $et) {
					$etArr[] = $et['external_userid'];
				}
			} else {
				if ($data['selected_et']) {
					$etArr = explode(',', $data['selected_et']);
				}
			}
			if ($etArr) {
				$msg['external_userid'] = $etArr;
				$msg['text'] = ['content' => $data['invitation_text']];
				$msg['link'] = [
					'title' => $data['invitationLink_title'],
					'picurl' => "http://{$_SERVER['HTTP_HOST']}" . ltrim($url, '.'),
					'desc' => $data['invitationLink_desc'],
					'url' => "http://{$_SERVER['HTTP_HOST']}" . ltrim($url, '.')
					// 'url' => Helper::getInstance()->get_http_server_name() . '/Addons/Fission/H5/Fission/activity_fission.html?fid=' . $id
				];
				try {
					$messageRes = $etApp->external_contact_message->submit($msg);
				} catch (\Exception $e) {
					return ['status' => 'error', 'msg' => $e->getMessage()];
				}
			}
		}
	}
}
