<?php

namespace Agent\Lib;

use Dever;

class Manage
{
    public function agentOut($data)
    {
        $file = Dever::input('excel_name');
        $header = array('姓名', '手机号', '身份证号', '代理角色', '代理商区域', '代理费', '余额', '直推业绩', '团队业绩', '注册时间', '注册完成时间', '推荐人', '推荐人电话', '推荐人代理角色');
        
        $body = array();

        if ($data) {
            foreach ($data as $k => $v) {
                $prize_type = '';
                if (is_array($v)) {
                    if ($v['role']) {
                        $role = Dever::db('setting/role')->find($v['role']);
                        if($v['role'] == 8){
                            if($v['prize_type'] == 1){
                                $prize_type = '-名额外';
                            }elseif($v['prize_type'] == 2){
                                $prize_type = '-名额内';
                            }
                        }
                    } else {
                        $role = array('name' => '普通代理',);
                    }

                    $order = Dever::db('agent/order')->find(array('mid' => $v['id']));
                    $agent_cash = 0;
                    if ($order) {
                        $agent_cash = $order['agent_cash'];
                    }
                    
                    $area = Dever::load("area/api.string", $v['area']);
                    if ($v['rdate']) {
                        $rdate = date('Y-m-d H:i',$v['rdate']);
                    } else {
                        $rdate = '-';
                    }
                    $parent_name = '';
                    $parent_mobile = '';
                    $parent_rolename = '';

                    if ($v['parent_mid'] && $v['parent_mid'] > 0) {
                        $parent = Dever::db('agent/member')->find(array('id'=>$v['parent_mid']));
                        if ($parent) {
                            if($parent['role']){
                                $parent_role = Dever::db('setting/role')->find(array('id'=>$parent['role']));
                                if($parent_role){
                                    $parent_rolename = $parent_role['name'];
                                }
                            }
                            if($parent['name']){
                                $parent_name = $parent['name'];
                            }
                            if($parent['mobile']){
                                $parent_mobile = $parent['mobile'];
                            }
                        }
                    }
                    
                    $d = array
                    (
                        $v['name'],
                        $v['mobile'],
                        $v['idcard'],
                        $role['name'].$prize_type,
                        $area,
                        $agent_cash,
                        $v['cash'],
                        $v['sell'],
                        $v['group_sell'],
                        date('Y-m-d H:i',$v['cdate']),
                        $rdate,
                        $parent_name,
                        $parent_mobile,
                        $parent_rolename,
                    );
                    $body[] = $d;
                }
            }
        }

        return Dever::excelExport($body, $header, $file);
    }

    public function agentCashOut($data)
    {
        $db = Dever::db('agent/test:old');
        $file = Dever::input('excel_name');
        $header = array('姓名', '手机号', '代理角色', '交款金额', '直推佣金', '团队佣金', '注册时间');
        
        $body = array();

        if ($data) {
            foreach ($data as $k => $v) {
                if ($v['rdate'] > 0) {
                    if ($v['role']) {
                        $role = Dever::db('setting/role')->find($v['role']);
                    } else {
                        $role = array('name' => '普通代理',);
                    }

                    $order = Dever::db('agent/order')->find(array('mid' => $v['id']));
                    $price = 0;
                    if ($order) {
                        $price = $order['price'];
                    }


                    $cash_zt = 0;
                    $cash_group = 0;

                    $cash = Dever::db('bill/cash')->getCash(array('type' => 1, 'mid' => $v['id']));

                    if ($cash) {
                        $cash_zt = $cash['total'];
                    }

                    $cash = Dever::db('bill/cash')->getCash(array('type' => 2, 'mid' => $v['id']));

                    if ($cash) {
                        $cash_group = $cash['total'];
                    }
                    if (!$cash_group) {
                        $cash_group = 0;
                    }

                    if ($v['id'] < 50000) {
                        $info = $db->fetch('select * from ims_ewei_shop_member where id = ' . $v['id']);
                        if ($info) {
                            $member = $db->fetch('select * from ims_mc_members where uid = ' . $info['uid']);
                            $cash_zt += ($member && $member['credit2']) ? $member['credit2'] : $info['credit2'];
                        }
                    }

                    $cdate = date('Y-m-d H:i', $v['rdate']);
                    
                    $d = array
                    (
                        $v['name'],
                        $v['mobile'],
                        $role['name'],
                        $price,
                        $cash_zt,
                        $cash_group,
                        $cdate,
                    );
                    $body[] = $d;
                }
            }
        }

        return Dever::excelExport($body, $header, $file);
    }

