<?php

namespace Shop\Lib;

use Dever;

class Manage
{
    public function sellOrderPs($id, $name, $data)
    {
        Dever::config('base')->hook = true;
        $order_id = Dever::param('order_id', $data);
        if ($order_id) {
            $info = Dever::db('shop/sell_order')->find(array('id' => $order_id));
            if ($info && $info['status'] < 3) {
                Dever::load('shop/lib/sell')->notice($info);
            }
        }
    }

    # 获取规格型号
    public function getSku($goods_id, $sku_id)
    {
        $goods_info = Dever::load('goods/lib/info')->getInfoBySku($goods_id, $sku_id);
        if (isset($goods_info['sku'])) {
            $sku = $goods_info['sku']['string'];
        } else {
            $sku = '';
        }

        return $sku;
    }

    # 获取在途库存
    public function getGoodsTotal($type, $type_id, $goods_id, $sku_id)
    {
        $where['type'] = $type;
        $where['type_id'] = $type_id;
        $where['status'] = '2,3,4';
        $where['goods_id'] = $goods_id;
        $where['sku_id'] = $sku_id;
        $order = Dever::db('shop/buy_order_goods')->getGoodsTotal($where);
        if ($order && $order['total']) {
            return $order['total'];
        }
        return 0;
    }

    public function buyInfoRefundNum($id)
    {
        $where['status'] = 3;
        $where['order_id'] = $id;
        $order = Dever::db('shop/buy_order_goods')->getGoodsNum($where);
        if ($order && $order['total']) {
            return $order['total'];
        }
        return 0;
    }

    public function buyInfoRefundStatus($id, $table = 'buy_order')
    {
        $info = Dever::db('shop/' . $table)->find($id);
        if ($info['refund_cash'] > 0) {
            if ($info['status'] == 6 || $info['status'] == 8) {
                return '已退款';
            } else {
                return '有退款';
            }
        } elseif ($info['refund_status'] == 2) {
            return '已申请';
        } else {
            return '未申请';
        }
    }

    public function shopInfoType($type)
    {
        $config_type = Dever::db('shop/info')->config['config_type'];

        return $config_type[$type];
    }

    public function getTotalCash($id)
    {
        $order = Dever::db('shop/sell_order')->one($id);

        $cash = 0;
        $cash = $order['oprice'];
        return $cash;
    }

    public function getOrderUrl($order_id, $order_num, $search)
    {
        //$url = Dever::load('manage/database')->url('list', $order_id, 'buy_order_goods&project=shop&order_id='.$order_id.'&page_type=1');

        $url = Dever::url('project/database/list?project=cash&search_option_search=1&search_option_type=1&page_type=2&table=buy_order_goods&project=shop&order_id='.$order_id.'&page_type=1&menu=cash&menu_id=124&search_option_state=1', 'manage');
        if ($search == 3) {
            $url .= '&type=2&search_option_type=2';
        } elseif ($search == 2) {
            $url .= '&type=1&search_option_type=3';
        } else {
            $url .= '&type=1&search_option_type=1';
        }
        $url = '<a href="'.$url.'">'.$order_num.'</a>';
        return $url;
    }
    public function showCash($cash, $p_cash = 0)
    {
        if (!$cash) {
            $cash = 0;
        }

        if (!$p_cash) {
            $p_cash = 0;
        }

        return $cash - $p_cash;
    }
    # 获取用户信息
    public function user($id, $type = 1)
    {
        $info = Dever::db('shop/sell_order')->one($id);

        if ($info['uid'] && $info['uid'] > 0) {
            $user = Dever::db('passport/user')->one($info['uid']);

            $result = $user['username'];
            if ($type == 1 && $info['mobile']) {
                $result .= '('.$info['mobile'].')';
            }
        } else {
            $result = $info['mobile'];
        }
        
        return $result;
    }

