<?php
/**
 * Created by PhpStorm.
 * User: james
 * Date: 2017/4/21
 * Time: 上午10:23
 */

class message_formater
{
    public function format($param)
    {
        $result = [];
        $result['message_id'] = intval($param['message_id']);

        $result['message_parent_id'] = intval($param['message_parent_id']);
        $result['from_member_id'] = intval($param['from_member_id']);
        $result['to_member_id'] = strval($param['to_member_id']);

        $result['message_title'] = strval($param['message_title']);
        $result['message_body'] = strval($param['message_body']);

        $result['message_time'] = strval($param['message_time']);
        $result['message_update_time'] = strval($param['message_update_time']);

        $result['message_open'] = intval($param['message_open']);
        $result['message_state'] = intval($param['message_state']);
        $result['message_type'] = intval($param['message_type']);
        $result['read_member_id'] = strval($param['read_member_id']);
        $result['del_member_id'] = strval($param['del_member_id']);
        $result['message_ismore'] = intval($param['message_ismore']);
        $result['read_member_id'] = strval($param['read_member_id']);
        $result['from_member_name'] = strval($param['from_member_name']);
        $result['to_member_name'] = strval($param['to_member_name']);

        return $result;
    }
}

class member_messageControl extends mbMemberControl
{
    public function indexOp()
    {

    }

    public function listOp()
    {
        $mod_message	= Model('message');
        $items	= $mod_message->listMessage(array('message_type'=>'1','to_member_id_common'=>$_SESSION['member_id'],'no_message_state'=>'2'));

        if (empty($items)) {
            return self::outsuccess(null, 'nomessage');
        }
        else
        {
            $messages = [];
            $messager = new message_formater();
            foreach ($items as $item)
            {
                $messages[] = $messager->format($item);
            }

            $newnum = $this->countnewnum();
            return self::outsuccess(array('newnum'=>$newnum, 'message_array'=>$messages));
        }
    }


    public function systemmsgOp()
    {
        $model_message	= Model('message');
        $message_array	= $model_message->listMessage(array('from_member_id'=>'0','message_type'=>'1','to_member_id'=>$_SESSION['member_id'],'no_del_member_id'=>$_SESSION['member_id']));
        if (!empty($message_array) && is_array($message_array))
        {
            foreach ($message_array as $k=>$v)
            {
                $v['message_open'] = '0';
                if (!empty($v['read_member_id'])){
                    $tmp_readid_arr = explode(',',$v['read_member_id']);
                    if (in_array($_SESSION['member_id'],$tmp_readid_arr)){
                        $v['message_open'] = '1';
                    }
                }
                $v['from_member_name'] = Language::get('home_message_system_message');
                $message_array[$k]	= $v;
            }
            $message_array = array_slice($message_array, 0, 20);
            $messages = [];
            foreach ($message_array as $item)
            {
                $messager = new message_formater($item);
                $message = $messager->format();
                $messages[] = $message;
            }

            $newnum = intval($model_message->countNewMessage($_SESSION['member_id']));
            return self::outsuccess($messages);
        } else {
            return self::outsuccess(null, 'nomessage');
        }
    }