    public function relation_api()
    {
        $admin = Dever::load('manage/auth.data');
        if ($admin['role'] != 1) {
            Dever::alert('无法访问');
        }
        $data = array();
        $data['mobile'] = Dever::input('mobile');
        $member = Dever::db('agent/member')->find(array('mobile' => $data['mobile']));
        $data['mid'] = $member['id'];
        // Dever::input('mid');
        $data['link'] = Dever::decode(Dever::input('refer'));

        return Dever::render('index', $data);
    }
    # 后台设置区域
    public function updateArea($id, $name, $data)
    {
        Dever::config('base')->hook = true;
        $id = $id['where_id'];
        $is_area = Dever::param('is_area', $data);

        $area = Dever::param('area', $data);#修改后
        $role = Dever::param('role', $data);
        $level_id = Dever::param('level_id', $data);
        
        $member = Dever::db('agent/member')->find($id);
        if (!$member) {
            return;
        }

        if (!$is_area) {
            $is_area = 1;
        }

        if ($is_area == 1) {
            if ($area && is_array($area) && $role) {
                $role = Dever::db('setting/role')->find($role);
                $area_string = array();
                if ($role && $role['type'] == 2) {
                    $area_string = Dever::load('agent/lib/order')->checkArea($area, $role, $member['id']);
                } else {
                    $area_string = implode(',', $area);
                }

                $area_string = str_replace(',-1', '', $area_string);
                
                $data['set_area'] = $area_string;
                if ($area_string == $member['area']) {
                    $area_string = '';
                }
                $this->upLog($member, $role, $area_string, -1, 3);
            }
        } else {
            # 清理区域
            $role = Dever::db('setting/role')->find($member['role']);
            if ($role && $role['type'] == 2) {
                $area = $member['area'];
                Dever::load('area/api')->upStatus($area, 1);
                $area_data['mid'] = $member['id'];
                $area_data['area'] = $area;
                $area_info = Dever::db('agent/member_area')->find($area_data);
                if ($area_info) {
                    Dever::db('agent/member_area')->update(array('where_id' => $area_info['id'], 'state' => 2));
                    Dever::db('agent/member')->update(array('where_id' => $member['id'], 'area' => ''));
                    //Dever::load('agent/lib/order')->editArea($member, '');

                    $this->area_log($member['id'], -1, $member['area'], '');
                }
                $data['set_area'] = 'null';
            }
        }
        
        if ($level_id && $level_id != $member['level_id']) {
            $group_num = Dever::load('invite/api')->getChildNum($member['id'], 1);
            Dever::load('agent/lib/level_log')->up($member['id'], -1, $member['level_id'], $level_id, 0, 0, $group_num);
        }

        $name = Dever::param('name', $data);
        if ($name) {
            $order = Dever::db('agent/order')->select(array('mid' => $member['id']));
            if ($order) {
                foreach ($order as $k => $v) {
                    if ($v['status'] <= 2) {
                        Dever::db('agent/order')->update(array('where_id' => $v['id'], 'name' => $name));
                    }
                }
            }
        }

        $mobile = Dever::param('mobile', $data);
        if ($mobile) {
            # 验证手机号是否可以修改
            $mobile_member = Dever::db('agent/member')->find(array('mobile' => $mobile));
            if ($mobile_member && $mobile_member['id'] != $member['id']) {
                Dever::alert('无法修改手机号，当前手机号已被代理商'.$mobile_member['name'].'使用');
            }

            # 是否同步修改期权表
            $option_member = Dever::db('option/member')->find(array('mobile' => $member['mobile'], 'main' => 2));
            if ($option_member) {
                $mobile_member = Dever::db('option/member')->find(array('mobile' => $mobile));
                if ($mobile_member && $mobile_member['id'] != $member['id']) {
                    Dever::alert('无法修改手机号，当前手机号已被代理商期权子账户'.$mobile_member['name'].'使用');
                }
                Dever::db('option/member')->update(array('where_id' => $option_member['id'], 'mobile' => $mobile));
            }

            # 同步修改其他表的手机号
            Dever::db('agent/member_agreement')->updates(array('option_mid' => $member['id'], 'set_mobile' => $mobile));
            Dever::db('agent/dh_order')->updates(array('option_mid' => $member['id'], 'set_mobile' => $mobile));
            Dever::db('agent/order')->updates(array('option_mid' => $member['id'], 'set_mobile' => $mobile));
            Dever::db('agent/user_bind')->updates(array('option_mid' => $member['id'], 'set_mobile' => $mobile));
            Dever::db('agent/soft_cash')->updates(array('option_mid' => $member['id'], 'set_mobile' => $mobile));


        }

        return $data;
    }