    # 获取订单信息
    public function sell_order($id)
    {
        $table = array();
        $info = Dever::db('shop/sell_order')->one($id);

        $goods = Dever::db('shop/sell_order_goods')->select(array('order_id' => $info['id']));

        foreach ($goods as $k => $v) {
            $goods_info = Dever::load('goods/lib/info')->getInfoBySku($v['goods_id'], $v['sku_id']);
            //print_r($goods_info);die;
            $table[$goods_info['name']] = $v['price'];
        }
        
        return Dever::table($table);
    }

    /**
     * 更新信息
     *
     * @return mixed
     */
    public function upInfo($id, $name, $data)
    {
        Dever::config('base')->hook = true;
        
    }

    /**
     * 更新信息
     *
     * @return mixed
     */
    public function printInsert($id, $name, $data)
    {
        Dever::config('base')->hook = true;
        $name = Dever::param('name', $data);
        $number = Dever::param('number', $data);
        $phonenum = Dever::param('phonenum', $data);
        $key = Dever::param('key', $data);
        if ($number && $key) {
            $data = array();
            $data['name'] = $name;
            $data['number'] = $number;
            $data['phonenum'] = $phonenum;
            $data['key'] = $key;
            $result = Dever::load('mshop/lib/feieyun')->add(array($data));
            if (isset($result['no'][0]) && $result['no'][0] && strstr($result['no'][0], '编号不合法')) {
                Dever::db('shop/print')->update(array('where_id' => $id, 'status' => 10));
            } else {
                Dever::db('shop/print')->update(array('where_id' => $id, 'status' => 1));
            }
        }
    }

    /**
     * 更新信息
     *
     * @return mixed
     */
    public function printUpdate($id, $name, $data)
    {
        Dever::config('base')->hook = true;
        $info = Dever::db('shop/print')->one($id);
        $name = Dever::param('name', $data);
        $phonenum = Dever::param('phonenum', $data);
        if ($info && $name) {
            if ($info['status'] == 10) {
                $this->printInsert($id, $name, $info);
            } else {
                Dever::load('mshop/lib/feieyun')->edit($info['number'], $name, $phonenum);
            }
        }
    }

    /**
     * 打印机状态
     *
     * @return mixed
     */
    public function printStatus($status, $sn)
    {
        return $status >= 10 ? '绑定失败' : Dever::load('mshop/lib/feieyun')->status($sn);
    }

    public function buyOrderUpdate($id, $name, $data)
    {
        Dever::config('base')->hook = true;
        $update = array();
        $audit = Dever::param('audit', $data);
        $info = Dever::db('shop/buy_order')->one($id);
        if ($audit > 1 && $info && $info['status'] == 2) {
            if ($audit == 2) {
                # 成功
                Dever::setInput('order_id', $id);
                Dever::load('mshop/lib/buy.audit_commit');
            } else {
                # 退款
                $shop = Dever::db('shop/info')->find($info['type_id']);
                Dever::load('shop/lib/refund')->set('buy')->apply(1, $shop['id'], $id, false, 3, 0, '未通过审核');
            }
        }
    }

    public function sellOrderUpdate($id, $name, $data)
    {
        Dever::config('base')->hook = true;
        $update = array();
        $audit = Dever::param('audit', $data);
        $info = Dever::db('shop/sell_order')->one($id);
        if ($audit > 1 && $info && $info['status'] == 2) {
            if ($audit == 2) {
                # 成功
                Dever::setInput('order_id', $id);
                Dever::load('shop/lib/sell.audit_commit');
            } else {
                # 退款
                $shop = Dever::db('shop/info')->find($info['shop_id']);
                Dever::load('shop/lib/refund')->set('sell')->apply(1, $shop['id'], $id, false, 3, 0, '未通过审核');
            }
        }
    }

