<?php


/**
 * Class imGroupAction
 */
class imGroupAction extends baseAction
{

	/**
	 * [$ypw model]
	 * @var [object]
	 */
	private $ypw = null;

	/**
	 * [$param 请求参数]
	 * @var array
	 */
	private $param = [];

	/**
	 * [$ver 腾讯api版本]
	 * @var string
	 */
	private $ver = 'v4/group_open_http_svc/';

	/**
	 * [$groupUserId 群主Uid]
	 * @var string
	 */
	private $groupUserId = 'yipartsb2c';

	/**
	 * [$return api返回]
	 * @var array
	 */
	private $return = [];

    /**
     * @var int 是否添加
     */
	private $isAdd = 0;

	private $statusName = [
	    '0' => '待处理',
        '1' => '投诉成立',
        '-1' => '投诉无效',
        '2'=>'关闭',
        '3'=>'已处理'
    ];
    /**
     * imGroupAction constructor.
     */
	public function __construct()
    {
        $this->ypw = new YpwBase;
        $this->param = array_merge(
            array_map(function ($value){

                return is_array($value) ? array_map('trim',$value) : (!empty($value) ? trim($value) : $value);

            }, $_POST),
            array_map(function ($value){

                return is_array($value) ? array_map('trim',$value) : (!empty($value) ? trim($value) : $value);

            }, $_GET)
        );
    }

    /**
	 * [groupBasic 群基础资料修改接口]
	 * @Author   Yangxing
	 * @DateTime 2020-06-13T17:54:14+0800
	 */
	public function groupBasic()
	{
		 if((int) $this->param['grp_seq'] > 999)  LibFc::ajaxJsonEncode(['status' => false,'data' => '排序最大值为999']);
		 if(mb_strlen($this->param['grp_name']) > 30) LibFc::ajaxJsonEncode(['status' => false,'data' => '群名字最长不能超过30个字']);
		 $this->isAdd = $this->ypw->YpwDb->One(sprintf("select 1 from im_groups where grp_code='%s'",$this->param['grp_code']));
		 $this->updateOrAdd();
	}

    /**
     * [deleteGroupBasic 删除群基础资料]
     * @Author   Yangxing
     * @DateTime 2020-06-13T17:54:14+0800
    */
	public function destroyGroup()
    {
        $this->__destroyGroup();

        if(isset($this->return['data']['ErrorCode']) && $this->return['data']['ErrorCode'] > 0)  LibFc::ajaxJsonEncode(['status'=>false,'data' => $this->return['data']['ErrorInfo']]);

        $result = $this->ypw->del('im_groups',sprintf(" and grp_code='%s'",$this->param['id']));

        LibFc::ajaxJsonEncode($result);
    }

	/**
	 * [groupList 群组列表页]
	 * @Author   Yangxing
	 * @DateTime 2020-06-13T18:04:08+0800
	 */
	public function groupList()
	{
        LibRule::Check('IM03');
        $where = '';

		$perPage = isset($_COOKIE['perPage'])? $_COOKIE['perPage'] : 20;
        $nowpage = LibFc::Int($_GET['page']) ? LibFc::Int($_GET['page']) : 1;

        if($this->param['grp_name']) $where .= sprintf(" and grp_name like '%%%s%%'",$this->param['grp_name']);
        if($this->param['pc_id']) $where .= sprintf(" and find_in_set('%s',grp_pcts)",'{"pid":'.$this->param['pc_id']);


        $count = $this->ypw->YpwDb->One(sprintf("select count(*) from im_groups where 1=1 %s",$where));
        LibTpl::Set('page',LibPage::Show($count, $perPage));

        $sql = "SELECT pc_id as id,pc_name as name,pc_pid as pid from yp_province_city where pc_pid in(SELECT pc_id from yp_province_city where pc_pid=0) union SELECT pc_id as id,pc_name as name,pc_pid as pid from yp_province_city  where pc_pid=0";
        $city = $this->ypw->YpwDb->Table($sql);
        LibTpl::Set('city',array_filter($city,function($value){ return $value['pid'] == 0;}));

        if($count > 0)
        {
            $citys = array_column($city,"name",'id');

            $list = $this->ypw->YpwDb->Table(sprintf("select im_groups.*,yp_user.u_name from im_groups join yp_user on grp_owner_uid=u_id where 1=1 %s order by grp_seq asc limit %s,%s",$where,($nowpage-1)*$perPage,$perPage));

            $grpCode = array_column($list,'grp_code');

            $this->__getGroupInfo($grpCode);

            $grpInfo = $this->return['data']['GroupInfo'];

            if(!empty($grpInfo))
            {
                $grpInfo = array_column($grpInfo,null,'GroupId');

                foreach ($list as &$item)
                {
                    $item['info'] = $grpInfo[$item['grp_code']];
                    $item['grp_atime'] = date('Y-m-d H:i',$item['grp_atime']);
                    $temp = json_decode($item['grp_pcts'],true);
                    $item['grp_city'] = $citys[$temp['pid']].$citys[$temp['cid']];
                }
            }

           unset($citys,$item,$sql,$count);
           LibTpl::Set('list',$list);
        }
        LibTpl::Set('param',$this->param);
        LibTpl::Set('title','群管理列表');
        LibTpl::Put();
	}

