<?php namespace Place\Lib;
use Dever;
use Place;
class Resource
{
    public $app;
    public $type;
    protected $db;
    protected $where;
    protected $set;
    public function __construct($type)
    {
        $this->type = $type;
        if (!$this->type) {
            Dever::error('资源参数错误');
        }
        if (isset(Dever::config('setting')['type'][$this->type])) {
            $this->app = Dever::config('setting')['type'][$this->type];
            $this->db = Dever::db('info', $this->app);
        } else {
            Dever::error('资源参数错误');
        }
        $this->where = array('status' => 1);
        $this->set['col'] = Dever::load('info', $this->app)->getCol();
    }

    # 获取列表
    public function getList($cate = false, $id = false, $num = 10)
    {
        if ($cate) {
            $cate = explode(',', $cate);
            $this->where['cate_parent_id'] = $cate[0];
            if (isset($cate[1])) {
                $this->where['cate_child_id'] = $cate[0];
            }
        }
        $name = Dever::input('search');
        if ($name) {
            $this->where['name'] = array('like', $name);
        }
        if ($id) {
            $this->set['limit'] = '0,6';
            $this->where['id'] = array('!=', $id);
        } else {
            $this->set['num'] = $num;
        }
        $info = $this->db->select($this->where, $this->set);
        $result = array();
        foreach ($info as $k => $v) {
            $v = $this->handleInfo($v);
            if ($v) {
                $result[] = $v;
            }
        }
        return $result;
    }

    public function getInfo($id, $state = true)
    {
        if (!$id) {
            Dever::error('资源不存在');
        }
        $this->where['id'] = $id;
        $info = $this->db->find($this->where);
        if (!$info) {
            if ($state) {
                Dever::error('资源不存在');
            }
            return false;
        }
        return $this->handleInfo($info);
    }

    # 下单
    public function pay_commit(){}
    public function pay($info)
    {
        if (isset($info['stock']) && $info['num'] > $info['stock']) {
            Dever::error('库存不足');
        }
        $order = array();
        $order['uid'] = Place::$uid;
        $order['name'] = $info['name'];
        $prefix = strtoupper(substr($this->app, 0, 2));
        if ($this->type == 3) {
            $order['cash'] = $info['value'];
            $order['address_id'] = Dever::input('address_id', 'is_numeric', '收货地址');
        } else {
            $order['cash'] = ($info['value']/Place::$info['score_per']);
        }
        $order['order_num'] = Dever::load('util', 'api')->createNumber($prefix, $this->app . '/order');
        $order['notify'] = 'place/callback.resource|' . Dever::input('p') . '|' . $order['order_num'] . '|' . $this->app;

        $data['pay'] = Dever::load('account', 'place')->pay($order);
        #if ($data['pay'] && empty($data['pay']['link'])) {
        if ($data['pay']) {
            $order['status'] = 2;
            $order['info_id'] = $info['id'];
            $order['num'] = $info['num'];
            $data['order_id'] = Dever::db('order', $this->app)->insert($order);
            $data['order_num'] = $order['order_num'];
            if (isset($info['detail'])) {
                Dever::load('log', $this->app)->up(1, $order['uid'], $data['order_id'], '下单成功');
                $detail['order_id'] = $data['order_id'];
                foreach ($info['detail'] as $k => $v) {
                    $detail['info_id'] = $v['id'];
                    if (isset($v['sku_id'])) {
                        $detail['sku_id'] = $v['sku_id'];
                    }
                    if (isset($v['sku_name'])) {
                        $detail['sku_name'] = $v['sku_name'];
                    }
                    $detail['pic'] = $v['pic'];
                    $detail['cash'] = $v['cash'];
                    $detail['num'] = $v['num'] ?? $order['num'];
                    $detail['name'] = $v['name'];
                    $detail['pic'] = $v['pic'];
                    Dever::db('order_detail', $this->app)->insert($detail);
                    if (isset($v['stock'])) {
                        $state = Dever::load('stock', 'goods')->sell($detail['info_id'], $detail['sku_id'], $detail['num']);
                        if (!$state) {
                            Dever::error('库存不足');
                        }
                    }
                    if (isset($v['cart_id']) && $v['cart_id']) {
                        Dever::db('cart', $this->app)->delete(array('id' => $v['cart_id'], 'uid' => Place::$uid));
                    }
                }
            }
        }
        return $data;
    }

