<?php
/**
 * Copyright (C) LJCMS All rights reserved.
 * <E-Mail：aspcms@qq.com>
 * Url http://www.liangjing.org
 *     http://www.8CMS.com
 * Update 2016.03.19
 */

class productIModel extends X
{

    public function getList($items)
    {
        $lang     = parent::$lang;
        $pagesize = intval($items['pagesize']);
        $where    = " WHERE v.flag='1' " . $items['searchsql'];
        $start    = ($items['page'] - 1) * $pagesize;
        $countsql = "SELECT COUNT(*) AS my_count FROM " . DB_PREFIX . "product AS v" . $where;
        $total    = parent::$obj->fetch_count($countsql);
        $sql      = "SELECT v.*,c.catname,c.asname,c.dirname,c.catpic" .
            ",c.linktype AS catlinktpye,c.outurl" .
            " FROM " . DB_PREFIX . "product AS v" .
            " LEFT JOIN " . DB_PREFIX . "category AS c ON v.catid=c.catid" .
            $where . $items['orderby'] . " LIMIT " . $start . ", " . $pagesize . "";
        $data     = parent::$obj->getall($sql);
        return array($total, $this->_handleList($data));
    }


    public function getVolist($where = '', $orderby = '', $num = 0, $limit = '', $type = NULL)
    {
        $lang = parent::$lang;
        $sql  = "SELECT v.*,c.catname,c.asname,c.dirname,c.catpic,c.linktype AS catlinktpye,c.outurl" .
            " FROM " . DB_PREFIX . "product AS v" .
            " LEFT JOIN " . DB_PREFIX . "category AS c ON v.catid=c.catid" .
            " WHERE v.flag='1' AND v.elite='1' AND v.lang='$lang'";
        $sql  .= !empty($where) ? ' AND ' . $where : '';
        $sql  .= !empty($orderby) ? ' ' . $orderby : ' ORDER BY v.addtime DESC';
        if (!empty($limit)) {
            $sql .= " LIMIT {$limit}";
        } else {
            $num = intval($num) < 1 ? intval(parent::$cfg['productnum']) : intval($num);
            $sql .= " LIMIT {$num}";
        }
        $data = parent::$obj->getall($sql);
        return $this->_handleList($data, $type);
    }


    public function getOneData($id)
    {
        $data = $attr_data = $catdata = array();
        $sql  = "SELECT v.*, c.dirname, m.tpldetail AS mod_tpldetail" .
            " FROM " . DB_PREFIX . "product AS v" .
            " LEFT JOIN " . DB_PREFIX . "category AS c ON v.catid=c.catid" .
            " LEFT JOIN " . DB_PREFIX . "module AS m ON v.modalias=m.alias" .
            " WHERE v.productid='{$id}'";
        $data = parent::$obj->fetch_first($sql);
        if (!empty($data)) {
            #URL路由
            $m_label = parent::model('label', 'im');
            if ($data['linktype'] == 2) {
                $data['url']    = $m_label->repLabel($data['linkurl']);
                $data['wapurl'] = $m_label->repLabel($data['linkurl']);
            } else {
                $data['url']    = XUrl::getContentUrl('product', $data['dirname'], $data['productid']);
                $data['wapurl'] = XUrl::getContentWapUrl('product', $data['productid']);
            }
            unset($m_label);
            #图片处理
            if (empty($data['thumbfiles'])) {
                $data['thumbfiles'] = parent::$urlpath . 'tpl/static/images/nopic_s.jpg';
            } else {
                if (substr($data['thumbfiles'], 0, 15) == 'data/attachment') {
                    $data['thumbfiles'] = parent::$urlpath . $data['thumbfiles'];
                }
            }
            if (empty($data['uploadfiles'])) {
                $data['uploadfiles'] = parent::$urlpath . 'tpl/static/images/nopic.jpg';
            } else {
                if (substr($data['uploadfiles'], 0, 15) == 'data/attachment') {
                    $data['uploadfiles'] = parent::$urlpath . $data['uploadfiles'];
                }
            }

            $m_atrr      = parent::model('modattr', 'im');
            $attr_data   = $m_atrr->getAttrList('product', $id);
            $extend_data = $m_atrr->assembleAttr('product', $id);
            if (!empty($extend_data)) {
                $data = array_merge($data, $extend_data);
            }
            unset($m_atrr);


            $m_category = parent::model('category', 'im');
            $catdata    = $m_category->getOneData(intval($data['catid']));
            unset($m_category);

            $this->_updateHits($id);

            $data['gallery'] = XHandle::dounSerialize($data['albums']);
            if (is_array($data['gallery'])) {
                $i = 1;
                foreach ($data['gallery'] as $k => $v) {
                    $data['gallery'][$k]['i'] = $i;
                    if (substr($v['imgurl'], 0, 15) == 'data/attachment') {
                        $data['gallery'][$k]['imgurl'] = parent::$urlpath . $v['imgurl'];
                    }
                    if (substr($v['imgthumb'], 0, 15) == 'data/attachment') {
                        $data['gallery'][$k]['imgthumb'] = parent::$urlpath . $v['imgthumb'];
                    }
                    $i++;
                }
                unset($i);
            }


            $m_link          = parent::model('relatedlink', 'im');
            $data['content'] = $m_link->tagContent('product', $data['content']);
            unset($m_link);
        }
        return array($data, $attr_data, $catdata);
    }