    /**
     * [getGroupShuttedUin 获取禁言列表]
     * @Author   Yangxing
     * @DateTime 2020-06-13T18:04:08+0800
     */
	public function getGroupShuttedUin()
    {
        $this->__getGroupShuttedUin();
        ob_clean();
        echo json_encode(['code' => 0 ,'msg' => '','count' => count($this->return['data']['ShuttedUinList']) ,'data' => $this->return['data']['ShuttedUinList']]);
    }

    /**
     * [__getGroupShuttedUin 获取禁言列表]
     * @Author   Yangxing
     * @DateTime 2020-06-13T18:04:08+0800
     */
    private function __getGroupShuttedUin()
    {
        $this->requestApi(["GroupId" => $this->param['id']]);
    }

    /**
     * [getGroupMemberList 群成员列表]
     * @Author   Yangxing
     * @DateTime 2020-06-13T17:29:44+0800
     */
	public function getGroupMemberList()
    {
        $this->__getGroupMemberInfo();
        ob_clean();
        $data = ['code' => 0, 'msg' => '', 'data' => $this->return['data']['MemberList'], 'count' => $this->return['data']['MemberNum']];
        echo json_encode($data);
    }

	/**
	 * [__modifyGroupBaseInfo 修改基础资料]
	 * @Author   Yangxing
	 * @DateTime 2020-06-13T17:30:07+0800
	 */
	private function __modifyGroupBaseInfo()
	{
        $param = [
              'GroupId' => $this->param['grp_code'],
		      'Type' => 'Public', //公开的
		      'Name' => $this->param['grp_name'],//群名称
		      'Introduction' => $this->param['Introduction'], //群简介
              'Notification' => $this->param['Notification'],
              'FaceUrl' => $this->param['FaceUrl'],
              'MaxMemberNum' => (int) $this->param['MaxMemberNum'] ?: 200,
              'ApplyJoinOption' => $this->param['ApplyJoinOption'] ?: 'FreeAccess',
              'ShutUpAllMember' => $this->param['ShutUpAllMember'] ?: 'On'
		];
		$this->requestApi($param);
	}

    /**
     * [deleteGroupMember 删除群成员]
     * @Author   Yangxing
     * @DateTime 2020-06-13T17:30:07+0800
     */
	public function deleteGroupMember()
    {
        $this->__deleteGroupMember();
        LibFc::ajaxJsonEncode($this->return['data']);
    }

    /**
     * [__deleteGroupMember 删除群成员]
     * @Author   Yangxing
     * @DateTime 2020-06-13T17:30:07+0800
     */
	private function __deleteGroupMember()
    {
        $this->requestApi([
            "GroupId" => $this->param['id'],
            'MemberToDel_Account' => $this->param['member']
        ]);
    }

