<?php

namespace Agent\Lib;

use Dever;

class Manage
{
    # 获取
    # 设置上级
    public function setParent_commit($id, $name, $data)
    {
        Dever::config('base')->hook = true;
        $mid = Dever::param('mid', $data);
        $parent_mobile = trim(Dever::param('parent_mobile', $data));
        if ($mid && $parent_mobile) {
            $member = Dever::db('agent/member')->find($mid);
            $parent = Dever::db('agent/member')->find(array('mobile' => $parent_mobile));
            if ($parent && $parent['status'] == 2) {
                if ($member['parent_mid'] == $parent['id']) {
                    Dever::alert('上级代理商设置失败');
                    return;
                }
                if ($member['parent_mid'] == $mid) {
                    Dever::alert('上级代理商不能设置为自己');
                    return;
                }
                # 删除之前关系
                Dever::load('invite/api')->dropRelation($mid, $parent['id']);
                # 获取所有下级
                $child = Dever::load('invite/api')->getChild($mid);
                if ($child) {
                    foreach ($child as $k => $v) {
                        Dever::load('invite/api')->dropRelation($v['to_uid'], $parent['id']);
                    }
                }

                # 重新设置关系
                Dever::load('invite/api')->setRelation($mid, $parent['id']);
                Dever::db('agent/member')->update(array('id' => $mid, 'parent_mid' => $parent['id']));
            } else {
                Dever::alert('上级代理商还未注册或者已封禁');
            }
        }
    }

    public function orderUpdate($id, $name, $data)
    {
        Dever::config('base')->hook = true;
        $audit = Dever::param('audit', $data);
        $status = Dever::param('status', $data);
        $desc = Dever::param('desc', $data);
        $order_id = Dever::param('order_id', $data);
        if ($order_id && $status) {
            if ($status < 3) {
                if ($audit == 1) {
                    $update = array('where_id' => $order_id, 'status' => $status+1);
                    if ($status == 2) {
                        $order = Dever::db('agent/order')->find($order_id);
                        $price = Dever::param('price', $data);
                        $prize_type = Dever::param('prize_type', $data);
                        if ($prize_type == 2) {
                            # 扣减已有名额，判断一下
                            $prize = Dever::db('setting/prize')->find(array('type' => 1, 'price' => $order['price']));
                            if ($prize) {
                                $member_goods = Dever::db('agent/member_goods')->getOne(array('mid' => $order['mid'], 'type' => 3, 'type_id' => $prize['id']));
                                if ($member_goods && $member_goods['num'] > 0) {
                                    # 有名额
                                    $price = 0;
                                    # 开始扣减
                                    $member = Dever::db('agent/member')->find($order['mid']);
                                    Dever::load('agent/lib/dhorder')->action($member, $prize['name'], $prize['num'], $prize['price'], array(), -1, 2, 3, $desc);
                                }
                            }
                        }
                        if ($price <= 0) {
                            $update['get_type'] = 2;
                        } else {
                            $update['get_type'] = 1;
                        }
                        $update['price'] = $price;
                        $update['agent_cash'] = $price;
                        $update['soft_cash'] = 0;

                        $cstatus = Dever::param('cstatus', $data);
                        if ($cstatus && $cstatus == 2 && $price > 0) {
                            # 拆分代理费
                            $role = Dever::db('setting/role')->one($order['role']);
                            if ($role && $role['soft']) {
                                if (strstr($role['soft'], '%')) {
                                    $role['soft'] = str_replace('%', '', $role['soft']);
                                    $role['soft'] = $price * ($role['soft']/100);
                                }

                                $update['agent_cash'] = $price - $role['soft'];
                                $update['soft_cash'] = $role['soft'];
                            }
                        }
                        
                        $update['pay_status'] = 2;
                        # 财务终审之后，先生成代理商
                        if ($order['mid'] <= 0) {
                            # 生成
                            $where['mobile'] = $order['mobile'];
                            $member = Dever::db('agent/member')->find($where);
                            if ($member) {
                                $update['mid'] = $member['id'];
                            } else {
                                $data = $where;
                                $data['name'] = $order['name'];
                                $data['idcard'] = $order['idcard'];
                                $data['idcard_front'] = $order['idcard_front'];
                                $data['idcard_back'] = $order['idcard_back'];
                                $data['company_name'] = $order['company_name'];
                                $data['company_pic'] = $order['company_pic'];
                                $data['company_number'] = $order['company_number'];
                                $data['role'] = 1;
                                $data['parent_mid'] = $order['parent_mid'];
                                $data['source_id'] = $order['source_id'];
                                $update['mid'] = Dever::db('agent/member')->insert($data);

                                Dever::load('invite/api')->setRelation($update['mid'], $data['parent_mid']);
                            }
                        }
                    }

                    Dever::db('agent/order')->update($update);
                } else {
                    Dever::db('agent/order')->update(array('where_id' => $order_id, 'status' => 5));
                }
            } elseif ($status == 3) {
                $info = Dever::db('agent/order_process')->find($id);
                if ($info && $info['status'] == 3) {
                    $info['type'] = explode(',', $info['type']);
                }
                if (in_array(2, $info['type'])) {
                    $goods_status = 3;
                } else {
                    $goods_status = 2;
                }
                Dever::db('agent/order')->update(array('where_id' => $order_id, 'fdate' => time(), 'status' => 4, 'goods_status' => $goods_status));

                $order = Dever::db('agent/order')->find($order_id);
                if ($order && $order['mid']) {
                    $member = Dever::db('agent/member')->find($order['mid']);
                    $update['where_id'] = $order['mid'];
                    if ($member && $member['status'] == 1) {
                        $update['status'] = 2;
                        $update['rdate'] = time();
                    }
                    $update['area'] = $order['area'];
                    $update['role'] = $order['role'];

                    Dever::db('agent/member')->update($update);

                    # 对改区域进行占用
                    Dever::load('area/api')->upStatus($order['area'], 2);
                    $area_data = array('mid' => $order['mid'], 'order_id' => $order['id'], 'role' => $order['role'], 'area' => $order['area']);
                    $area = Dever::db('agent/member_area')->find($area_data);

                    if (!$area) {
                        $area_data['type'] = $order['get_type'];
                        $area_data['price'] = $order['price'];
                        Dever::db('agent/member_area')->insert($area_data);
                    } else {
                        Dever::load('area/api')->upStatus($area['area'], 1);
                    }
                }
            }
        }
    }