    /**
     * 更新信息
     *
     * @return mixed
     */
    public function couponUpdate($id, $name, $data)
    {
        Dever::config('base')->hook = true;
        $update = array();
        $coupon = Dever::param('coupon', $data);
        if ($coupon) {
            $temp = is_string($coupon) ? explode(',', $coupon) : $coupon;
            $update['method'] = $temp[0];
            $update['coupon_id'] = $temp[1];
        }

        $shop_id = Dever::param('shop_id', $data);
        if ($shop_id) {
            $shop = Dever::db('shop/info')->find($shop_id);
            $update['city'] = $shop['city'];
        }

        if (isset($update) && $update) {
            $update['where_id'] = $id;
            Dever::db('shop/coupon')->update($update);
        }
    }

    /**
     * 更新信息
     *
     * @return mixed
     */
    public function infoUpdate($id, $name, $data)
    {
        $update = array();
        $area = Dever::param('area', $data);
        if ($area) {
            $temp = is_string($area) ? explode(',', $area) : $area;
            $update['province'] = $temp[0];
            $update['city'] = $temp[1];
            if (isset($temp[2])) {
                $update['county'] = $temp[2];
            }
            if (isset($temp[3])) {
                $update['town'] = $temp[3];
            }

            if (is_array($area)) {
                $area = implode(',', $area);
            }
            $gup['option_shop_id'] = $id;
            $gup['set_area'] = $area;
            Dever::db('shop/goods_sku')->updates($gup);
            Dever::db('shop/sell_order')->updates($gup);

            unset($gup['option_shop_id']);
            $gup['option_type_id'] = $id;
            $gup['option_type'] = 1;
            Dever::db('shop/buy_order')->updates($gup);
            Dever::db('shop/out_order')->updates($gup);
        }

        $address = Dever::param('address', $data);
        if ($address && isset($update['city'])) {
            $geo = Dever::load('shop/lib/info')->geo($update['city'], $address);
            $update['lng'] = $geo[0];
            $update['lat'] = $geo[1];
            $update['map'] = $geo[2];
            $update['coord_address'] = $address;
        }

        /*
        $map = Dever::param('map', $data);
        if ($map) {
            $temp = is_string($map) ? explode(',', $map) : $map;
            if (isset($temp[1])) {
                $update['lng'] = $temp[1];
                $update['lat'] = $temp[2];

                $address = Dever::param('address', $data);
                $update['coord_address'] = Dever::load('shop/lib/info')->address($temp[1], $temp[2]);

                if (!$address && $update['coord_address']) {
                    $update['address'] = $update['coord_address'];
                }
            }
        }
        */

        $act = Dever::param('act', $data);
        if ($act) {
            foreach ($act as $k => $v) {
                $w = array();
                $w['shop_id'] = $id;
                $w['act_id'] = $k;
                foreach ($v as $k1 => $v1) {
                    $w['shop_coupon_id'] = $v1;
                    $info = Dever::db('shop/coupon_act')->find($w);
                    if (!$info) {
                        Dever::db('shop/coupon_act')->insert($w);
                    }
                }
            }
        }

        //Dever::upLinkage($update, $id, $data, 'goods', 'shop/goods', 'shop_id', 'goods_id', 'category_id');
        //Dever::upLinkage($update, $id, $data, 'factory', 'shop/factory', 'shop_id', 'factory_id', 'city');
        //Dever::upLinkage($update, $id, $data, 'store', 'shop/store', 'shop_id', 'store_id', 'city');

        if (isset($update) && $update) {
            $update['where_id'] = $id;
            Dever::db('shop/info')->update($update);
        }

        $truename = Dever::param('truename', $data);
        $mobile = Dever::param('mobile', $data);
        if ($mobile) {
            $member = Dever::db('shop/member')->one(array('shop_id' => $id, 'mobile' => $mobile));

            $update = array();
            $update['shop_id'] = $id;
            $update['name'] = $truename;
            $update['mobile'] = $mobile;
            if ($member) {
                $update['where_id'] = $member['id'];
                Dever::db('shop/member')->update($update);
            } else {
                Dever::db('shop/member')->insert($update);
            }
        }
    }