    /**
     * [__addGroupMember 添加群成员]
     * @Author   Yangxing
     * @DateTime 2020-06-13T17:30:07+0800
     */
    private function __addGroupMember()
    {
        $this->requestApi([
            "GroupId" => $this->param['id'],
            "MemberList" => $this->param['member']
        ]);
    }

    /**
     * [__changeGroupOwner 转让群主]
     * @Author   Yangxing
     * @DateTime 2020-06-13T17:30:07+0800
     */
    private function __changeGroupOwner()
    {
        $this->requestApi([
             "GroupId" => $this->param['id'],  // 要被转移的群 ID（必填）
             "NewOwner_Account" => trim($this->param['member']) // 新群主 ID（必填）
        ]);
    }

    /**
     * [changeGroupOwner 转让群主]
     * @Author   Yangxing
     * @DateTime 2020-06-13T17:30:07+0800
     */
    public function changeGroupOwner()
    {
        $this->__changeGroupOwner();
        if($this->return['data']['ErrorCode'] == 0){
            $update = [
                'grp_owner_uid' => $this->ypw->YpwDb->One(sprintf("select u_id from yp_user where u_name='%s'",trim($this->param['member'])))
            ];
           $this->ypw->set('im_groups',$update,sprintf(" and grp_code='%s'",$this->param['id']));
        }
        LibFc::ajaxJsonEncode($this->return['data']);
    }

    /**
     * [__forbidSendMsg 禁言与取消禁言]
     * @Author   Yangxing
     * @DateTime 2020-06-13T17:30:07+0800
     */
    private function __forbidSendMsg()
    {
        $this->requestApi([
            "GroupId" => $this->param['id'],
            "Members_Account" => $this->param['member'],
            "ShutUpTime" => (int) $this->param['time'] // 禁言时间，单位为秒
        ]);
    }

    /**
     * [forbidSendMsg 禁言与取消禁言]
     * @Author   Yangxing
     * @DateTime 2020-06-13T17:30:07+0800
     */
    public function forbidSendMsg()
    {
        $this->__forbidSendMsg();
        LibFc::ajaxJsonEncode($this->return['data']);
    }

    /**
     * [deleteGroupMsgBySender 删除消息]
     * @Author   Yangxing
     * @DateTime 2020-06-13T17:30:07+0800
     */
    public function deleteGroupMsgBySender()
    {
        $this->__deleteGroupMsgBySender();
        LibFc::ajaxJsonEncode($this->return['data']);
    }

    /**
     * [__deleteGroupMsgBySender 删除消息]
     * @Author   Yangxing
     * @DateTime 2020-06-13T17:30:07+0800
     */
    private function __deleteGroupMsgBySender()
    {
        foreach ($this->param['member'] as $member)
        {
            $this->requestApi([
                "GroupId" => $this->param['id'],    //必填
                "Sender_Account" => $member      //必填
            ]);
        }
    }

    /**
     * [groupMsgGetSimple 群消息记录]
     * @Author   Yangxing
     * @DateTime 2020-06-13T17:30:07+0800
     */
    public function groupMsgGetSimple()
    {
       
        $this->__groupMsgGetSimple();
        if(!empty($this->return['data']['RspMsgList'])){
            $res = end($this->return['data']['RspMsgList']);
        }else{
            $res['MsgSeq'] = 0;
        }

        LibFc::ajaxJsonEncode(['status' => true,'code' => 0,'seq' => $res['MsgSeq'], 'data' => $this->return['data']['RspMsgList'] ?: []]);
    }

    /**
     * [__groupMsgGetSimple 群消息记录]
     * @Author   Yangxing
     * @DateTime 2020-06-13T17:30:07+0800
     */
    private function __groupMsgGetSimple()
    {
        if($this->param['page'] == 1){
            $param = [
                "GroupId" => $this->param['id'],    //拉取消息的群 ID
                "ReqMsgNumber" => 20,      //需要拉取的消息条数
            ];
        }else{
            if($this->param['seq']-1 <= 0){
                $this->return = [];
                return false;
            }
            $param = [
                "GroupId" => $this->param['id'],    //拉取消息的群 ID
                "ReqMsgNumber" => 20,      //需要拉取的消息条数\
                'ReqMsgSeq' => $this->param['seq'] -1
            ];
        }
        $this->requestApi($param);
    }