    # 获取订单列表
    public function getOrderList()
    {
        $where['uid'] = Place::$uid;
        $set['num'] = 10;
        $set['col'] = 'id,order_num,info_id,name,cash,num,cdate,status';
        $status = Dever::input('status');
        if ($status) {
            if ($status == 10) {
                $where['or'] = array
                (
                    'refund_status' => '1',
                    'status' => '8',
                );
                $where = ' uid = ' . $where['uid'] . ' and (refund_status = 1 or status = 8)';
            } else {
                $where['status'] = array('in', $status);
            }
        }
        $data = Dever::db('order', $this->app)->select($where, $set);
        $result = array();
        if ($data) {
            foreach ($data as $k => $v) {
                $order = $this->getOrderInfo($v);
                if ($order) {
                    $result[] = $order;
                }
            }
        }
        return $result;
    }

    # 获取订单详情
    public function getOrderView()
    {
        $where['uid'] = Place::$uid;
        $where['id'] = Dever::input('id', 'is_numeric', '订单');
        $order = Dever::db('order', $this->app)->find($where);
        if ($order) {
            $order = $this->getOrderInfo($order, true);
        } else {
            Dever::error('订单不存在');
        }
        return $order;
    }

    # 更新地址
    public function upOrderAddress()
    {
        $where['uid'] = Place::$uid;
        $where['id'] = Dever::input('id', 'is_numeric', '订单');
        $order = Dever::db('order', $this->app)->find($where);
        if ($order && $order['status'] <= 2) {
            $province = Dever::input('province', 'is_numeric', '省份');
            $city = Dever::input('city', 'is_numeric', '城市');
            $county = Dever::input('county', 'is_numeric', '区县');
            $address = Dever::input('address', 'is_string', '地址');
            $name = Dever::input('name', 'is_string', '联系人');
            $phone = Dever::input('phone', 'is_string', '联系方式');
            Dever::load('address', $this->app)->up($order['id'], $order['uid'], $order['address_id'], $name, $phone, $province . ',' . $city . ',' . $county, $address);
        } else {
            Dever::error('无法修改订单收货地址');
        }
        return $order;
    }

    # 取消订单
    public function upOrderCancel()
    {
        $where['uid'] = Place::$uid;
        $where['id'] = Dever::input('id', 'is_numeric', '订单');
        $order = Dever::db('order', $this->app)->find($where);
        if ($order && ($order['status'] == 1)) {
            Dever::load('order', $this->app)->cancel($order);
        } else {
            Dever::error('无法取消订单');
        }
        return $order;
    }

    # 确认收货
    public function upOrderFinish()
    {
        $where['uid'] = Place::$uid;
        $where['id'] = Dever::input('id', 'is_numeric', '订单');
        $order = Dever::db('order', $this->app)->find($where);
        if ($order && ($order['status'] == 3 || $order['status'] == 4)) {
            Dever::load('order', $this->app)->finish(1, $order);
        } else {
            Dever::error('无法确认收货');
        }
        return $order;
    }

    private function getOrderInfo($order, $view = false)
    {
        if ($order) {
            $info = Dever::db('info', $this->app)->find($order['info_id'], array('col' => 'id,name,pic,info'));
            $info['pic'] = explode(',', $info['pic']);
            $order['pic'] = $info['pic'][0] ?? '';
            $order['status_name'] = Dever::db('order', $this->app)->value('status', $order['status']);
            $order['cdate_str'] = date('Y-m-d H:i:s', $order['cdate']);
            if (isset($order['pdate']) && $order['pdate']) {
                $order['pdate_str'] = date('Y-m-d H:i:s', $order['pdate']);
            }
            if (isset($order['ddate']) && $order['ddate']) {
                $order['ddate_str'] = date('Y-m-d H:i:s', $order['ddate']);
            }
            if (isset($order['qdate']) && $order['qdate']) {
                $order['qdate_str'] = date('Y-m-d H:i:s', $order['qdate']);
            }
            if (isset($order['fdate']) && $order['fdate']) {
                $order['fdate_str'] = date('Y-m-d H:i:s', $order['fdate']);
            }
            $order = Dever::load('order', $this->app)->getInfo($order, $view);
        }
        return $order;
    }