    # 发放权益
    public function set_commit_api()
    {
        Dever::config('base')->hook = true;
        $type = Dever::input('type', 2);

        $order_id = Dever::input('order_id');
        # 检测是否发放过了
        $order = Dever::db('agent/order')->find($order_id);
        if ($order['status'] != 3) {
            Dever::alert('无发放权限');
        }

        if ($order['mid'] <= 0) {
            $update = array('where_id' => $order_id);
            $where['mobile'] = $order['mobile'];
            $member = Dever::db('agent/member')->find($where);
            if ($member) {
                $update['mid'] = $member['id'];
            } else {
                $data = $where;
                $data['name'] = $order['name'];
                $data['idcard'] = $order['idcard'];
                $data['idcard_front'] = $order['idcard_front'];
                $data['idcard_back'] = $order['idcard_back'];
                $data['company_name'] = $order['company_name'];
                $data['company_pic'] = $order['company_pic'];
                $data['company_number'] = $order['company_number'];
                $data['role'] = 1;
                $data['parent_mid'] = $order['parent_mid'];
                $data['source_id'] = $order['source_id'];
                $update['mid'] = Dever::db('agent/member')->insert($data);
                Dever::load('invite/api')->setRelation($update['mid'], $data['parent_mid']);
            }
            Dever::db('agent/order')->update($update);
            $order['mid'] = $update['mid'];
        }

        $order_process = Dever::db('agent/order_process')->find(array('order_id' => $order_id, 'status' => 3));

        $yes = -1;
        if (!$order_process) {
            # 可以发放
            $yes = 1;
        } elseif ($order_process) {
            $order_process['type'] = explode(',', $order_process['type']);
            if (!in_array($type, $order_process['type'])) {
                # 可以发放
                $yes = 2;
            }
        }
        if ($yes > 0) {
            if ($yes == 1) {
                $data['order_id'] = $order_id;
                $data['status'] = 3;
                $data['type'] = '1,' . $type;
                $state = Dever::db('agent/order_process')->insert($data);
            } else {
                $data['where_id'] = $order_process['id'];
                $order_process['type'][] = $type;
                $data['type'] = implode(',', $order_process['type']);
                $state = Dever::db('agent/order_process')->update($data);
            }
            if ($state) {

                if ($type == 2) {
                    $this->setGoods($order);
                } elseif ($type == 3) {
                    $this->setCash($order);
                } elseif ($type == 5) {
                    $this->setAgreement($order);
                }
            }
            return 'reload';
        } else {
            Dever::alert('无发放权限');
        }
    }

    # 设置多个权益
    private function setGoods($order)
    {
        $goods = Dever::db('agent/order_goods')->getData(array('order_id' => $order['id']));
        if (!$goods) {
            $goods = Dever::db('setting/role_goods')->getData(array('role_id' => $order['role'], 'give' => $order['order_type']));
        }

        if ($goods) {
            $where = array();
            foreach ($goods as $k => $v) {
                $this->addGoods($order, $v);
            }
        }
    }