    /**
     * [__sendGroupMsg 发送普通消息]
     * @Author   Yangxing
     * @DateTime 2020-06-13T17:30:07+0800
     */
    private function __sendGroupMsg()
    {
        //todo 只对接了文本
        foreach ($this->param['id'] as $id){
            if(empty($id)){
                continue;
            }
            $this->requestApi([
                "GroupId" => $id,
                "Random" => time(), // 随机数字，五分钟数字相同认为是重复消息
                "MsgBody" => [ // 消息体，由一个 element 数组组成，详见字段说明
                    [
                        "MsgType" => "TIMTextElem", // 文本
                        "MsgContent" => [
                            "Text" => $this->param['content']
                        ],
                    ]
                ],
//            "OfflinePushInfo" => [
//                  "PushFlag" => 0, // 正常推送，
//                  "Desc" => "离线推送内容",
//                  "Ext" => "这是透传的内容",
//                  "AndroidInfo" => [
//                        "Sound" => "android.mp3"
//                  ],
//            ],
//           "ApnsInfo" => [
//               "Sound" => "apns.mp3",
//               "BadgeMode" => 1, // 这个字段缺省或者为0表示需要计数，为1表示本条消息不需要计数，即右上角图标数字不增加
//               "Title" => "apns title", // apns title
//               "SubTitle" => "apns subtitle", // apns subtitle
//               "Image" => "www.image.com" // image url
//           ]
            ]);
        }
    }

    /**
     * [__sendGroupSystemNotification 发送消息通知]
     * @Author   Yangxing
     * @DateTime 2020-06-13T17:30:07+0800
     */
    private function __sendGroupSystemNotification()
    {
        foreach ($this->param['id'] as $id){
            if(empty($id)){
                continue;
            }
            $this->requestApi([
                "GroupId" => $id,
                "Content" =>  $this->param['content'],// 系统通知内容
                'igs_type' => $this->param['igs_type']
            ]);
        }
    }

    /**
     * @param member 发送人
     * @param igs_grp_code 群ID
     */
    public function groupHairList()
    {
        $where = '';
        if($this->param['member']) $where .= sprintf(" and igs_auname='%s'",$this->param['member']);
        if($this->param['grp_code'])  $where .= sprintf(" and igs_grp_code='%s'",$this->param['grp_code']);
        $count = $this->ypw->YpwDb->One(sprintf("select count(*) from im_groups_sendmsg where 1=1 %s",$where));
        $list = [];
        if($count > 0)  $list = $this->ypw->YpwDb->Table(sprintf("select im_groups_sendmsg.*,grp_name from im_groups_sendmsg left join im_groups on grp_code=igs_grp_code where 1=1 %s order by igs_atime desc limit %s,%s",$where,((int) $this->param['page'] -1) * $this->param['limit'],$this->param['limit']));
        ob_clean();
        echo json_encode(['code' => 0, 'msg' => 'ok', 'count' => $count, 'data' => $list]);
    }

    public function groupSelectList()
    {
        $result = $this->ypw->get("im_groups",['grp_code as id','grp_name as name'],'');
        LibFc::ajaxJsonEncode($result);
    }

    /**
     * [sendGroupSystemNotification 发送消息通知]
     * @Author   Yangxing
     * @DateTime 2020-06-13T17:30:07+0800
     */
    public function sendGroupSystemNotification()
    {
        //todo 表单验证
        if(empty($this->param['id'])) LibFc::ajaxJsonEncode(['status' => false,'data' => 'GroupId 不可为空']);
        if(empty($this->param['content'])) LibFc::ajaxJsonEncode(['status' => false,'data' => '发送消息通知的内容不可为空']);
        $this->__sendGroupSystemNotification();
        $this->addLog();
        LibFc::ajaxJsonEncode($this->return['data']);
    }