    private function updateParam()
    {

    }

    /**
     * 更新商品信息
     *
     * @return mixed
     */
    public function goodsUpdate($id, $name, $data)
    {
        $update = array();
        $state = Dever::param('state', $data);
        if ($state) {
            Dever::config('base')->after = true;
            $info = Dever::db('shop/goods')->one($id);
            $shop_id = $info['shop_id'];

            $shop = Dever::db('shop/info')->one($shop_id);

            if ($shop && $shop['goods']) {
                $goods = Dever::json_decode($shop['goods']);

                if (isset($goods['level_' . $info['category_id']]['value']['id_' . $info['goods_id']])) {
                    if ($state == 2) {
                        unset($goods['level_' . $info['category_id']]['value']['id_' . $info['goods_id']]);
                    }

                    if (count($goods['level_' . $info['category_id']]['value']) <= 0) {
                        unset($goods['level_' . $info['category_id']]);
                    }
                } elseif ($state == 1) {
                    $goods_info = Dever::db('goods/info')->one($info['goods_id']);
                    $cate = Dever::load('category/api')->string($info['category_id']);
                    $goods['level_' . $info['category_id']]['id'] = $info['category_id'];
                    $goods['level_' . $info['category_id']]['name'] = $cate;
                    $goods['level_' . $info['category_id']]['value']['id_' . $info['goods_id']] = array
                    (
                        'id' => $info['goods_id'],
                        'name' => $goods_info['name'],
                        'state' => 1,
                    );
                }
                
                $set['goods'] = Dever::json_encode($goods);
                $set['where_id'] = $shop_id;
                Dever::db('shop/info')->update($set);
            }
        }
    }

    /**
     * 更新库存信息
     *
     * @return mixed
     */
    public function skuUpdate($id, $name, $data)
    {
        $update = array();
        $add_num = Dever::param('add_num', $data);
        if ($add_num) {
            $state = Dever::db('shop/goods_sku')->updateTotal(array('where_id' => $id, 'total_num' => $add_num));
            if ($state) {
                $state = Dever::db('shop/goods_sku')->update(array('where_id' => $id, 'add_num' => 0));
                $info = Dever::db('shop/goods_sku')->one($id);
                $goods = Dever::db('shop/goods')->one(array('goods_id' => $info['goods_id'], 'shop_id' => $info['shop_id']));
                if ($goods) {
                    Dever::db('shop/goods')->update(array('where_id' => $goods['id'], 'total_num' => $info['total_num'], 'add_num' => 0));
                }

                if ($add_num < 0) {
                    # 记录出库日志
                } else {
                    # 记录入库日志
                }
            }
        }
    }

    # 获取供货商信息
    public function buyInfo($type = '', $type_id = '')
    {
        if ($type == 1) {
            $type_info = Dever::db('shop/info')->one($type_id);
            return $type_info['name'] . '('.$type_info['mobile'].')';
        } elseif ($type == 2) {
            $type_info = Dever::db('store/info')->one($type_id);
            $sign = Dever::login($type_id);
            $link = Dever::url('home?sign=' . $sign, 'store');
            //return $type_info['name'] . '('.$type_info['mobile'].')<br /><a href="'.$link.'" target="_blank">进入仓库管理</a>';
            return $type_info['name'] . '('.$type_info['mobile'].')';
        } elseif ($type == 3) {
            $sign = Dever::login($type_id);
            $link = Dever::url('home?sign=' . $sign, 'factory');
            $type_info = Dever::db('factory/info')->one($type_id);
            //return $type_info['name'] . '('.$type_info['mobile'].')<br /><a href="'.$link.'" target="_blank">进入工厂管理</a>';
            return $type_info['name'] . '('.$type_info['mobile'].')';
        } else {
            return '无';
        }
    }