    # 同步资源，关联资源
    public function relation($place_id, $data, $relation)
    {
        $where['channel_place_id'] = $place_id;
        $where['channel_type'] = $data['type'];
        $where['channel_type_id'] = $data['type_id'];
        $info = Dever::db('resource_relation', 'place')->find($where);
        if ($info) {
            if ($info['status'] == 2) {
                Dever::db('resource_relation', 'place')->update($info['id'], array('status' => 1));
                $update['source'] = 2;
                Dever::db('info', $this->app, false)->update($info['type_id'], $update);
                # 同步sku
                $this->relationSku($info['type_id'], $relation);
            }
        } else {
            $parent_id = $child_id = 0;
            foreach ($relation['cate'] as $k => $v) {
                unset($v['id']);
                unset($v['cdate']);
                if (!$parent_id) {
                    $v['parent_id'] = 0;
                    $parent_id = $this->createCate($v);
                } else {
                    $v['parent_id'] = $parent_id;
                    $child_id = $this->createCate($v);
                }
            }
            $cate[] = $relation['info']['cate_parent_id'] = $parent_id;
            if ($child_id) {
                $cate[] = $relation['info']['cate_child_id'] = $child_id;
            }
            $relation['info']['cate'] = implode(',', $cate);
            $relation['info']['source'] = 2;
            unset($relation['info']['id']);
            $info_id = Dever::db('info', $this->app, false)->insert($relation['info']);
            if ($info_id) {
                # 同步sku
                $this->relationSku($info_id, $relation);

                $where['type'] = $data['type'];
                $where['type_id'] = $info_id;
                $where['channel_price'] = $data['price'];
                $where['status'] = 1;
                Dever::db('resource_relation', 'place')->insert($where);
            }
        }
    }

    # 同步sku
    public function relationSku($info_id, $relation)
    {
        if (isset($relation['sku']) && $relation['sku']) {
            $spec_value = array();
            $spec_db = Dever::db('spec', $this->app, false);
            $spec_value_db = Dever::db('spec_value', $this->app, false);
            $sku_db = Dever::db('sku', $this->app, false);
            $spec_db->delete(array('info_id' => $info_id));
            $spec_value_db->delete(array('info_id' => $info_id));
            $sku_db->delete(array('info_id' => $info_id));
            foreach ($relation['spec'] as $v) {
                unset($v['id']);
                unset($v['cdate']);
                $v['info_id'] = $info_id;
                $spec_id = $spec_db->insert($v);
                foreach ($v['value'] as $v1) {
                    $id = $v1['id'];
                    unset($v1['id']);
                    unset($v1['cdate']);
                    $v1['info_id'] = $info_id;
                    $v1['spec_id'] = $spec_id;
                    $value_id = $spec_value_db->insert($v1);
                    $spec_value[$id] = $value_id;
                }
            }
            
            foreach ($relation['sku'] as $v) {
                unset($v['id']);
                unset($v['cdate']);
                $key = explode(',', $v['key']);
                $v['key'] = array();
                foreach ($key as $v1) {
                    if (isset($spec_value[$v1])) {
                        $v['key'][] = $spec_value[$v1];
                    }
                }
                $v['key'] = implode(',', $v['key']);
                $sku_db->insert($v);
            }
        }
    }

    # 删除关联关系
    public function relationDel($place_id, $data)
    {
        $where['channel_place_id'] = $place_id;
        $where['channel_type'] = $data['type'];
        $where['channel_type_id'] = $data['type_id'];
        $where['status'] = 1;
        $info = Dever::db('resource_relation', 'place')->find($where);
        if ($info) {
            Dever::db('resource_relation', 'place')->update($info['id'], array('status' => 2));
            Dever::db('info', $this->app, false)->update($info['type_id'], array('source' => 1));
        }
    }

    # 创建分类
    private function createCate($v)
    {
        $db = Dever::db('cate', $this->app, false);
        $info = $db->find(array('key' => $v['key']));
        if (!$info) {
            $id = $db->insert($v);
        } else {
            $id = $info['id'];
        }
        return $id;
    }

    private function handleInfo($info)
    {
        $info = Dever::load('info', $this->app)->getInfo($info);
        if (!$info) {
            return $info;
        }
        $info['pic'] = explode(',', $info['pic']);
        $info['cdate_str'] = date('Y-m-d H:i:s', $info['cdate']);
        if (Place::$uid && Place::$user['client_id'] > 0) {
            $info['client'] = Dever::load('client', 'place')->get($info, $this->app, $this->type, '进货');
        }
        $info['price'] = Dever::load('price', 'place')->get($info, $this->app, $this->type, '下载');

        if (isset($info['content'])) {
            if (isset($info['password'])) {
                unset($info['password']);
            }
            # 查看详情信息
            if (Place::$uid) {
                $act = new Act('collect', $this->type, $info['id']);
                $info['collect'] = 2;
                $collect = $act->getInfo();
                if ($collect) {
                    $info['collect'] = 1;
                }
            }
            $info['content'] = htmlspecialchars_decode($info['content']);
        } else {
            $info['pic'] = $info['pic'][0] ?? '';
        }
        return $info;
    }
}