    public function showmsgbatchOp()
    {
        $model_message	= Model('message');
        $message_id =  intval($_GET['message_id']);
        $drop_type = trim($_GET['drop_type']);
        $referer_url = getReferer();
        if(!in_array($drop_type,array('msg_system','msg_seller')) || $message_id<=0){
         //   showMessage(Language::get('wrong_argument'),$referer_url,'html','error');
        }
        //查询站内信
        $param = array();
        $param['message_id'] = "$message_id";
        $param['to_member_id'] = "{$_SESSION['member_id']}";
        $param['no_del_member_id'] = "{$_SESSION['member_id']}";
        $message_info = $model_message->getRowMessage($param);
        if (empty($message_info)){
           // showMessage(Language::get('home_message_no_record'),$referer_url,'html','error');
        }
        if ($drop_type == 'msg_system'){
            $message_info['from_member_name'] =  Language::get('home_message_system_message');
        }
//        if ($drop_type == 'msg_seller'){
//            //查询店铺信息
//            $model_store = Model('store');
//            $store_info = $model_store->getStoreInfo(array('member_id'=>"{$message_info['from_member_id']}"));
//            $message_info['from_member_name'] =  $store_info['store_name'];
//            $message_info['store_id'] =  $store_info['store_id'];
//        }
        $message_list[0] = $message_info;
        //    Tpl::output('message_list',$message_list);//站内信列表
        //更新为已读信息
        $tmp_readid_str = '';
        if (!empty($message_info['read_member_id'])){
            $tmp_readid_arr = explode(',',$message_info['read_member_id']);
            if (!in_array($_SESSION['member_id'],$tmp_readid_arr)){
                $tmp_readid_arr[] = $_SESSION['member_id'];
            }
            foreach ($tmp_readid_arr as $readid_k=>$readid_v){
                if ($readid_v == ''){
                    unset($tmp_readid_arr[$readid_k]);
                }
            }
            $tmp_readid_arr = array_unique ($tmp_readid_arr);//去除相同
            sort($tmp_readid_arr);//排序
            $tmp_readid_str = ",".implode(',',$tmp_readid_arr).",";
        }else {
            $tmp_readid_str = ",{$_SESSION['member_id']},";
        }
        $model_message->updateCommonMessage(array('read_member_id'=>$tmp_readid_str),array('message_id'=>"{$message_id}"));
        //更新未读站内信数量cookie值
        //   $cookie_name = 'msgnewnum'.$_SESSION['member_id'];
        //   $countnum = $model_message->countNewMessage($_SESSION['member_id']);
        //    setNcCookie($cookie_name,$countnum,2*3600);//保存2小时
        //   Tpl::output('message_num',$countnum);

        // 新消息数量
        $newnum = $this->countnewnum();
        return self::outsuccess(array('message_list'=>$message_list, 'newnum' => $newnum));

        // Tpl::output('drop_type',$drop_type);
        //  $this->profile_menu('showmsg');
        //  Tpl::showpage('member_message.view');
    }

    /**
     * 删除普通信
     */
    public function dropcommonmsgOp() {
        $message_id = trim($_GET['message_id']);
        $drop_type = trim($_GET['drop_type']);
        if(!in_array($drop_type,array('msg_private','msg_list','sns_msg')) || empty($message_id)) {
            showMessage(Language::get('wrong_argument'),'','html','error');
        }
        $messageid_arr = explode(',',$message_id);
        $messageid_str = '';
        if (!empty($messageid_arr)){
            $messageid_str = "'".implode("','",$messageid_arr)."'";
        }
        $model_message	= Model('message');
        $param	= array('message_id_in'=>$messageid_str);
        if($drop_type == 'msg_private'){
            $param['from_member_id'] = "{$_SESSION['member_id']}";
        }elseif($drop_type == 'msg_list'){
            $param['to_member_id_common']	= "{$_SESSION['member_id']}";
        }elseif($drop_type == 'sns_msg'){
            $param['from_to_member_id']	= $_SESSION['member_id'];
        }
        $drop_state	= $model_message->dropCommonMessage($param,$drop_type);
        if ($drop_state){
            //更新未读站内信数量cookie值
            $cookie_name = 'msgnewnum'.$_SESSION['member_id'];
            $countnum = $model_message->countNewMessage($_SESSION['member_id']);
            setNcCookie($cookie_name,$countnum,2*3600);//保存2小时
            showDialog(Language::get('home_message_delete_success'),'reload','succ');
        }else {
            showDialog(Language::get('home_message_delete_fail'),'','error');
        }
    }
    /**
     * 删除批量站内信
     */
    public function dropbatchmsgOp() {
        $message_id = trim($_GET['message_id']);
        $drop_type = trim($_GET['drop_type']);
        if(!in_array($drop_type,array('msg_system','msg_seller')) || empty($message_id)){
            // showDialog(Language::get('home_message_delete_request_wrong'));
            self::outerr('home_message_delete_request_wrong');
        }
        $messageid_arr = explode(',',$message_id);
        $messageid_str = '';
        if (!empty($messageid_arr)){
            $messageid_str = "'".implode("','",$messageid_arr)."'";
        }
        $model_message	= Model('message');
        $param	= array('message_id_in'=>$messageid_str);
        if($drop_type == 'msg_system'){
            $param['message_type'] = '1';
            $param['from_member_id'] = '0';
        }
        if($drop_type == 'msg_seller'){
            $param['message_type'] = '2';
        }
        $drop_state	= $model_message->dropBatchMessage($param,$_SESSION['member_id']);
        if ($drop_state){
            //更新未读站内信数量cookie值
            //  $cookie_name = 'msgnewnum'.$_SESSION['member_id'];
            $countnum = $model_message->countNewMessage($_SESSION['member_id']);
            return self::outsuccess(array('drop_state'=>true, 'newnum' => $countnum));
            //  setNcCookie($cookie_name,$countnum,2*3600);//保存2小时
            // showDialog(Language::get('home_message_delete_success'),'reload','succ');
        }else {
            return self::outerr(array('drop_state' => false));
        }
    }

