<?php
/**
 * 我的地址
 *
 *
 *
 *
 */

//use Shopnc\Tpl;

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

require_once(BASE_ROOT_PATH . '/helper/search/tcp_client.php');
require_once(BASE_ROOT_PATH . '/helper/session_helper.php');


class member_addressControl extends mbMemberControl
{
    const MAX_ADDRESS_COUNT = 50;

    public function __construct()
    {
        parent::__construct();
    }

    public function address_listOp()
    {
        $model_address = Model('address');
        $address_list = $model_address->getAddressList(array('member_id' => $_SESSION['member_id']));
        self::outsuccess(array('address_list' => $address_list), 'shop/choose_address');
    }
    public function address_infoOp()
    {
        $address_id = intval($_POST['address_id']);
        if (empty($_POST['address_id']) || $address_id < 0) {
            return self::outerr(errcode::ErrParamter, "address_id = {$address_id}. must > 0.");
        }

        $model_address = Model('address');
        $address_info = $model_address->getAddressInfo(array('address_id' => $address_id,'member_id' => $_SESSION['member_id']));
        if (!empty($address_info)) {
            self::outsuccess($address_info, 'shop/update_address');
        } else {
            return self::outerr(errcode::ErrAddress, '地址不存在');
        }
    }

    public function address_delOp()
    {
        $address_id = intval($_POST['address_id']);
        if (empty($_POST['address_id']) || $address_id < 0) {
            return self::outerr(errcode::ErrParamter, "address_id = {$address_id}. must > 0.");
        }

        $model_address = Model('address');
        $model_address->delAddress(array('address_id' => $address_id,'member_id' => $_SESSION['member_id']));
        session_helper::clear_addr();
        $default_address_info = $model_address->getDefaultAddressInfo(array('member_id' => $_SESSION['member_id']));
        if (intval($default_address_info['is_default']) === 0) {
            $this->_set_default($default_address_info['address_id'], 1);
        }
        self::outsuccess(array('result' => '1'));
    }

    /**
     * 新增地址
     */
    public function address_addOp()
    {
        $model_address = Model('address');
        $address_info = $this->_address_valid($err, $err_code);
        if ($err != '') {
            return self::outerr($err_code, $err);
        }

        $addr_acount = $model_address->getAddressCount(array('member_id' => $_SESSION['member_id']));
        if ($addr_acount >= self::MAX_ADDRESS_COUNT) {
            return self::outerr(errcode::ErrAddress, '地址数量已达上限');
        }

        $result = $model_address->addAddress($address_info);
        if ($result)
        {
            $addr_acount = $model_address->getAddressCount(array('member_id' => $_SESSION['member_id']));
            if (intval($addr_acount) === 1) {
                $this->_set_default($result, 1);
                session_helper::clear_addr();
            }
            self::outsuccess(array('address_id' => $result));
        } else {
            return self::outerr(errcode::ErrAddress, '保存失败');
        }
    }

    /**
     * 编辑地址
     */
    public function address_editOp()
    {
        $address_id = intval($_POST['address_id']);
        if (empty($_POST['address_id']) || $address_id < 0) {
            return self::outerr(errcode::ErrParamter, "address_id = {$address_id}. must > 0.");
        }

        $model_address = Model('address');
        $address_info = $model_address->getOneAddress($address_id);
        //验证地址是否为本人
        if ($address_info['member_id'] != $_SESSION['member_id']) {
            return self::outerr(errcode::ErrAddress, '参数错误');
        }
        else
        {
            $address_info = $this->_address_valid($err, $errcode);
            if(empty($address_info)) {
                self::outerr($errcode,$err);
            }
            else
            {
                $result = $model_address->editAddress($address_info, array('address_id' => $address_id));
                if ($result) {
                    session_helper::clear_addr();
                    self::outsuccess(array('result' => '1'));
                } else {
                    return self::outerr(errcode::ErrAddress, '保存失败');
                }
            }
        }
    }