    # 更改日志
    private function upLog($member, $role, $area, $order_id = -1, $type = 3, $price = 0)
    {
        if (is_numeric($role)) {
            $role = Dever::db('setting/role')->find($role);
        }
        if (!$role) {
            return;
        }
        $this->upRole($member, $role, $area, $order_id);
        if ($area) {
            $this->upArea($member, $role, $area, $order_id, $type, $price);
        }
    }

    private function upRole($member, $role, $area, $order_id = -1)
    {
        if ($role['id'] == $member['role']) {
            return;
        }
        $data['mid'] = $member['id'];
        $data['order_id'] = $order_id;
        $data['old_role'] = $member['role'];
        $data['new_role'] = $role['id'];
        
        if ($area) {
            $data['area'] = $area;
        } else {
            $data['area'] = $member['area'];
        }
        
        if ($order_id && $order_id > 0) {
            $data['type'] = 1;
            $order = Dever::db('agent/order')->find($order_id);
            $data['price'] = $order['price'];
        } else {
            $data['type'] = 2;
            $admin = Dever::load('manage/auth.info');
            $data['audit_admin'] = $admin['id'];
        }
        
        Dever::db('agent/member_account_log')->insert($data);
    }

    public function upArea($member, $role, $area, $order_id = -1, $type = 3, $price = 0)
    {
        if (!$role) {
            return;
        }
        if ($area == $member['area']) {
            //return;
        }
        $area_data = array('mid' => $member['id']);
        $area_info = Dever::db('agent/member_area')->getOne($area_data);
        if ($area_info) {
            Dever::db('agent/member_area')->update(array('where_id' => $area_info['id'], 'state' => 2));
        }
        if ($role && $role['type'] == 2) {
            Dever::load('area/api')->upStatus($area, 2);
            $area_data['order_id'] = $order_id;
            $area_data['role'] = $role['id'];
            $area_data['area'] = $area;
            $area_data['type'] = $type;
            $area_data['price'] = $price;
            $area_data['status'] = 1;
            Dever::db('agent/member_area')->insert($area_data);

            //Dever::load('agent/lib/order')->editArea($v, $area);
        }

        $this->area_log($member['id'], $order_id, $member['area'], $area);
    }
     