    /**
     * [sendGroupSystemNotification 发送普通消息]
     * @Author   Yangxing
     * @DateTime 2020-06-13T17:30:07+0800
     */
    public function sendGroupMsg()
    {
        if(empty($this->param['id'])) LibFc::ajaxJsonEncode(['status' => false, 'data' => 'GroupId不可为空']);
        if(empty($this->param['content'])) LibFc::ajaxJsonEncode(['status' => false, 'data' => '发送的消息不可为空']);
        $this->__sendGroupMsg();
        $this->addLog();
        LibFc::ajaxJsonEncode($this->return['data']);
    }

    /**
     * [addLog 发送消息通知或者普通消息时添加]
     * @Author   Yangxing
     * @DateTime 2020-06-13T17:30:07+0800
     */
    private function addLog()
    {
        foreach ($this->param['id'] as $id)
        {
            if(empty($id)) continue;
            $data = [
                'igs_grp_code' => $id,
                'igs_type' => $this->param['igs_type'],
                'igs_text' => $this->param['content'],
                'igs_atime' => time(),
                'igs_add_uid' => $_SESSION['admin_userid'],
                'igs_auname' => $_SESSION['admin_uname'],
                'igs_remark' => $this->param['igs_remark'] ?: '',
            ];
            $this->ypw->add('im_groups_sendmsg',$data);
            unset($data);
        }
    }

    /**
     * [__addGroupMember 添加群成员]
     * @Author   Yangxing
     * @DateTime 2020-06-13T17:30:07+0800
     */
    public function addGroupMember()
    {
        $this->param['member'] = str_replace('，',',',$this->param['member']);
        $temp = explode(',',$this->param['member']);
        $this->param['member'] = [];
        foreach ($temp as $key => $value)
        {
            if(empty($value)){
               continue;
            }
            $this->param['member'][] = [
                'Member_Account' => trim($value)
            ];
        }
        unset($temp);
        $this->__addGroupMember();
        LibFc::ajaxJsonEncode($this->return);
    }

	//添加页面
	public function addPage()
    {
       
        if(empty($this->param['id']))
        {
            $data = [
                 'grp_code'  => '',  //'群ID',
                 'grp_name' => '',//'群名',
                 'grp_owner_uid' => '' ,//'群主用户ID',
                 'grp_pcts' => '',//'{"pid":"省ID","cid":"城市ID"}',
                 'grp_atime' =>  '',
                 'grp_add_uid' => '', // '创建人ID',
                 'grp_auname' => '',// '创建人',
                 'grp_seq' => '1',// '排序 小到大',
                 'is_add' => 1,
                 'grp_pctss' => '',
            ];
        }
        else
        {
            $data = $this->ypw->YpwDb->Row(sprintf('select * from im_groups where grp_code="%s"',$this->param['id']));
            $data['is_add'] = 0;
            $this->__getGroupInfo([$this->param['id']]);//必须传二维数组
            if(isset($this->return['data']) && $this->return['data']['ErrorCode'] > 0){
                echo $this->return['data']['ErrorInfo'];exit();
            }else{
                $groupInfo = current($this->return['data']['GroupInfo']);
                LibTpl::Set('groupInfo',$groupInfo);
            }
        }

        $sql = "SELECT pc_id as id,pc_pid as pid,pc_name as name,pc_fromid as code from yp_province_city where pc_pid in(SELECT pc_id from yp_province_city where pc_pid=0) union SELECT pc_id as id,pc_pid as pid,pc_name as name,pc_fromid as code from yp_province_city where pc_pid=0";

        $city = $this->ypw->YpwDb->Table($sql);

        if($data['is_add'] == 0)
        {
            $data['grp_pcts'] = json_decode($data['grp_pcts']);
            $data['cid'] = $data['grp_pcts']->cid;
            $data['pid'] = $data['grp_pcts']->pid;
        }
        LibTpl::Set('city',json_encode($city,true));
        LibTpl::Set('data',$data);
        LibTpl::Put();
    }