    public function getPrevious($treeid, $id)
    {
        $treeid = intval($treeid);
        $id     = intval($id);
        $query  = "SELECT v.*, c.dirname" .
            " FROM " . DB_PREFIX . "product AS v" .
            " LEFT JOIN " . DB_PREFIX . "category AS c ON v.catid=c.catid" .
            " WHERE v.productid<{$id} AND v.flag='1' AND v.treeid='{$treeid}'" .
            " ORDER BY v.productid DESC LIMIT 1";
        $rows   = parent::$obj->fetch_first($query);
        if (!empty($rows)) {
            #URL路由
            if ($rows['linktype'] == 2) {
                $m_label        = parent::model('label', 'im');
                $rows['url']    = $m_label->repLabel($rows['linkurl']);
                $rows['wapurl'] = $m_label->repLabel($rows['linkurl']);
                unset($m_label);
            } else {
                $rows['url']    = XUrl::getContentUrl('product', $rows['dirname'], $rows['productid']);
                $rows['wapurl'] = XUrl::getContentWapUrl('product', $rows['productid']);
            }
        }
        unset($query, $treeid, $id);
        return $rows;
    }


    public function getNext($treeid, $id, $style = NULL)
    {
        $treeid = intval($treeid);
        $id     = intval($id);
        $query  = "SELECT v.*, c.dirname" .
            " FROM " . DB_PREFIX . "product AS v" .
            " LEFT JOIN " . DB_PREFIX . "category AS c ON v.catid=c.catid" .
            " WHERE v.productid>{$id} AND v.flag='1' AND v.treeid='{$treeid}'" .
            " ORDER BY v.productid ASC LIMIT 1";
        $rows   = parent::$obj->fetch_first($query);
        if (!empty($rows)) {
            #URL路由
            if ($rows['linktype'] == 2) {
                $m_label        = parent::model('label', 'im');
                $rows['url']    = $m_label->repLabel($rows['linkurl']);
                $rows['wapurl'] = $m_label->repLabel($rows['linkurl']);
                unset($m_label);
            } else {
                $rows['url']    = XUrl::getContentUrl('product', $rows['dirname'], $rows['productid']);
                $rows['wapurl'] = XUrl::getContentWapUrl('product', $rows['productid']);
            }
        }
        unset($query, $treeid, $id);
        return $rows;
    }