    /**
     * 验证地址数据
     */
    private function _address_valid(&$err, &$errcode)
    {
        $obj_validate = new Validator();
        $obj_validate->validateparam = array(
            array("input" => $_POST["true_name"], "require" => "true", "message" => '姓名不能为空'),
            array("input" => $_POST["address"], "require" => "true", "message" => '地址不能为空'),
            Validator::verify_mobile($_POST['mob_phone'])
        );

        $err = $obj_validate->validate();
        if ($err != '') {
            $errcode = errcode::ErrAddress;
            return NULL;
        }

        $area_id = intval($_POST['area_id']);
        $area = search\search_client::instance()->get_area($area_id);
        if ($area == false || $area['result'] == false) {
            $errcode = errcode::ErrAddress;
            return NULL;
        }

        $data = array();
        $data['member_id'] = $_SESSION['member_id'];
        $data['true_name'] = urldecode($_POST['true_name']);

        $data['area_id'] = intval($area['country']['area_id']);
        $data['city_id'] = intval($area['city']['area_id']);
        $data['area_info'] = "{$area['province']['area_name']}\t{$area['city']['area_name']}\t{$area['country']['area_name']}";

        $data['address'] = urldecode($_POST['address']);
        $data['tel_phone'] = '';
        $data['mob_phone'] = $_POST['mob_phone'];

        return $data;
    }

    /**
     * 编辑地址
     */
    public function set_defaultOp()
    {
        $address_id = intval($_POST['address_id']);
        $is_default = intval($_POST['is_default']);

        $model_address = Model('address');
        //验证地址是否为本人
        $address_info = $model_address->getOneAddress($address_id);
        if ($address_info['member_id'] != $_SESSION['member_id']) {
            return self::outerr(errcode::ErrAddress, '参数错误');
        }
        else
        {
            $ret = $this->_set_default($address_id, $is_default);
            if ($ret) {
                return self::outsuccess(array('result' => '1'));
            } else {
                return self::outerr($ret['code'], $ret['msg']);
            }
        }
    }

    private function _set_default($address_id, $is_default)
    {
        $member_id = $_SESSION['member_id'];
        $model = Model('address');
        if ($is_default === 1)
        {
            if ($model->editAddress(array('is_default' => '0'),array('member_id' => $member_id)) &&
                $model->editAddress(array('is_default' => '1'),array('address_id' => $address_id))) {
                return true;
            } else {
                return array('code' => errcode::ErrAddress, 'msg' => '保存失败');
            }
        }
        else {
            $area = $model->editAddress(array('is_default' => '0'),array('address_id' => $address_id));
        }

        if ($area) {
            return true;
        } else {
            return array('code' => errcode::ErrAddress, 'msg' => '保存失败');
        }
    }

    /**
     * 地区列表
     */
    public function area_listOp()
    {
        $prefix = "mb_";

        $area_id = intval($_POST['area_id']);
        if ($area_id > 0) {
            $key = "area_parent_id_{$area_id}";
        } else {
            $key = "area_deep_1";
        }

        $from = $_POST['from'];
        if($from === 'app') {
            $key = "app_{$key}";
        }

        $ret = rcache($key,$prefix);
        if(empty($ret))
        {
            $model_area = Model('area');

            if ($from === 'app') {
                $area_list = $this->get_area_list($area_id);
            }
            else
            {
                $condition = array();
                if ($area_id > 0) {
                    $condition['area_parent_id'] = $area_id;
                } else {
                    $condition['area_deep'] = 1;
                }
                $area_list = $model_area->getAreaList($condition, 'area_id,area_name');
            }
            wcache($key,array("area_list" => serialize($area_list)),$prefix);
        }
        else {
            $area_list = unserialize($ret['area_list']);
        }

        self::outsuccess(array('area_list' => $area_list));
    }

    private function get_area_list($area_id)
    {
        $model_area = Model('area');
        $condition = array();
        if ($area_id > 0) {
            $condition['area_parent_id'] = $area_id;
        } else {
            $condition['area_deep'] = 1;
        }
        $area_list = $model_area->getAreaList($condition, 'area_id,area_name');
        foreach ($area_list as $k => $area) {
            $area_list_by_id = $this->get_area_list($area['area_id']);
            if (count($area_list_by_id) > 0) {
                $area_list[$k]['area_list'] = $area_list_by_id;
            }
        }
        return $area_list;
    }
}

class tpl_address
{
    private $out_put;
    private $address;
    private $address_list;
    public function __construct($out_put)
    {
        $this->out_put = $out_put;
        $this->address = $this->out_put['address'];
        $this->address_list = $this->out_put['address_list'];
    }