	/**
	 * [addGroup 添加群基础资料]
	 * @Author   Yangxing
	 * @DateTime 2020-06-13T17:29:44+0800
	 */
	private function __createGroup()
	{
		$param = [
		      'GroupId' => $this->param['grp_code'],
		      'Owner_Account' => $this->groupUserId, //群主UserId
		      'Type' => 'Public', //公开的
		      'Name' => $this->param['grp_name'],//群名称
              'Introduction' => $this->param['Introduction'], //群简介
              'Notification' => $this->param['Notification'],
              'FaceUrl' => $this->param['FaceUrl'],
              'ApplyJoinOption' => $this->param['ApplyJoinOption'] ?: 'FreeAccess',
              'MaxMemberNum' => (int) $this->param['MaxMemberNum'] ?: 2000,
              'ShutUpAllMember' => $this->param['ShutUpAllMember'] ?: 'On'
		];
		$this->requestApi($param);
	}

    /**
     * 创建群ID
     */
	private function createGroupId()
    {
        return uniqid("yiparts");
    }

    /**
     * [addGroup 删除群基础资料]
     * @Author   Yangxing
     * @DateTime 2020-06-13T17:29:44+0800
     */
	private function __destroyGroup()
    {
        $param = [
            "GroupId" => $this->param['id']
        ];
        $this->requestApi($param);
    }

    /**
     * 获取群组资料
     * @param $id
     * @return bool
     */
    private function __getGroupInfo($id)
    {
        if(empty($id['0']))
        {
           return true;
        }
        $param = [
            "GroupIdList" => $id,
            'ResponseFilter' => [
                "GroupBaseInfoFilter" => [ // 如果基础信息字段，请在此数组中添加
                    "Type",
                    "Name",
                    "Introduction",
                    "Notification",
                    "MaxMemberNum",
                    "Introduction",
                    "MemberNum",
                    "Notification",//群主通知
                    "FaceUrl",
                    "ApplyJoinOption",
                    "CreateTime",
                    "MemberNum",
                    "ShutUpAllMember"
                ],
            ]
        ];
        $this->requestApi($param);
    }

    /**
     * [__getGroupMemberInfo 群成员列表]
     * @Author   Yangxing
     * @DateTime 2020-06-13T17:29:44+0800
     */
    private function __getGroupMemberInfo()
    {
        $param = [
            "GroupId" => $this->param['id'],
            "Limit" => (int) $this->param['limit'], // 最多获取多少个成员的资料
            "Offset" =>  (int) $this->param['page'] - 1, // 从第多少个成员开始获取资料
            "MemberRoleFilter" => $this->param['MemberRoleFilter'] ? [$this->param['MemberRoleFilter']] : ['Owner', 'Member', 'Admin']
        ];
        $this->requestApi($param);
    }