    # 新增权益
    private function addGoods($order, $v)
    {
        $where['mid'] = $order['mid'];
        $where['type'] = $v['type'];
        $where['type_id'] = $v['type_id'];
        $where['sku_id'] = $v['sku_id'];
        $info = Dever::db('agent/member_goods')->find($where);
        if ($info) {
            $up['where_id'] = $info['id'];
            $up['total_num'] = $info['total_num'] + $v['num'];
            $state = Dever::db('agent/member_goods')->update($up);

            if ($state) {
                Dever::load('agent/lib/member_set')->log($order['mid'], $order['order_num'], $v['type'], $v['type_id'], $v['sku_id'], $v['num'], $info['total_num'], $up['total_num']);
            }
            
        } else {
            $up = $where;
            $up['total_num'] = $v['num'];
            $state = Dever::db('agent/member_goods')->insert($up);
            if ($state) {
                Dever::load('agent/lib/member_set')->log($order['mid'], $order['order_num'], $v['type'], $v['type_id'], $v['sku_id'], $v['num'], 0, $up['total_num']);
            }
        }
    }

    private function setCash($order)
    {
        $param = Dever::input('param');
        if ($param) {
            $param = explode(',', $param);
            foreach ($param as $k => $v) {
                $t = explode('-', $v);
                $where['type'] = $t[0];
                $where['order_id'] = $order['id'];
                $where['mid'] = $order['mid'];
                $where['parent_mid'] = $t[2];
                $info = Dever::db('agent/order_cash')->find($where);
                if (!$info) {
                    $insert = $where;
                    $insert['cash'] = $t[3];
                    $insert['per'] = $t[5];
                    if (isset($t[6])) {
                        $insert['prize_id'] = $t[6];
                    }
                    Dever::db('agent/order_cash')->insert($insert);
                } else {
                    $update['where_id'] = $info['id'];
                    $update['cash'] = $t[3];
                    $update['per'] = $t[5];
                    if (isset($t[6])) {
                        $update['prize_id'] = $t[6];
                    }
                    Dever::db('agent/order_cash')->update($update);
                }

                if (isset($t[6]) && isset($t[7])) {
                    $prize_info = Dever::db('setting/prize')->find($t[6]);
                    if ($prize_info) {
                        $prize_insert['order_id'] = $order['order_id'];
                        $prize_insert['mid'] = $t[2];
                        $prize_insert['child_num'] = $t[7];
                        $prize_insert['prize_id'] = $prize_info['id'];
                        Dever::db('agent/member_prize')->insert($prize_insert);

                        $prize['type'] = 3;
                        $prize['type_id'] = $prize_info['id'];
                        $prize['sku_id'] = -1;
                        $prize['num'] = $prize_info['num'];
                        $this->addGoods($order, $prize);
                    }
                }

                $member = Dever::db('agent/member')->find($where['mid']);
                $desc = $member['name'] . '成为代理商，佣金'.$t[5].'%';
                Dever::load('agent/lib/member')->up($member, $order['id'], $order['role'], $where['type'], $where['parent_mid'], $t[3], $order['agent_cash'], $t[4], $desc);
            }
        }
    }

    private function setAgreement($order)
    {
        Dever::load('agent/lib/agreement')->up($order);
    }

    public function sellOrderUpdate($id, $name, $data)
    {
        Dever::config('base')->hook = true;
        $update = array();
        $audit = Dever::param('audit', $data);
        $info = Dever::db('agent/dh_order')->one($id);
        if ($audit > 1 && $info && $info['status'] == 2) {
            if ($audit == 2) {
                # 成功
                Dever::setInput('order_id', $id);
                Dever::load('agent/lib/dhorder.audit_commit');
            } else {
                Dever::db('agent/dh_order')->update(array('where_id' => $id, 'status' => 7));
            }
        }
    }

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

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

    # 获取权益名称
    public function getGoods($type, $type_id, $sku_id)
    {
        if ($type == 1) {
            if ($sku_id == -2) {
                return '商品';
            }
            $goods_info = Dever::load('goods/lib/info')->getInfoBySku($type_id, $sku_id);
            if (isset($goods_info['sku'])) {
                $sku = '-' . $goods_info['sku']['string'];
            } else {
                $sku = '';
            }

            return array('name' => $goods_info['name'] . $sku, 'price' => $goods_info['price']);
        } elseif ($type == 2) {
            $card = Dever::db('card/info')->find($type_id);
            return array('name' => $card['name'], 'price' => $card['price']);
        } elseif ($type == 3) {
            $prize = Dever::db('setting/role_goods')->config['set']['prize'];

            return array('name' => $prize[$type_id], 'price' => 0);
        }
    }
}