    /**
     * 更新信息
     *
     * @return mixed
     */
    public function buyOrderPs($id, $name, $data)
    {
        $order_id = Dever::param('order_id', $data);
        if ($order_id) {
            $update['where_id'] = $order_id;
            $update['set_status'] = 4;
            Dever::db('shop/buy_order')->update($update);
        }
    }

    # 获取门店
    public function search_api()
    {
        return Dever::search('shop/info');
    }

    # 获取环比增长
    public function getGoodsHb($num, $day, $goods_id)
    {
        $where = array('day' => $day, 'goods_id' => $goods_id);
        $search = Dever::search_button();
        if ($search) {
            $where['config']['group'] = $search[0];
            $where['config']['col'] = str_replace('|id', '', $search[1]);
        }
        if ($num < 0) {
            $num = 0;
        }
        $prev = Dever::db('shop/goods_stat')->prev($where);
        if ($prev && $num > 0 && $prev['num'] >= 0) {
            $n = $prev['num'];
            if ($n == 0) {
                $n = 1;
            }
            $hb = round(($num-$prev['num'])/$n, 2)*100;
        } else {
            $hb = 0;
        }

        return $hb . '%';
    }

    public function getUserHb($num, $total, $day)
    {
        $result = $this->getUserStat($num, $total, 0);
        $where = array('day' => $day);
        $search = Dever::search_button();
        if ($search) {
            $where['config']['group'] = $search[0];
            $where['config']['col'] = str_replace('|id', '', $search[1]);
        }
        $hb = 0;
        $prev = Dever::db('shop/user_stat')->prev($where);
        if ($prev) {
            $prev = $this->getUserStat($prev['num'], $prev['total'], $prev['order_num']);
            if ($result['fg'] > 0 && $prev['fg'] >= 0) {
                $fg = $prev['fg'];
                if ($fg == 0) {
                    $fg = 1;
                }
                $hb = round(($result['fg']-$prev['fg'])/$fg, 2)*100;
            }
        }

        return $hb . '%';
    }

    public function getUserStat($num, $total, $order_num)
    {
        //print_r($info);die;
        if ($num && $total) {
            $result['fg'] = round($num/$total, 2);
        } else {
            $result['fg'] = 0;
        }

        if ($order_num) {
            $result['per_num'] = round($order_num/$total, 2);
        } else {
            $result['per_num'] = 0;
        }
        
        return $result;
    }

    # 获取环比增长
    public function getUserRankHb($num, $mobile, $day)
    {
        $where = array('day' => $day, 'mobile' => $mobile);
        $search = Dever::search_button();
        if ($search) {
            $where['config']['group'] = $search[0];
            $where['config']['col'] = str_replace('|id', '', $search[1]);
        }
        if ($num < 0) {
            $num = 0;
        }
        $prev = Dever::db('shop/user_rank_stat')->prev($where);
        if ($prev && $num > 0 && $prev['num'] >= 0) {
            $n = $prev['num'];
            if ($n == 0) {
                $n = 1;
            }
            $hb = round(($num-$prev['num'])/$n, 2)*100;
        } else {
            $hb = 0;
        }

        return $hb . '%';
    }

    # 确认收货
    public function setSellOrderStatus_api()
    {
        $order_id = Dever::input('order_id');

        $info = Dever::db('shop/sell_order')->find($order_id);
        if ($info) {
            Dever::load('shop/lib/sell')->finish($info, $info['shop_id']);
            return 'reload';
        } else {
            Dever::alert('错误的订单号');
        }
    }

    public function searchName($where)
    {
        $data = Dever::db('store/info')->like($where);
        if (!$data) {
            $data = Dever::db('shop/info')->like($where);
        }

        return $data;
    }

    public function searchFName($where)
    {
        $data = Dever::db('store/info')->like($where);
        if (!$data) {
            $data = Dever::db('factory/info')->like($where);
        }

        return $data;
    }
}