    /**
     * 请求api
     * @param $param array 参数
     */
	private function requestApi($param)
	{
        $dbt = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS,2);
        $caller = isset($dbt[1]['function']) ? $dbt[1]['function'] : null;
        $caller = $this->uncamelize(str_replace("__",'',$caller));
		$this->return = (new LibYpApi)->get('im/getApi', [],['apiName'=>$this->ver.$caller,'params'=> $param]);
	}

    /**
     * 驼峰转为下划线
     * @param $camelCaps string 字符串
     * @param $separator string 分隔符
     * @return string 驼峰命名字符串
     */
     private function uncamelize($camelCaps,$separator='_')
     {
         return strtolower(preg_replace('/([a-z])([A-Z])/', "$1" . $separator . "$2", $camelCaps));
     }

	/**
	 * [updateOrAdd 修改或者添加]
	 * @Author   Yangxing
	 * @DateTime 2020-06-13T17:48:39+0800
	 */
	private function updateOrAdd()
	{
		if(isset($this->return['data']['ErrorCode']) && $this->return['data']['ErrorCode'] > 0)
		{
			LibFc::ajaxJsonEncode(['status'=>false,'data' => $this->return['data']['ErrorInfo']]);
		}


		$uId = $this->ypw->YpwDb->One(sprintf("select u_id from yp_user where u_name='%s'",$this->groupUserId));

        $pcts = json_encode(['pid' => $this->param['pid'] ?: '','cid' => $this->param['cid'] ?: '']);

		//todo 此处可以直接replace
		if($this->isAdd)
		{
			$data = [
              'grp_name' => $this->param['grp_name'], //群名称
              'grp_owner_uid' => $uId, //群主ID
              'grp_pcts' => $pcts,
              'grp_atime' => time(), //创建时间',
              'grp_add_uid' => $_SESSION['admin_userid'], //创建人ID
              'grp_auname' => $_SESSION['admin_uname'], //创建人
              'grp_seq' => (int) $this->param['grp_seq'], //排序 小到大
		    ];
			$result = $this->ypw->set('im_groups',$data,sprintf(" and grp_code='%s'",$this->param['grp_code']));
            if($result['status']){
                $this->isAdd ? $this->__modifyGroupBaseInfo() : $this->__createGroup();
            }
		}
		else
		{
		    $data = [
		     // 'grp_code' => $this->return['data']['GroupId'], //群ID
              'grp_name' => $this->param['grp_name'], //群名称
              'grp_owner_uid' => $uId, //群主ID
              'grp_pcts' =>  $pcts,
              'grp_atime' => time(), //创建时间',
              'grp_add_uid' => $_SESSION['admin_userid'], //创建人ID
              'grp_auname' => $_SESSION['admin_uname'], //创建人
              'grp_seq' => (int) $this->param['grp_seq'], //排序 小到大
		    ];
		   $result = $this->ypw->add('im_groups',$data);
		   if($result['status']){
		       $this->param['grp_code'] = $result['data'];
               $this->isAdd ? $this->__modifyGroupBaseInfo() : $this->__createGroup();
           }else{
		       LibFc::ajaxJsonEncode(['status' => false,'data' => '添加失败']);
           }
		}
		LibFc::ajaxJsonEncode($result);
	}

	//群投诉管理
	public function complaint()
    {
        //todo 权限不对
        LibRule::Check('IM04');
        $where = ' and tou_status != -2 ';
        $pageSize = isset($_COOKIE['perPage']) ? $_COOKIE['perPage'] : 20;
        $page = (int) $this->param['page'] ?: 1;
        $where .= is_numeric($this->param['tou_status']) ? sprintf(" and tou_status='%s'",$this->param['tou_status']) : '';
        if($this->param['tou_from_uid'])  $where .= sprintf(" and user1.u_name like '%%%s%%'",$this->param['tou_from_uid']);
        if($this->param['tou_uid']) $where .= sprintf(" and user2.u_name like '%%%s%%'",$this->param['tou_uid']);
        if($this->param['tou_word']) $where .= sprintf( " and (tou_yuanyin like '%%%s%%' or tou_txt like '%%%s%%')",$this->param['tou_word'],$this->param['tou_word']);
        $count = $this->ypw->YpwDb->One(sprintf("select count(*) as count, user1.u_name as tou_from_username, user2.u_name as tou_username from im_tousu left join yp_user as user1 on tou_from_uid = user1.u_id left join yp_user as user2 on tou_uid = user2.u_id where 1=1 %s",$where));
        LibTpl::Set('page',LibPage::Show($count, $pageSize));

        if($count > 0)
        {
            $list = $this->ypw->YpwDb->Table(sprintf("select im_tousu.*,im_groups.grp_name, user1.u_name as tou_from_username, user2.u_name as tou_username from im_tousu left join yp_user as user1 on tou_from_uid = user1.u_id left join yp_user as user2 on tou_uid = user2.u_id left join im_groups on tou_grp_code=grp_code where 1=1 %s order by field(tou_status,0,1,-1) asc,tou_atime desc limit %s,%s",$where,($page-1)*$pageSize,$pageSize));
            $config = mvc::$cfg['FILE_CENTER']['pjl']; //图片配置
            foreach ($list as &$value)
            {
                if(empty($value['tou_imgs'])){
                    $value['tou_imgs'] = [];
                    $value['tou_imgs_json'] = '{}';
                }else{

                    $value['tou_imgs'] = explode(',',trim($value['tou_imgs'],','));
                    $value['tou_imgs'] = array_map(function ($item) use ($config){
                       return  $config['url_get'].'&c=tousu&f='.$item.$config['get_uri'];
                    },$value['tou_imgs']);
                }
                $value['tou_yuanyin'] = $this->__strSplit($value['tou_yuanyin']);
                $value['tou_txt'] = $this->__strSplit($value['tou_txt'],75);
                $value['status_name'] = $this->statusName[$value['tou_status']] ?: '未知';
                $value['tou_check_time'] = !empty($value['tou_check_time']) ? date('Y-m-d H:i',$value['tou_check_time']) : '';
                $value['tou_atime'] = !empty($value['tou_atime']) ? date('Y-m-d H:i',$value['tou_atime']) : '';
            }
            LibTpl::Set('list',$list);
        }
        LibTpl::Set('title','群投诉列表');
        LibTpl::Set('param',$this->param);
        LibTpl::Set('statusName',$this->statusName);
        LibTpl::Put();
    }

    /**
     * @param $str string 字符串
     * @param $manyNum int 分成多少条数据
     * @return array
     */
    private function __strSplit($str,$manyNum=32)
    {
        $arr = [];
        //str_split 分割中文乱码
        $length = mb_strlen($str);
        $count = ceil($length / $manyNum);
        for ($i = 1 ; $i <= $count; $i++)
        {
            $arr[$i-1] = mb_substr($str,($i-1)*$manyNum,$manyNum);
        }
        return $arr;
    }

    //审核
    public function audit()
    {
		LibRule::Check('IM04');
        $data = [
            'tou_check_uid' => $_SESSION['admin_userid'],
            'tou_status' => $_POST['tou_status'],
            'tou_check_user' => $_SESSION['admin_uname'],
            'tou_check_remark' => $_POST['tou_check_remark'],
            'tou_check_time' => time(),
        ];
        $result = $this->ypw->set('im_tousu',$data,sprintf(" and tou_id=%d",$_POST['tou_id']));
        LibFc::ajaxJsonEncode($result);
    }

    /**
     * @method 删除投诉记录
     * @author zhengweihua 
     * @copyright 2023-03-13
     */
    public function delComplaint()
    {
        LibRule::Check('IM04');
        $Params = mvc::$URL_PARAMS;
		if($Params['tou_id'])
        {
            $result =  $this->ypw->del('im_tousu',sprintf(" and tou_id=%d",LibFc::Int($Params['tou_id'])));
            LibFc::ajaxJsonEncode($result);
        }
		LibFc::ajaxJsonEncode(['status'=>false,'data'=>'参数不正确!']);
    }

    /**
     * @method 聊天记录
     * @author zhengweihua 
     * @copyright 2023-03-13
     */
    public function chatList()
    {
        LibRule::Check('IM04');
        $where = " and icb_callname='C2C.CallbackAfterSendMsg'";
        $pageSize = isset($_COOKIE['perPage']) ? $_COOKIE['perPage'] : 20;
        $page = (int) $this->param['page'] ?: 1;
       
        if($this->param['icb_from'])  $where .= sprintf(" and icb_from like '%%%s%%'",LibFc::Escape($this->param['icb_from']));
        if($this->param['icb_to']) $where .= sprintf(" and icb_to like '%%%s%%'",LibFc::Escape($this->param['icb_to']));
        if($this->param['keyword']) $where .= sprintf( " and icb_json like '%%%s%%'",LibFc::Escape($this->param['keyword']));
        $count = $this->ypw->YpwDb->One(sprintf("select count(*) as count from im_callback where 1=1 %s",$where));
        LibTpl::Set('page',LibPage::Show($count, $pageSize));

        if($count > 0)
        {
            $list = $this->ypw->YpwDb->Table(sprintf("select * from im_callback where 1=1 %s order by icb_atime desc limit %s,%s",$where,($page-1)*$pageSize,$pageSize));
            
            LibTpl::Set('list',$list);
        }
        LibTpl::Set('title','聊天记录列表');
        LibTpl::Set('param',$this->param);
        LibTpl::Put();
    }
}
