<?php

defined('InShopNC') or exit('Access Invalid!');

class mobile_contactsModel extends Model
{
    public function __construct()
    {
        parent::__construct('mobile_contacts');
    }

    public function add($member_id, $contacts)
    {
        return $this->insert(array('member_id'=>$member_id,'origin_contacts'=>serialize($contacts),'task_status'=>0), true);
    }


    public function genRelations($member_id)
    {
        $ret = $this->field('member_id,origin_contacts,unregister_contacts,friend_contacts')->where(array("member_id" => $member_id,"task_status" => 0))->find();
        if (!empty($ret)) {
            $origin_contacts = unserialize($ret["origin_contacts"]);
            $mobilelist = array();
            $namelist = array();
            foreach($origin_contacts as $obj) {
                $mobilelist[] = $obj["mobile"];
                $namelist[$obj["mobile"]] = $obj["name"];
            }

            $member_nameids = array();
            $member_ids = Model("member")->field("member_id,member_mobile")->where(array('member_mobile'=>array('in', $mobilelist)))->select();
            if(!empty($member_ids)) {
                foreach($member_ids as $key => $val) {
                    $member_nameids[] = array("member_id"=>$val["member_id"],"name"=>$namelist[$val["member_mobile"]]);
                }

                $data = array("task_status"=>1,"friend_contacts"=>serialize($member_nameids));
                $this->where(array("member_id"=>$member_id))->update($data);

                $prefix = "mb_";
                $key = "mobilecontacts_{$member_id}";
                dcache($key,$prefix);
                return true;
            }
        }

        return false;
    }

    public function getRelations($member_id)
    {
        $data = array();
        if (isset($member_id) && !empty($member_id)) {
            $prefix = "mb_";
            $key = "mobilecontacts_{$member_id}";

            $ret = rcache($key,$prefix);
            if (empty($ret)) {
                $data =  $this->field('friend_contacts')->where(array("member_id"=>$member_id))->find();
                wcache($key,array("contacts_list"=>$data["friend_contacts"]),$prefix);
                $data = unserialize($data["friend_contacts"]);
            } else {
                $data = unserialize($ret["contacts_list"]);
            }
        }

        return $data;
    }
}