    public function settingOp() {
        $model_membermsgsetting = Model('member_msg_setting');
        if (chksubmit())
        {
            $insert = array(
                // 付款成功提醒
                array( 'mmt_code' => 'order_payment_success', 'member_id' => $_SESSION['member_id'], 'is_receive' => intval($_POST['order_payment_success']) ),
                // 商品出库提醒
                array( 'mmt_code' => 'order_deliver_success', 'member_id' => $_SESSION['member_id'], 'is_receive' => intval($_POST['order_deliver_success']) ),
                // 余额变动提醒
                array( 'mmt_code' => 'predeposit_change', 'member_id' => $_SESSION['member_id'], 'is_receive' => intval($_POST['predeposit_change']) ),
                // 充值卡余额变动提醒
                array( 'mmt_code' => 'recharge_card_balance_change', 'member_id' => $_SESSION['member_id'], 'is_receive' => intval($_POST['recharge_card_balance_change']) ),
                // 代金券使用提醒
                array( 'mmt_code' => 'voucher_use', 'member_id' => $_SESSION['member_id'], 'is_receive' => intval($_POST['voucher_use']) ),
                // 退款退货提醒
                array( 'mmt_code' => 'refund_return_notice', 'member_id' => $_SESSION['member_id'], 'is_receive' => intval($_POST['refund_return_notice']) ),
                // 到货通知提醒
                array( 'mmt_code' => 'arrival_notice', 'member_id' => $_SESSION['member_id'], 'is_receive' => intval($_POST['arrival_notice']) ),
                // 商品咨询回复提醒
                array( 'mmt_code' => 'consult_goods_reply', 'member_id' => $_SESSION['member_id'], 'is_receive' => intval($_POST['consult_goods_reply']) ),
                // 平台客服回复提醒
                array( 'mmt_code' => 'consult_mall_reply', 'member_id' => $_SESSION['member_id'], 'is_receive' => intval($_POST['consult_mall_reply']) ),
                // 代金券即将到期
                array( 'mmt_code' => 'voucher_will_expire', 'member_id' => $_SESSION['member_id'], 'is_receive' => intval($_POST['voucher_will_expire'])),
                // 兑换码即将到期提醒
                array( 'mmt_code' => 'vr_code_will_expire', 'member_id' => $_SESSION['member_id'], 'is_receive' => intval($_POST['vr_code_will_expire'])),
            );
            $result = $model_membermsgsetting->addMemberMsgSettingAll($insert);
            if ($result) {
                self::outsuccess(array('set_mess' => true));
            } else {
                self::outerr(array('set_mess'=>false));
            }
        }
        // 新消息数量
        $newnum = $this->countnewnum();

        $setting_list = $model_membermsgsetting->getMemberMsgSettingList(array('member_id' => $_SESSION['member_id']));
        $setting_array = array();
        if (!empty($setting_list)) {
            foreach ($setting_list as $val) {
                $setting_array[$val['mmt_code']] = intval($val['is_receive']);
            }
        }
        return self::outsuccess(array('setting_array'=>$setting_array, 'newnum'=>$newnum));
    }

    private function countnewnum()
    {
        $num = [];
        $num['system'] = $this->countNsystem();
        return $num;
    }

    private function countNsystem()
    {
        $mod = Model('message');
        $con = [];
        $con['message_type'] = '1';
        $con['to_member_id'] = $_SESSION['member_id'];
        $con['no_del_member_id'] = $_SESSION['member_id'];
        $con['no_read_member_id'] = $_SESSION['member_id'];
        $countnum = $mod->countMessage($con);
        return $countnum;
    }




}