    private function _handleList($data, $type = NULL)
    {
        if (!empty($data)) {
            $i = 1;
            foreach ($data as $key => $value) {
                #URL路由
                $m_label = parent::model('label', 'im');
                if ($value['catlinktype'] == 2) {
                    $data[$key]['caturl'] = $m_label->repLabel($value['outurl']);
                    $data[$key]['wapurl'] = $m_label->repLabel($value['outurl']);
                } else {
                    $data[$key]['caturl'] = XUrl::getCategoryUrl('product', $value['catid'], $value['dirname']);
                    $data[$key]['wapurl'] = XUrl::getCategoryWapUrl('product', $value['catid']);
                }
                if ($value['linktype'] == 2) {
                    $data[$key]['url']    = $m_label->repLabel($value['linkurl']);
                    $data[$key]['wapurl'] = $m_label->repLabel($value['linkurl']);
                } else {
                    $data[$key]['url']    = XUrl::getContentUrl('product', $value['dirname'], $value['productid']);
                    $data[$key]['wapurl'] = XUrl::getContentWapUrl('product', $value['productid']);
                }
                unset($m_label);
                #图片处理
                if (empty($value['thumbfiles'])) {
                    $data[$key]['thumbfiles'] = parent::$urlpath . 'tpl/static/images/nopic_s.jpg';
                } else {
                    if (substr($value['thumbfiles'], 0, 15) == 'data/attachment') {
                        $data[$key]['thumbfiles'] = parent::$urlpath . $value['thumbfiles'];
                    }
                }
                if (empty($value['uploadfiles'])) {
                    $data[$key]['uploadfiles'] = parent::$urlpath . 'tpl/static/images/nopic.jpg';
                } else {
                    if (substr($value['uploadfiles'], 0, 15) == 'data/attachment') {
                        $data[$key]['uploadfiles'] = parent::$urlpath . $value['uploadfiles'];
                    }
                }
                #标题处理
                $data[$key]['sort_productname'] = XHandle::cutStrLen($value['productname'], parent::$cfg['productlen']);
                $data[$key]['i']                = $i;
                $i                              = ($i + 1);
            }
        }
        return $data;
    }


    private function _updateHits($id)
    {
        parent::$obj->update(DB_PREFIX . 'product', array('hits' => '[[hits+1]]'), 'productid=' . $id . '');
    }

    public function getprovince()
    {
        $sql = "SELECT * FROM " . DB_PREFIX . "region WHERE parent_id='0' AND level='1'";
        return parent::$obj->getall($sql);
    }

    public function getcity()
    {
        $sql = "SELECT * FROM " . DB_PREFIX . "region WHERE level='2'";
        return parent::$obj->getall($sql);
    }

    public function getares()
    {
        $sql = "SELECT * FROM " . DB_PREFIX . "region WHERE level='3'";
        return parent::$obj->getall($sql);
    }

    public function getregion($id, $level)
    {
        $sql = "SELECT * FROM " . DB_PREFIX . "region WHERE parent_id='$id' AND level='$level'";
        return parent::$obj->getall($sql);
    }

    public function getregionname($id)
    {
        $sql  = "SELECT * FROM " . DB_PREFIX . "region WHERE id='$id'";
        $data = parent::$obj->fetch_first($sql);
        return $data['name'];
    }

    public function addorder($arr)
    {
        return parent::$obj->insert(DB_PREFIX . 'order', $arr);
    }

    public function getorderinfo($number)
    {
        $sql  = "SELECT * FROM " . DB_PREFIX . "order WHERE ordernum='$number'";
        $data = parent::$obj->fetch_first($sql);
        return $data;
    }

    public function addlog($arr)
    {
        return parent::$obj->insert(DB_PREFIX . 'account_log', $arr);
    }

    public function payorder($number)
    {
        $info['status'] = '待发货';
        return parent::$obj->update(DB_PREFIX . 'order', $info, 'ordernum=' . $number . '');
    }
    public function confirmorder($number)
    {
        $info['status'] = '已完成';
        return parent::$obj->update(DB_PREFIX . 'order', $info, 'ordernum=' . $number . '');
    }
    public function confirmgoodsorder($number){
        $info['status'] = '已完成';
        $info['sendtime'] = time();
        return parent::$obj->update(DB_PREFIX . 'order_info', $info, 'ordernum=' . $number . '');
    }
    public function doEdit($id, $array)
    {
        $result = parent::$obj->update(DB_PREFIX . 'order', $array, 'id=' . $id . '');
        return $result;
    }

    public function getuseraddressinfo($id)
    {
        $sql = "SELECT * FROM " . DB_PREFIX . "member_address WHERE user_id='" . $id . "' AND is_mo='1'";
        return parent::$obj->fetch_first($sql);
    }