    # 获取
    # 设置上级
    public function setParent_commit($id, $name, $data)
    {
        //Dever::alert('暂未开放');
        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')->resetRelation($mid, $parent['id']);

                /*
                # 删除之前关系
                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('where_id' => $mid, 'parent_mid' => $parent['id']));
            } else {
                Dever::alert('上级代理商还未注册或者已封禁');
            }
        }
    }

    public function orderUpdateParent($id, $name, $data)
    {
        Dever::config('base')->hook = true;
        $id = $id['where_id'];

        $order = Dever::db('agent/order')->find($id);
        if (!$order) {
            return;
        }

        $area = Dever::param('area', $data);#修改后
        $role = Dever::param('role', $data);

        $invite_type = Dever::param('invite_type', $data);
        $parent_code = Dever::param('parent_code', $data);
        if ($invite_type == 1 && $parent_code) {
            $parent_mid = Dever::load('invite/api')->getUid($parent_code);
            if ($parent_mid) {
                $parent_member = Dever::db('agent/member')->find($parent_mid);
                if (!$parent_member) {
                    Dever::alert('错误的邀请码');
                }
                if ($order['mid'] == $parent_member['id']) {
                    Dever::alert('邀请人不能是自己');
                }
                $data['set_parent_mid'] = $parent_mid;

                //Dever::db('agent/member')->update(array('where_id' => $order['mid'], 'parent_mid' => $parent_mid));
            } else {
                Dever::alert('错误的邀请码');
            }
        }

        if ($area && is_array($area) && $role) {
            $role = Dever::db('setting/role')->find($role);
            $area_string = array();
            if ($role && $role['type'] == 2) {
                $area_string = Dever::load('agent/lib/order')->checkArea($area, $role, $order['mid']);
            } else {
                $area_string = implode(',', $area);
                $area_string = str_replace(',-1', '', $area_string);
            }
            if ($role['type'] == 1) {
                $data['set_f_price'] = $data['set_price'] = $role['price'];
            } elseif ($role['type'] == 2) {
                $data['set_f_price'] = $data['set_price'] = Dever::load('area/api')->getPrice($role['area'], $area_string);
            } else {
                $data['set_f_price'] = $data['set_price'] = 0;
            }
            
            $data['set_area'] = $area_string;
        }

        return $data;
    }

    public function orderStartUpdate($id, $name, $data)
    {
        $order_id = Dever::param('order_id', $data);
        if ($order_id) {
            $order = Dever::db('agent/order')->find($order_id);
            if ($order && $order['source_id'] < 0) {
                if ($order['parent_mid'] > 0) {
                    $member = Dever::db('agent/member')->find($order['parent_mid']);
                    if ($member['status'] == 2) {
                        return $data;
                    }
                }
                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);
        $order = Dever::db('agent/order')->find($order_id);
        if ($order_id && $order && $status) {
            $admin = Dever::load('manage/auth.info');
            if ($admin) {
                Dever::db('agent/order_process')->update(array('where_id' => $id, 'admin' => $admin['id']));
            }
            
            if ($status < 3) {
                if ($audit == 1) {
                    $update = array('where_id' => $order_id, 'status' => $status+1);
                    if ($status == 1) {
                        $soft_price = Dever::param('soft_price', $data);
                        $price = Dever::param('price', $data);
                        $prize_type = Dever::param('prize_type', $data);
                        $option_price = Dever::param('option_price', $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, $prize['id'], $desc);
                                }
                            }
                        }
                        if ($price <= 0) {
                            $update['get_type'] = 2;
                        } else {
                            $update['get_type'] = 1;
                        }
                        $update['price'] = $price;
                        $update['agent_cash'] = $price;
                        $update['soft_cash'] = 0;
                        $update['option_price']=$option_price;

                        $cstatus = Dever::param('cstatus', $data);
                        if ($cstatus && $cstatus == 2 && $price > 0) {
                            # 拆分代理费
                            if ($soft_price > 0) {
                                $update['agent_cash'] = $price - $soft_price;
                                $update['soft_cash'] = $soft_price;
                            } else {
                                $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'];
                                }
                            }
                        }

                        # 增加业绩
                        //Dever::load('bill/lib/sell')->up($order['mid'], 2, $order['price'], $order['role'], $order['id'], $order['name'] . '成为代理商');
                    } elseif ($status == 2) {
                        if ($order['mid'] && $order['mid'] > 0 && $order['parent_mid'] && $order['parent_mid'] > 0) {
                            Dever::load('invite/api')->setRelation($order['mid'], $order['parent_mid']);
                            Dever::db('agent/member')->update(array('where_id' => $order['mid'], 'parent_mid' => $order['parent_mid']));
                        }
                        $update['pay_status'] = 2;
                        Dever::load('agent/lib/member')->create($order);
                    }

                    Dever::db('agent/order')->update($update);
                } else {
                    
                    Dever::db('agent/order')->update(array('where_id' => $order_id, 'status' => 5, 'history_status' => $order['status'], 'audit_desc' => $desc));

                    if (Dever::project('sms')) {
                        Dever::load('sms/api')->send('daili_reg_no', $order['mobile'], array('name' => $order['name'], 'content' => $desc));
                    }
                }
            } elseif ($status == 3) {
                $info = Dever::db('agent/order_process')->find(array('id' => $id, 'clear' => true));
                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));

                # 通知短信
                if (Dever::project('sms')) {
                     $order = Dever::db('agent/order')->find($order_id);
                     Dever::load('sms/api')->send('daili_reg_yes', $order['mobile'], array('name' => $order['name']));
                }

                $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);
                    if ($order['price'] > 0) {
                        $type = 1;
                    } else {
                        $type = 2;
                    }
                    $this->upLog($member, $order['role'], $order['area'], $order['id'], $type, $order['price']);
                }
            }
        }
    }
    #区域日志
    public function area_log($mid,$order_id,$old_area, $area) {
        $data['mid']=$mid;
        $data['order_id']=$order_id;
        $data['old_area']=$old_area;
        $data['area']=$area;
        if ($order_id && $order_id > 0) {
            $data['type'] = 1;
        } else {
            $admin = Dever::load('manage/auth.info');
            $data['audit_admin'] = $admin['id'];
            $data['type'] = 2;
        }
        
        $id = Dever::db('agent/member_area_log')->insert($data);
        return $id;
    }

    # 发放权益
    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('无发放权限');
        }

        $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)
    {
        $t = 1;
        $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']));
            $t = intval($order['agent_cash']/10000);
            if ($t <= 0) {
                $t = 1;
            }
        }

        if ($goods) {
            $where = array();
            $goods_cash = 0;
            foreach ($goods as $k => $v) {
                $price = $this->addGoods($order, $v, $t);
                if ($price && $v['type'] < 3) {
                    # 计算商品价值
                    $goods_cash += $price;
                }
            }

            $update = array();
            if ($goods_cash) {
                $update['goods_cash'] = $goods_cash;
                
            }
            $update['goods_status'] = 3;
            $update['where_id'] = $order['id'];
            Dever::db('agent/order')->update($update);
        }
    }

    # 新增权益
    private function addGoods($order, $v, $t)
    {
        $cash = $price = 0;
        
        if ($v['type'] == 1) {
            $v['num'] = $v['num'] * $t;
            $goods_info = Dever::load('goods/lib/info')->getInfoBySku($v['type_id'], $v['sku_id']);
            $price = $goods_info['price'];
            $cash = $goods_info['price'] * $v['num'];
            if (isset($goods_info['sku'])) {
                $sku = '-' . $goods_info['sku']['string'];
            } else {
                $sku = '';
            }
            $name = $goods_info['name'] . $sku;
        } elseif ($v['type'] == 2) {
            $v['sku_id'] = -1;
            # 生成一个电子券
            $card = Dever::db('card/info')->find($v['type_id']);
            if (!$card) {
                return false;
            }
            $name = $card['name'];
            if ($card['create_type'] == 2) {
                $cash = $card['value']*$v['num'] * $t;
                $price = $cash;
                $v['num'] = 1;
                $v['sku_id'] = Dever::load('card/lib/code')->create($card, 2, $order['mid'], $order['id'], $cash);
                if (!$v['sku_id']) {
                    return false;
                }
            } elseif ($card['create_type'] == 3) {
                $cash = round($order['agent_cash']*($v['num']/100), 2);
                $price = $cash;
                $v['num'] = 1;
                $v['sku_id'] = Dever::load('card/lib/code')->create($card, 2, $order['mid'], $order['id'], $cash);
                if (!$v['sku_id']) {
                    return false;
                }
            } else {
                $cash = $card['value'];
                $price = $cash;
                $total = $t*$v['num'];
                $t = 1;
                for($i=0; $i<$total;$i++) {
                    $v['sku_id'] = Dever::load('card/lib/code')->create($card, 2, $order['mid'], $order['id'], $cash);
                    if ($v['sku_id']) {
                        $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;
                            $up['total_num'] = $t;
                            $up['cash'] = $cash;
                            $up['price'] = $price;
                            $up['name'] = $name;
                            $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'], $t, 0, $t, $name);
                            }
                        }
                    }
                }
                return $cash * $total;
            }
            
        } elseif ($v['type'] == 3) {
            $prize = Dever::db('setting/prize')->find($v['type_id']);
            $v['num'] = $v['num'] * $t;
            $role = Dever::db('setting/role')->find($order['role']);
            if ($role && $role['max_me_num'] && $role['max_me_num'] < $v['num']) {
                $v['num'] = $role['max_me_num'];
            }
            $price = $prize['price'];
            $cash = $prize['price']*$v['num'];
            $name = $prize['name'];
        }

        $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'];
            $up['cash'] = $cash;
            $up['price'] = $price;
            $up['name'] = $name;
            $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'], $name);
            }
            
        } else {
            $up = $where;
            $up['total_num'] = $v['num'];
            $up['cash'] = $cash;
            $up['price'] = $price;
            $up['name'] = $name;
            $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'], $name);
            }
        }
        return $cash;
    }

    private function setCash($order)
    {
        $param = Dever::input('param');
        if ($param) {
            $param = explode(',', $param);
            foreach ($param as $k => $v) {
                $t = Dever::array_decode($v);

                # 判断是否名额内
                if (isset($t['prize_type']) && $t['prize_type'] == 2) {
                    Dever::db('agent/member')->update(array('where_id' => $order['mid'], 'prize_type' => $t['prize_type']));
                }
                $parent_order = $order;
                $parent_order['mid'] = $t['parent_mid'];
                $where['type'] = $t['type'];
                $where['order_id'] = $order['id'];
                $where['mid'] = $order['mid'];
                $where['parent_mid'] = $t['parent_mid'];
                $info = Dever::db('agent/order_cash')->find($where);
                if (!$info) {
                    $insert = $where;
                    $insert['cash'] = $t['cash'];
                    $insert['per'] = $t['per'];
                    if (isset($t['prize_id'])) {
                        $insert['prize_id'] = $t['prize_id'];
                    }
                    if (isset($t['goods'])) {
                        $insert['goods'] = Dever::array_encode($t['goods']);
                    }
                    Dever::db('agent/order_cash')->insert($insert);
                } else {
                    $update['where_id'] = $info['id'];
                    $update['cash'] = $t['cash'];
                    $update['per'] = $t['per'];
                    if (isset($t['prize_id'])) {
                        $update['prize_id'] = $t['prize_id'];
                    }
                    if (isset($t['goods'])) {
                        $update['goods'] = Dever::array_encode($t['goods']);
                    }
                    Dever::db('agent/order_cash')->update($update);
                }

                if (isset($t['prize_id']) && isset($t['child_num'])) {
                    $prize_info = Dever::db('setting/prize')->find($t['prize_id']);
                    if ($prize_info) {
                        $prize_insert['order_id'] = $order['order_id'];
                        $prize_insert['mid'] = $t['parent_mid'];
                        $prize_insert['child_num'] = $t['child_num'];
                        $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($parent_order, $prize, 1);
                    }
                }
                if (isset($t['parent_goods_id'])) {
                    $parent_goods = Dever::db('agent/member_goods')->getOne(array('id' => $t['parent_goods_id']));
                    if ($parent_goods && $parent_goods['num'] > 0) {
                        $parent_prize = Dever::db('setting/prize')->find($parent_goods['type_id']);
                        if ($parent_prize) {
                            # 检测有没有名额权益
                            $prize_goods = Dever::db('setting/prize_goods')->select(array('prize_id' => $parent_prize['id']));
                            if ($prize_goods) {
                                # 赠送权益
                                foreach ($prize_goods as $k1 => $v1) {
                                    $this->addGoods($parent_order, $v1, 1);
                                }
                            }

                            $member = Dever::db('agent/member')->find($t['parent_mid']);
                            if ($member) {
                                $desc = $parent_prize['name'] . '名额使用';
                                Dever::load('agent/lib/dhorder')->action($member, $parent_prize['name'], $parent_prize['num'], $parent_prize['price'], array(), -1, 2, 3, $parent_goods['type_id'], $desc);
                            }
                        }
                    }
                }

                if (!isset($t['parent_level'])) {
                    $t['parent_level'] = false;
                }
                if (!isset($t['child_num'])) {
                    $t['child_num'] = 0;
                }
                $member = Dever::db('agent/member')->find($where['mid']);
                $desc = $member['name'] . '成为代理商，佣金'.$t['per'].'%';
                
                Dever::load('agent/lib/member')->up($member, $where['parent_mid'], $order['id'], $order['role'], $where['type'], $t['cash'], $order['agent_cash'], $t['parent_level'], $desc, $t['child_num']);


                # 自动升级
                if (isset($t['role_up']) && $t['role_up']) {
                    $member = Dever::db('agent/member')->find(array('id' => $where['parent_mid']));
                    $role = Dever::db('setting/role')->find($t['role_up']['t_role_id']);
                    Dever::db('agent/member')->update(array('where_id' => $where['parent_mid'], 'role' => $t['role_up']['t_role_id']));
                    if ($member && $role) {
                        $this->upRole($member, $role, '', $order['id']);
                    }
                }
            }
        }
    }

    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);
        $desc = Dever::param('audit_desc', $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));
                Dever::load('agent/lib/dhorder')->updateSell($info, 2);

                if (Dever::project('sms')) {
                    $member = Dever::db('agent/member')->find($info['mid']);
                    Dever::load('sms/api')->send('daili_goods_no', $member['mobile'], array('name' => $member['name'], 'content' => $desc));
                }
            }
        }
    }

    # 确认收货
    public function setDhOrderStatus_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, $name = '')
    {
        if ($type == 1) {
            if ($name) {
                return array('name' => $name . '('.$type_id.')');
            }
            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 . '('.$type_id.')', 'price' => $goods_info['price']);
        } elseif ($type == 2) {
            $code = Dever::db('card/code')->find($sku_id);
            $card = Dever::db('card/info')->find($code['card_id']);
            return array('name' => $card['name'] . '('.$type_id.') <br /> ' . $code['card'], 'price' => $code['total_cash']);
        } elseif ($type == 3) {
            if ($name) {
                return array('name' => $name . '('.$type_id.')');
            }
            $prize = Dever::db('setting/prize')->find($type_id);

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

    public function setOrderStatus_api()
    {
        $where['where_id'] = Dever::input('id');
        $order = Dever::db('agent/order')->find($where['where_id']);
        if ($order) {
            $where['status'] = Dever::input('value');
            if ($where['status'] == 6) {
                $where['history_status'] = $order['status'];
            }
            Dever::db('agent/order')->update($where);
        }
        

        return 'reload';
    }

    public function upAgreement_api()
    {
        $id = Dever::input('id');
        if ($id) {
            Dever::load('agent/lib/agreement')->upContent($id);
        }
        

        return 'reload';
    }

    public function dropAgreement_api()
    {
        $id = Dever::input('id');
        if ($id) {
            Dever::load('agent/lib/agreement')->drop($id);
        }
        

        return 'reload';
    }

    public function memberShop_api(){
        $data = Dever::db('agent/member')->getShopAll(array('shop_id'=>1,'state'=>1));
        if($data){
            foreach($data as $k=>$v){
                $log = Dever::db('agent/member_shop_log')->find(array('mid'=>$v['id']));
                if($log){ 
                }else{
                    Dever::db('agent/member_shop_log')->insert(array('mid'=>$v['id'],'new_shop_id'=>$v['shop_id'],'cdate'=>'1651680000'));
                }
            }
        }
        return 'ok';
    }

    public function updateUserBind($id, $name, $data)
    {
        Dever::config('base')->hook = true;
        $update = array();
        $audit = Dever::param('audit', $data);
        $desc = Dever::param('audit_desc', $data);
        $info = Dever::db('agent/user_bind')->one($id);
        if ($info) {
            if ($audit) {
                $update['where_id'] = $info['id'];
                $update['audit_date'] = time();
                $update['status'] = $audit;
                $admin = Dever::load('manage/auth.info');
                $update['admin'] = $admin['id'];
                Dever::db('agent/user_bind')->update($update);
            }
        }
    }

    public function search_api()
    {
        $where = array();
        return Dever::search('agent/member', $where);
    }
    public function out_arealog($data){
        $header = array('区域名称', '区域价值', '售出时间');
        $body = array();
        foreach($data as $k1=> $v1){
            $member = Dever::db('agent/member')->find($v1['mid']);
            $role = Dever::db('setting/role')->find($member['role']);
            if ($role['type'] == 1) {
                $data[$k1]['price'] = $role['price'];
            } 
            if(isset($data[$k1]['price']) && $data[$k1]['price']<1){
                unset($data[$k1]);
            }
        }
        $res = array_values($data);
        foreach($res as $k=>$v){
            $res[$k]['areas'] = Dever::load("area/api.string", $v['area']);
            $member = Dever::db('agent/member')->find($v['mid']);
            $role = Dever::db('setting/role')->find($member['role']);
            $res[$k]['cdate'] = date('Y-m-d H:i',$v['cdate']);
            if ($role['type'] == 1) {
                $res[$k]['price'] = $role['price'];
            } elseif ($role['type'] == 2) {
                $res[$k]['price'] = Dever::load('area/api')->getPrice($role['area'], $v['area']);
            }
            
           $d = array
           (
                $res[$k]['areas'],
                $res[$k]['price'],
                $res[$k]['cdate']

            );

           $body[] = $d;
        }
        $file = Dever::input('excel_name');
        return Dever::excelExport($body, $header, $file);
    }
    public function out_zhitui($data){
        $header = array('推荐人姓名', '手机号', '身份证', '角色', '被推荐人姓名', '手机号', '身份证', '角色','代理费','奖励金','时间');

        $body = array();
        foreach($data as $k => $v){
            if($v['parent_mid']>0){
                $member = Dever::db('agent/member')->find($v['parent_mid']);
                $prole_name = '';
                if($member && $member['role']){
                    $prole = Dever::db('setting/role')->find($member['role']);
                    if($prole && $prole['name']){
                        $prole_name = $prole['name'];
                    }
                }
                $role_name = '';
                if($v['role']){
                    $role = Dever::db('setting/role') ->find($v['role']);
                    if($role && $role['name']){
                        $role_name = $role['name'];
                    }
                }
                
                $order = Dever::db('agent/order')->find(array('mid'=>$v['id']));
                $cdate = '';
                if($v['cdate']){
                    $cdate = date('Y-m-d H:i',$v['cdate']);
                }
                if($member){
                    $d = array
                    (
                        $member['name'],
                        $member['mobile'],
                        $member['idcard'],
                        $prole_name,
                        $v['name'],
                        $v['mobile'],
                        $v['idcard'],
                        $role['name'],
                        $order['agent_cash'],
                        $v['cash'],
                        $cdate,
                    );
                    $body[] = $d;
                }
            }
        }
        $file = Dever::input('excel_name');
        return Dever::excelExport($body, $header, $file);
    }
}