    public function show_address_list()
    {
        $goods_id = cookie('goods_id');
        $number = cookie('number');
        $card_id = $goods_id."|".$number;
        foreach ($this->address_list as $key => $adlist)
        {
            if ($adlist['is_default']=='1') {
                $address_id = $adlist['address_id'];
                $herf_edit  = MOBILE_SITE_URL . '/index.php?act=member_address&op=address_info&address_id='.$adlist['address_id'];
                $herf_first = MOBILE_SITE_URL.'/index.php?client_type=wap&act=member_buy&op=step_first'.'&cart_id='.$card_id
                    .'&address_id='.$address_id.'&goods_id='.$goods_id.'&number='.$number;
                echo "<div class=\"item-content default_address\">
                      <a href='{$herf_first}' external><div class=\"row item-top\">                
                        <div class=\"col-50\">{$adlist['true_name']}</div>
                        <div class=\"col-50\">{$adlist['mob_phone']}</div>
                    </div>
                    <div class=\"row item\">
                        <div class=\"col-80\">
                            <span class=\"default_title\">[默认地址]</span>{$adlist['area_info']}{$adlist['address']}
                        </div>
                    </div></a>                               
                    <a href=\"{$herf_edit}\" class=\"pull-right external\">
                        <span class=\"icon icon-rev\"></span>
                    </a>
                </div>";
                unset($this->address_list[$key]);
            }
        }

        foreach ($this->address_list as $adlist) {
            $address_id = $adlist['address_id'];
            $herf_edit = MOBILE_SITE_URL . '/index.php?act=member_address&op=address_info&address_id='.$adlist['address_id'];
            $herf_first = MOBILE_SITE_URL.'/index.php?client_type=wap&act=member_buy&op=step_first'.'&cart_id='.$card_id
            .'&address_id='.$address_id.'&goods_id='.$goods_id.'&number='.$number;

            echo "  <div class=\"item-content\">
                 <a href='{$herf_first}' external><div class=\"row item-top\">
                    <div class=\"col-50\">{$adlist['true_name']}</div>
                    <div class=\"col-50\">{$adlist['mob_phone']}</div>
                </div>
                <div class=\"row\">
                    <div class=\"col-80\">
                        {$adlist['area_info']}{$adlist['address']}
                    </div>
                </div>
                </a> 
                <span class=\"pull-right icon icon-rev\"></span>
                <a href=\"{$herf_edit}\" class=\"pull-right external\">
                    <span class=\"icon icon-rev\"></span>
                </a>
            </div>";
        }
    }
    public function show_edit()
    {
        echo
            "<div class=\"list-block\">
                <ul>
                    <li class=\"item-content\">
                        <div class=\"item-inner list_padding_left row\">
                            <div class=\"col-25\"><label for=\"username\">收件人姓名</label></div>
                            <div class=\"col-75\"><input type=\"text\" value=\"{$this->single_info['true_name']}\" name=\"true_name\" id=\"username\"/></div>
                        </div>
                    </li>
                    <li class=\"item-content\">
                        <div class=\"item-inner list_padding_left row\">
                            <div class=\"col-25\"><label for=\"telphone\">手机号码</label></div>
                            <div class=\"col-75\"><input type=\"text\" value=\"{$this->single_info['mob_name']}\" name=\"mob_phone\" id=\"telphone\"/></div>
                        </div>
                    </li>
                    <li class=\"item-content\">
                        <div class=\"item-inner list_padding_left row\">
                            <div class=\"col-25\"><label for=\"city-picker\">所在区域</label></div>
                            <div class=\"col-75\"><input type=\"text\" value=\"{$this->single_info['area_info']}\" name=\"area_info\" id=\"city-picker\"/></div>
                        </div>
                    </li>
                    <li class=\"item-content\">
                        <div class=\"item-inner list_padding_left row\">
                            <div class=\"col-25\"><label for=\"address\">详细地址</label></div>
                            <div class=\"col-75\"><input type=\"text\" value=\"{$this->single_info['address']}\" name=\"address\" id=\"address\"/></div>
                        </div>
                    </li>
                </ul>
            </div>";

        echo
            "<div class=\"default_btn\">
                <label><input class=\"icon_check\" type=\"checkbox\" value=\"1\" name=\"default_id\"/>设置为默认地址</label>
            </div>";

    }

}