    public function checkorder($pid,$uid){
       $sql = "SELECT * FROM ".DB_PREFIX."order WHERE goodsid='".$pid."' AND status='待付款' AND user_id='".$uid."'";
       return parent::$obj->fetch_first($sql);
    }

    public function goshopping($downloadid,$username){
       $sql = "SELECT * FROM ".DB_PREFIX."shopping WHERE productid='".$downloadid."' AND userid='".$username."'";
       return parent::$obj->fetch_first($sql);
    }
    public function shopping($downloadid,$username){
       $sql = "SELECT * FROM ".DB_PREFIX."shopping WHERE productid='".$downloadid."' AND userid='".$username."'";
       return parent::$obj->getall($sql);
    }
    public function shoppings($arr){
          return parent::$obj->insert(DB_PREFIX.'shopping', $arr); 
    }
        public function getusershopping($user_id){
            $sql = "SELECT * FROM  ".DB_PREFIX."shopping WHERE userid='".$user_id."'";
           return parent::$obj->getall($sql);

        }
    public function getuserbuyshopping($user_id){
        $sql = "SELECT * FROM  ".DB_PREFIX."shopping WHERE userid='".$user_id."' AND selected='1'";
        return parent::$obj->getall($sql);

    }
    public function updateshopping($downloadid,$username,$buynum){
        $array['productnum']=$buynum;
        $array['selected']=1;
        $result = parent::$obj->update(DB_PREFIX . 'shopping', $array, 'productid=' . $downloadid . ' AND userid='.$username.'');
        return $result;
       //$sql = "UPDATE ".DB_PREFIX."shopping SET productnum='".$buynum."''check'='1' WHERE productid='".$downloadid."' AND userid='".$username."'";
      // return parent::$obj->query($sql);
    }
    public function updateselected($username){
        //先将所有选中变为不选中
        $arr['selected']=0;
        parent::$obj->update(DB_PREFIX . 'shopping', $arr,  'userid='.$username.'');
    }
    public function deluserorder($userid){
       $sql = "DELETE FROM ".DB_PREFIX."order WHERE status='待付款' AND time<'".(time()-480)."'";
       return parent::$obj->getall($sql);
    }
    public function delshopping($userid){
       $sql = "DELETE FROM ".DB_PREFIX."shopping WHERE userid='".$userid."' AND selected='1'";
       return parent::$obj->query($sql);
    }

    public function submitorderinfo($omber,$gnme,$gpic,$gnum,$opic,$sts,$uid,$img){
        $oderinfo['ordernum'] = $omber;
        //$oderinfo['goodsid'] = $gid;
        $oderinfo['goodsname'] = $gnme;
        $oderinfo['goodsprice'] = $gpic;
        $oderinfo['goodsnum'] = $gnum;
        $oderinfo['orderprice'] = $opic;
        // $oderinfo['buyordertime'] = $buytime;
        $oderinfo['status'] = $sts;
        $oderinfo['user_id'] = $uid;
        $oderinfo['goodsimg'] = $img;
        return parent::$obj->insert(DB_PREFIX.'order_info', $oderinfo); 
    }
    public function updateorderinfo($omber,$odrid,$uid){
        $oderinfo['orderid'] = $odrid;
        return parent::$obj->update(DB_PREFIX.'order_info', $oderinfo, 'ordernum='.$omber.''); 
    }

    public function doEditStock($id, $stocknumber) {
        $sql = "SELECT * FROM ".DB_PREFIX."product WHERE productid='".$id."'";
        $data = parent::$obj->fetch_first($sql);
        if ($data['stock'] < $stocknumber) {
            # code...
        } else {
            $info['stock'] = $data['stock'] - $stocknumber;
            return parent::$obj->update(DB_PREFIX.'product', $info, 'productid='.$id.'');
        }
    }
    
    public function delshous($id) {
        $sql = "DELETE FROM ".DB_PREFIX."shopping WHERE id='".intval($id)."' OR productid='".intval($id)."'";
        
          return parent::$obj->query($sql);
    }

}
?>
