<?php

namespace Agent\Lib;

use Dever;

class Order
{
    /**
     * 下单
     *
     * @return mixed
     */
    public function action($mid)
    {
        $config = Dever::db('setting/base')->one();
        if($config['type'] == 2){
            Dever::alert($config['type_desc']);
        }
        $member = array();
        $parent_mid = -1;
        if ($mid > 0) {
            $member = Dever::db('agent/member')->find($mid);
            if (!$member) {
                Dever::alert('代理商不存在');
            }
            
            $mobile = $member['mobile'];
            
            $data['mid'] = $member['id'];
            $data['type'] = $member['type'];
            $data['name'] = $member['name'];
            $data['idcard'] = $member['idcard'];
            $data['idcard_front'] = $member['idcard_front'];
            $data['idcard_back'] = $member['idcard_back'];
            $data['company_name'] = $member['company_name'];
            $data['company_pic'] = $member['company_pic'];
            $data['company_number'] = $member['company_number'];
            $data['source_id'] = $member['source_id'];

            $code = Dever::input('code');
            if ($code) {
                $uid = Dever::load('invite/api')->getUid($code);
                if ($uid) {
                    $user = Dever::db('agent/member')->find($uid);
                    if ($user && $user['status'] <= 2) {
                        $parent_mid = $user['id'];
                    }
                    $data['parent_code'] = $code;
                }
            } else {
                $parent_mid = $member['parent_mid'];
                if ($parent_mid && $parent_mid > 0) {
                    $parent_code = Dever::load("invite/api.code", $parent_mid);
                    if ($parent_code) {
                        $data['parent_code'] = $parent_code;
                    }
                }
            }
            
        } else {
            $mobile = Dever::input('mobile');
            $where['mobile'] = Dever::load('agent/lib/member')->checkMobile($mobile);
            $checkMember = Dever::db('agent/member')->find($where);

            if ($checkMember) {
                Dever::alert('注册失败，手机号已存在');
            }

            $code = Dever::input('code');
            if ($code) {
                $uid = Dever::load('invite/api')->getUid($code);
                if ($uid) {
                    $user = Dever::db('agent/member')->find($uid);
                    if ($user && $user['status'] <= 2) {
                        $parent_mid = $user['id'];
                    }
                    $data['parent_code'] = $code;
                }
            }

            $data['type'] = Dever::input('type', 1);
            $data['name'] = Dever::input('name');
            $data['idcard'] = Dever::input('idcard');
            $data['idcard_front'] = Dever::input('idcard_front');
            $data['idcard_back'] = Dever::input('idcard_back');
            $data['company_name'] = Dever::input('company_name');
            $data['company_pic'] = Dever::input('company_pic');
            $data['company_number'] = Dever::input('company_number');
            $data['source_id'] = Dever::input('source_id');
        }
        if($data['idcard']){
             $birth = strlen($data['idcard'])==15 ? ('19' . substr($data['idcard'], 6, 6)) : substr($data['idcard'], 6, 8);
             $year=substr($birth,0,4);#出生年份
             $month=substr($birth,4,4);#出生日期
             $y=date('Y',time());#当前年份
             $m=date('md',time());#当前日期
             if(($m-$month)<0){
                $zhou=$y-$year-1;
             }else{
                $zhou=$y-$year;
             }
             if($zhou>=65 || $zhou<18){
                Dever::alert('您不满足申请条件，请联系客服');
             }
        }
        $idcard_path = Dever::input('idcard_path');
        if($idcard_path){
            $data['idcard_path'] = $idcard_path;
            $idcard_path = (array)json_decode($data['idcard_path']);
            if($idcard_path['face']){
                $rest = (array)$idcard_path['face'];
                if($data['name'] != $rest['name'] || $data['idcard'] != $rest['idNumber']){
                    Dever::alert('姓名或身份证号不匹配');
                }
            }
            if($idcard_path['back']){
                $rest = (array)$idcard_path['back'];
                $date = explode('-',$rest['validPeriod']);
                if($date[1] && $date[1]!='长期'){
                    $cdate = strtotime(str_replace('.','-',$date[1]));
                    if(time()>=$cdate){
                        Dever::alert('身份证背面已过期');
                    }
                }
                
            }
        }
        if ($data['source_id'] && $data['source_id'] > 0) {
            $data['invite_type'] = 2;
        } else {
            $data['invite_type'] = 1;
            if ($parent_mid < 0) {
                Dever::alert('请填写正确的邀请码');
            }
        }
        
        Dever::load('agent/lib/member')->checkMcode($mobile);

        $data['mobile'] = $mobile;
        $data['parent_mid'] = $parent_mid;

        if (!$data['idcard_front']) {
            Dever::alert('身份证正面不能为空');
        }
        if (!$data['idcard_back']) {
            Dever::alert('身份证反面不能为空');
        }

        if ($data['type'] == 2) {
            if (!$data['company_name']) {
                Dever::alert('公司名称不能为空');
            }
            if (!$data['company_pic']) {
                Dever::alert('营业执照照片不能为空');
            }
            if (!$data['company_number']) {
                Dever::alert('营业执照号码不能为空');
            }
        }
        if (!$data['name']) {
            Dever::alert('姓名不能为空');
        }
        if (!$data['idcard']) {
            Dever::alert('身份证号不能为空');
        }

        if (!preg_match(Dever::rule('idcard'), $data['idcard'])) {
            Dever::alert('身份证号不正确');
        }

        $data += $this->getPrice($member);

        $data['sign'] = Dever::input('sign');

        /*
        if (!$data['sign']) {
            Dever::alert('手写签名不能为空');
        }*/

        $data['order_num'] = $this->getOrderId();

        # 付款信息
        $data['pay_type'] = Dever::input('pay_type', 1);

        if ($data['pay_type'] == 1 && $data['role']['type'] == 1) {
            //Dever::alert('暂时不支持在线支付');
            /*
            $data['openid'] = Dever::input('openid');
            if (!$data['openid']) {
                Dever::alert('请先授权');
            }
            */
        } elseif ($data['pay_type'] == 3) {
            $data['bank_id'] = Dever::input('bank_id');
            if (!$data['bank_id']) {
                Dever::alert('请选择银行');
            }
            $data['bank_card'] = Dever::input('bank_card');
            if (!$data['bank_card']) {
                Dever::alert('请输入银行卡号');
            }
        } else {
            # 汇款
            $data['pay_pic'] = Dever::input('pay_pic');
            if (!$data['pay_pic']) {
                Dever::alert('请上传打款凭证');
            }
            $data['pay_price'] = Dever::input('pay_price');
        }

        $where['mobile'] = $data['mobile'];
        $where['role'] = $data['role']['id'];
        $where['area'] = $data['area'];

        $info = Dever::db('agent/order')->find($where);
        if ($info && $info['status'] != 5) {
            //Dever::alert('请勿重复提交');
        }

        $data['role'] = $where['role'];
        $data['status'] = -2;
        $data['mid'] = Dever::load('agent/lib/member')->create($data);
        if ($data['mid']) {
            $data['udate'] = time();
            $data['id'] = Dever::db('agent/order')->insert($data);
        } else {
            $data['id'] = false;
        }

        if ($data['id']) {
            # 生成代理商
            $result = Dever::load('passport/reg')->getSign($data['mid']);
            $result['order_id'] = $data['id'];
            $result['msg'] = '您的申请已经提交完成，请耐心等待，我们将在工作日8小时内为您通过审核，非常感谢。';

            $agreement = Dever::db('setting/agreement')->getData();
            list($temp, $result['agreement_1']) = Dever::load('agent/lib/agreement')->name($agreement[1], $data, $data['role'], 1, 2);
            list($temp, $result['agreement_4']) = Dever::load('agent/lib/agreement')->name($agreement[4], $data, $data['role'], 1, 2);

            if ($data['pay_type'] == 3) {
                $result['bank_msg'] = '您需要使用银行卡：所有人（'.$data['name'].'），账号（'.$data['bank_card'].'），转账至如下账户（'.$data['price_str'].'）:';
                $config = Dever::db('setting/base')->find();
                $result['bank_user'] = $config['bank_user'];
                $result['bank_name'] = $config['bank_name'];
                $result['bank_card'] = $config['bank_card'];
            } elseif ($data['pay_type'] == 1) {
                # 在线支付 生成支付信息
                $result['pay'] = $this->pay($data);
            }

            return $result;
        } else {
            Dever::alert('登录失败');
        }
    }

    # 签名确认
    public function sign($mid, $order_id)
    {
        if (!$order_id) {
            Dever::alert('验证失败');
        }
        $where['mid'] = $mid;
        $where['id'] = $order_id;
        $info = Dever::db('agent/order')->find($where);
        if (!$info) {
            Dever::alert('验证失败');
        }
        if ($info['status'] != -2) {
            //Dever::alert('验证失败');
        }
        $update['sign'] = $sign = Dever::input('sign');
        if (!$update['sign']) {
            Dever::alert('请上传签名');
        }
        $update['status'] = 1;
        $update['where_id'] = $info['id'];
        $state = Dever::db('agent/order')->update($update);
        if ($state) {
            $update = array();
            $update['sign'] = $sign;
            $update['where_id'] = $mid;
            $state = Dever::db('agent/member')->update($update);
            $result = Dever::load('passport/reg')->getSign($mid);
            return $result;
        } else {
            Dever::alert('验证失败');
        }
    }

    /**
     * 发起在线支付
     *
     * @return mixed
     */
    public function pay($data)
    {
        $param = array
        (
            'project_id' => 4,
            'channel_id' => 1,
            'system_source' => 1,
            'account_id' => 8,
            'uid' => $data['id'],
            'name' => $data['name'],
            //'openid' => $data['openid'],
            'cash' => $data['price'],
            'product_id' => $data['id'],
            'order_id' => $data['order_num'],
            'h5' => 1,
            'refer' => Dever::input('refer', 'http://guanli.uat.churenyiliao.com/data/payback/payback.html'),
        );

        $result = Dever::load('pay/api.pay', $param);
        $result['order_num'] = $data['order_num'];
        $result['order_id'] = $data['id'];

        return $result;
    }

    /**
     * 生成订单号
     *
     * @return mixed
     */
    public function getOrderId()
    {
        $where['order_num'] = Dever::order('D');
        $where['clear'] = true;
        $state = Dever::db('agent/order')->one($where);
        if (!$state) {
            return $where['order_num'];
        } else {
            return $this->getOrderId();
        }
    }

    # 支付成功回调 安全加密 设置token
    public function success_secure_api_token()
    {
        $project_id = Dever::input('pay_project_id');
        $info = Dever::db('pay/project')->one($project_id);
        if ($info) {
            return $info['key'];
        }
        return 'agent_buy_dever_2020';
    }

    # 支付成功回调 安全加密
    public function success_secure_api($param = array())
    {
        $this->success($param);
    }

    # 支付成功回调
    public function success($param = array())
    {
        $send = $param ? $param : Dever::preInput('pay_');
        $product_id = $send['pay_product_id'];
        $order_id = $send['pay_order_id'];
        $status = $send['pay_status'];
        $cash = $send['pay_cash'];
        $msg = $send['pay_msg'];

        $order = Dever::db('agent/order')->one(array('id' => $product_id, 'clear' => true));
        if ($order && $status == 2) {
            $update['pay_status'] = 2;
            $update['where_id'] = $order['id'];
            Dever::db('agent/order')->update($update);
        }

        return 'ok';
    }

    /**
     * 获取支付金额
     *
     * @return mixed
     */
    public function getPrice($member = false)
    {
        if ($member && !is_array($member)) {
            $member = Dever::db('agent/member')->find($member);
        }
        
        $data['role'] = Dever::input('role');
        if (!$data['role']) {
            Dever::alert('代理类型不能为空');
        }
        $data['role'] = Dever::db('setting/role')->find($data['role']);
        if (!$data['role']) {
            Dever::alert('代理类型不正确');
        }
        if ($data['role']['isbuy'] != 1) {
            Dever::alert('代理类型不正确');
        }
        $data['area'] = Dever::input('area');
        if ($data['role']['type'] == 2 && !$data['area']) {
            Dever::alert('代理区域不能为空');

            if (strstr($data['area'], '-1')) {
                Dever::alert('代理区域选择不正确');
            }
        }

        # 计算支付金额
        if ($data['role']['type'] == 1) {
            $data['price'] = $data['role']['price'];
        } elseif ($data['role']['type'] == 2) {
            $data['area'] = $this->checkArea($data['area'], $data['role'], $member ? $member['id'] : false);
            $data['price'] = Dever::load('area/api')->getPrice($data['role']['area'], $data['area']);
            if ($data['price'] <= 0) {
                Dever::alert('代理区域的代理价格为空，请联系客服');
            }
        } else {
            Dever::alert('代理类型不正确');
        }

        $data['order_type'] = 1;
        if ($member) {
            $member_role = Dever::db('setting/role')->find($member['role']);
            if ($member_role) {
                if ($member_role['levelup'] != 1) {
                    Dever::alert('当前代理角色无法升级');
                } elseif ($member_role['levelup_yue'] == 1) {
                    //$area = Dever::db('agent/member_area')->getOne(array('mid' => $member['id'], 'type' => 1));
                    $price = Dever::db('agent/order')->getPrice(array('mid' => $member['id']));
                    if ($price && $data['price'] > $price['total']) {
                        $data['price'] -= $price['total'];
                    } else {
                        Dever::alert('该代理区域无法升级');
                    }
                }
                $data['order_type'] = 2;
            }
        }

        if ($data['price'] >= 10000) {
            $data['price_str'] = ($data['price']/10000) . '万元';
        } else {
            $data['price_str'] = $data['price'] . '元';
        }

        if (is_int($data['price'])) {
            $data['price_str'] .= '整';
        }

        $data['f_price'] = $data['price'];

        return $data;
    }

    public function checkArea($area, $role, $mid = false)
    {
        if (is_string($area)) {
            $area = explode(',', $area);
        }
        $result = array();
        foreach ($area as $k => $v) {
            if ($role['area'] == 1) {
                if ($v < 0) {
                    if ($k == 1) {
                        Dever::alert('请选择城市');
                    }
                } elseif ($k < 2) {
                    $result[] = $v;
                }
            }
            if ($role['area'] == 2) {
                if ($v < 0) {
                    if ($k == 1) {
                        Dever::alert('请选择城市');
                    } elseif ($k == 2) {
                        Dever::alert('请选择区县');
                    }
                } elseif ($k < 3) {
                    $result[] = $v;
                }
            }
            if ($role['area'] == 3) {
                if ($v < 0) {
                    if ($k == 1) {
                        Dever::alert('请选择城市');
                    } elseif ($k == 2) {
                        Dever::alert('请选择区县');
                    } elseif ($k == 3) {
                        Dever::alert('请选择街道');
                    }
                } elseif ($k < 4) {
                    $result[] = $v;
                }
            }
        }

        $num = count($result);
        if ($role['area'] == 1 && $num < 2) {
            Dever::alert('请选择城市');
        } elseif ($role['area'] == 2 && $num < 3) {
            Dever::alert('请选择区县');
        } elseif ($role['area'] == 3 && $num < 4) {
            Dever::alert('请选择街道');
        }

        $result = implode(',', $result);
        $result = str_replace(',-1', '', $result);
        $area_info = Dever::db('agent/member_area')->getOne(array('area' => $result, 'role' => $role['id']));
        if ($area_info) {
            if ($mid) {
                if ($mid != $area_info['mid']) {
                    Dever::alert('该区域已被占用');
                }
            } else {
                Dever::alert('该区域已被占用');
            }
        }

        return $result;
    }


    # 展示订单详情
    public function show()
    {
        $id = Dever::input('order_id');

        $config = Dever::db('agent/order')->config['set'];

        $info = Dever::db('agent/order')->one($id);

        $process = Dever::db('agent/order_process')->getData(array('order_id' => $id));
        $process_status = Dever::db('agent/order_process')->config['status'];

        //print_r($process);die;
        $role = Dever::db('setting/role')->one($info['role']);
        $area = Dever::load("area/api.string", $info['area'], '');

        $status = Dever::status($config['status'], $info['status']);

        $member = array();
        if ($info['mid'] > 0) {
            $member = Dever::db('agent/member')->find($info['mid']);
        }
        
        $parent_member = array();
        if ($info['parent_mid'] > 0) {
            $parent_member = Dever::db('agent/member')->find($info['parent_mid']);
        }

        $cdate = date('Y-m-d H:i', $info['cdate']);

        if ($info['fdate']) {
            $fdate = date('Y-m-d H:i', $info['fdate']);
        } else {
            $fdate = '';
        }

        $result = array();

        $result[$info['order_num']] = array
        (
            'type' => 'user',
            'content' => array
            (
                array('订单状态', $status),
                array('订单类型', $config['order_type'][$info['order_type']]),
                array('申请日期', $cdate),
                array('管理员备注', $info['admin_desc']),
            )
        );

        if ($process) {
            foreach ($process as $k => $v) {
                $v['cdate'] = date('Y-m-d H:i', $v['cdate']);
                if($v['status'] == 1 || $v['status'] == 2){
                    $admin = Dever::load('manage/admin-find',$v['admin']);
                    if($v['desc']){
                         $v['cdate'] .= '<br/>操作人：'.$admin['username'].'<br/>备注：'.$v['desc'];
                     }else{
                        $v['cdate'] .= '<br/>操作人：'.$admin['username'];
                     }
                    
                } 
                $result[$info['order_num']]['content'][] = array($process_status[$v['status']], $v['cdate']);
            }
        }
        $idcard_pic = '<a href="'.$info['idcard_front'].'" target="_blank"><img src="'.$info['idcard_front'].'" width="100" /></a>';
        if ($info['idcard_back']) {
            $idcard_pic .= '&nbsp;&nbsp;<a href="'.$info['idcard_back'].'" target="_blank"><img src="'.$info['idcard_back'].'" width="100" /></a>';
        }
        if ($info['sign']) {
            $sign_pic = '<a href="'.$info['sign'].'" target="_blank"><img src="'.$info['sign'].'" width="100" /></a>';
        } else {
            $sign_pic = '暂无';
        }
        

        $pay_pic = '';
        if ($info['pay_pic']) {
            $temp = explode(',', $info['pay_pic']);
            foreach ($temp as $k => $v) {
                $pay_pic .= '&nbsp;&nbsp;<a href="'.$v.'" target="_blank"><img src="'.$v.'" width="100" /></a>';
            }
        }

        if (!$member['avatar']) {
            $default = Dever::db('passport/avatar')->one(1);
            $member['avatar'] = $default['avatar'];
        }

        $result['账号信息'] = array
        (
            'type' => 'user',
            'pic' => $member['avatar'],
            'content' => array
            (
                array('类型', $config['type'][$info['type']]),
                array('姓名', $info['name']),
                array('手机号', $info['mobile']),

                array('代理角色', $role['name']),
                array('代理区域', $area),
                //array('注意', '赠送区域无权益'),
                array('身份证号码', $info['idcard']),
            ),
        );

        if ($info['type'] == 2) {
            $company_pic = '&nbsp;&nbsp;<a href="'.$info['company_pic'].'" target="_blank"><img src="'.$info['company_pic'].'" width="100" /></a>';
            $result['账号信息']['content'][] = array
            (
                array('企业名称', $info['company_name']),
                array('营业执照号码', $info['company_number']),
                array('营业执照照片', $company_pic),
            );
        }

        $result['账号信息']['content'][] = array('身份证照片', $idcard_pic);
        $result['账号信息']['content'][] = array('代理商签名', $sign_pic);


        $result['支付信息'] = array
        (
            'type' => 'user',
            'content' => array
            (
                array('支付方式', $config['pay_type'][$info['pay_type']]),
                array('支付状态', $config['pay_status'][$info['pay_status']]),
                array('付款备注', $info['desc']),

                array('应付金额', '¥' . $info['f_price'] . '元'),
                array('实付金额', '¥' . $info['price'] . '元'),
                array('代理费', '¥' . $info['agent_cash'] . '元'),

                array('软件服务费', '¥' . $info['soft_cash'] . '元'),
                array('商品价值', '¥' . $info['goods_cash'] . '元'),
                array('赠送期权价值', '¥' . $info['option_price'] . '元'),

                array('支付凭证', $pay_pic),
            ),
        );

        if ($info['parent_mid'] && $info['parent_mid'] > 0) {
            $parent = Dever::db('agent/member')->one($info['parent_mid']);
            if ($parent) {
                $result['上级信息'] = Dever::load('agent/lib/member')->getShowInfo($parent);
            }
        }

        

        $button = $this->show_button($process, $info, $role, $parent_member);

        if (($info['status'] == 3 || $info['status'] == 4) && $info['agent_cash'] >= 0) {

            if (isset($process[3]) && $process[3]) {
                $process[3]['type'] = explode(',', $process[3]['type']);
            }

            if ($info['import'] == 1) {
                # 分润信息
                if ($parent_member) {
                    $this->show_parent($parent_member, $process, $info, $role, $result);
                }

                # 权益信息
                $this->show_goods($process, $info, $role, $result);
            }

            # 合同信息
            $this->show_agreement($process, $info, $role, $sign_pic, $result);
        }
        
        
        $head = array
        (
            'name' => '基本信息',
            'btn' => $button,
        );
        $html = Dever::show($head, $result, false, false, 'dls-user-box');

        return $html;
    }

    private function show_button($process, $info, $role, $parent_member)
    {
        $button = array();
        $cstatus = ',cstatus,soft_price';
        $soft_price = 0;
        if ($role['soft'] && $info['price'] > 0 && $info['status'] > 1) {
            //$cstatus = ',cstatus';
            //$soft = '【<a href="" style="color:blue">拆分代理费</a>】';
            if (strstr($role['soft'], '%')) {
                $role['soft'] = str_replace('%', '', $role['soft']);
                $role['soft'] = $info['price'] * ($role['soft']/100);
            }
            $soft_price = $role['soft'];
        }
        $option_price = 0;
        if($role['option_price'] && $info['price'] > 0 && $info['status'] > 0){
            if(strstr($role['option_price'],'%')){
                $role['option_price'] = str_replace('%','',$role['option_price']);
                $role['option_price'] = $info['price'] * ($role['option_price']/100);
            }
            $option_price = $role['option_price'];
        }
        if (Dever::load('manage/auth')->checkFunc('agent.order', 'edit', '备注')) {
            $purl = Dever::url('project/database/update?project=agent&table=order&where_id='.$info['id'].'&col=admin_desc', 'manage');
            $button[] = array
            (
                'type' => 'edit',
                'link' => $purl,
                'name' => '备注',
            );
        }

        if (Dever::load('manage/auth')->checkFunc('agent.order', 'edit1', '修改资料')) {
            if ($info['status'] <= 1 || $info['status'] == 5) {
                $purl = Dever::url('project/database/update?project=agent&table=order&where_id='.$info['id'].'&col=invite_type,parent_code,source_id,name,idcard,type,idcard_front,idcard_back,company_name,company_number,company_pic,pay_type,pay_pic,role,area', 'manage');

                $button[] = array
                (
                    'type' => 'edit',
                    'link' => $purl,
                    'name' => '修改资料',
                );
            }
        }

        if (Dever::load('manage/auth')->checkFunc('agent.order', 'edit_qiquan', '修改期权价值')) {
            $purl = Dever::url('project/database/update?project=agent&table=order&where_id='.$info['id'].'&col=option_price,soft_cash', 'manage');

            $button[] = array
            (
                'type' => 'edit',
                'link' => $purl,
                'name' => '修改期权价值',
            );
        }

        if (Dever::load('manage/auth')->checkFunc('agent.order', 'edit2', '挂起')) {
            if ($info['status'] <= 3 && $info['status'] > 0) {
                # 未完成审核的订单，可以随时挂起
                $button[] = array
                (
                    'type' => 'action',
                    'link' => Dever::url('lib/manage.setOrderStatus?id=' . $info['id'] . '&value=6', 'agent'),
                    'name' => '挂起',
                );
            } elseif ($info['status'] == 6) {
                # 恢复挂起
                $button[] = array
                (
                    'type' => 'action',
                    'link' => Dever::url('lib/manage.setOrderStatus?id=' . $info['id'] . '&value=' . $info['history_status'], 'agent'),
                    'name' => '恢复',
                );
            }
        }

        if ($info['status'] == 1) {
            # 根据价值获取名额
            $prize = Dever::db('setting/prize')->find(array('type' => 1, 'price' => $info['price']));
            if ($prize) {
                $member_goods = Dever::db('agent/member_goods')->getOne(array('mid' => $info['mid'], 'type' => 3, 'type_id' => $prize['id']));
                if ($member_goods && $member_goods['num'] > 0) {
                    # 有名额
                    $cstatus = ',prize_type';
                }
            }
            $purl = Dever::url('project/database/update?project=agent&table=order_process&order_id='.$info['id'].'&status=1&col=order_id,status,audit,price,option_price,desc'.$cstatus.'&price='.$info['price'].'&soft_price=' . $soft_price.'&option_price='.$option_price, 'manage');
            if (isset($process[1]) && $process[1]) {
                $purl .= '&where_id=' . $process[1]['id'];
            }

            if (Dever::load('manage/auth')->checkFunc('agent.order', 'edit3', '业务初审')) {
                if ($parent_member) {
                    if ($parent_member['status'] == 2) {
                        $button[] = array
                        (
                            'type' => 'edit',
                            'link' => $purl,
                            'name' => '业务初审',
                        );
                    } else {
                        $button[] = array
                        (
                            'type' => 'click',
                            'content' => 'showCs()',
                            'name' => '业务初审<script>function showCs(){layer.msg("直属上级未认证，无法进行初审")}</script>'
                        );
                    }
                    
                } else {
                    $button[] = array
                    (
                        'type' => 'edit',
                        'link' => $purl,
                        'name' => '业务初审',
                    );
                }
            }
            
        } elseif ($info['status'] == 2) {
            
            $purl = Dever::url('project/database/update?project=agent&table=order_process&order_id='.$info['id'].'&status=2&col=order_id,status,audit,desc', 'manage');
            if (isset($process[2]) && $process[2]) {
                $purl .= '&where_id=' . $process[2]['id'];
            }
            if (Dever::load('manage/auth')->checkFunc('agent.order', 'edit4', '财务终审')) {
                $button[] = array
                (
                    'type' => 'edit',
                    'link' => $purl,
                    'name' => '财务终审',
                );
            }
            
        } elseif ($info['status'] == 3) {
            $purl = Dever::url('project/database/update?project=agent&table=order_process&order_id='.$info['id'].'&status=3&col=order_id,status,type', 'manage');
            if (isset($process[3]) && $process[3]) {
                $purl .= '&where_id=' . $process[3]['id'];
            }
            if (Dever::load('manage/auth')->checkFunc('agent.order', 'edit5', '确认完成')) {
                $button[] = array
                (
                    'type' => 'edit',
                    'link' => $purl,
                    'name' => '确认完成',
                );
            }
        }
        #新加2022.4.8
        $button[] = array
        (
            'type' => 'link',
            'link' => 'refer',
            'name' => '返回上一页',
        );
        return $button;
    }

    private function getAreaAgent($area, $value)
    {
        $city_role = Dever::db('setting/role')->find(array('type' => 2, 'area' => $value));
        if ($city_role) {
            $area_info = Dever::db('agent/member')->find(array('area' => $area, 'role' => $city_role['id']));
            if ($area_info && $area_info['status'] <= 2) {
                
                if ($area_info['level_id'] > 0) {
                    $area_info['level'] = Dever::db('setting/level')->find($area_info['level_id']);
                } else {
                    $area_info['level'] = array('id' => -1, 'name' => '普通', 'level' => 0, 'num' => 1, 'value' => '0');
                }
                $area_info['role'] = $city_role;
                return $area_info;
            }
        }
        return array();
    }

    private function show_parent($parent_member, $process, $info, $role, &$result)
    {
        # 这里要获取上级信息
        $table = array();
        $table['head'] = array('类型', '姓名', '手机', '角色', '级别', '比例/数量', '金额/名称');
        $table['body'] = array();

        $parents[0] = array('uid' => $parent_member['id'], 'level' => 0);
        $parents = array_merge($parents, Dever::load('invite/api')->getParentAll($parent_member['id'], 100));

        $parent_per = 0;
        $max_per = 15;
        $level_up = false;
        $html = '';
        $parent_name = '';

        # 获取区域代理
        $area_agent = array();
        if ($role['type'] == 2 && $role['area'] > 1) {
            if ($role['area'] == 2) {
                # 区县，只需获取城市代理
                $temp = explode(',', $info['area']);
                $area_agent['city'] = $this->getAreaAgent($temp[0] . ',' . $temp[1], 1);
            } elseif ($role['area'] == 3) {
                # 街道，同时获取区县和城市代理
                $temp = explode(',', $info['area']);
                $area_agent['city'] = $this->getAreaAgent($temp[0] . ',' . $temp[1], 1);
                $area_agent['county'] = $this->getAreaAgent($temp[0] . ',' . $temp[1] . ',' . $temp[2], 2);
            }
        }
        foreach ($parents as $k => $v) {
            $parent_info = Dever::db('agent/member')->find($v['uid']);
            if ($parent_info && $parent_info['status'] == 2) {
                $child_num = 0;
                $parent_role = Dever::db('setting/role')->find($parent_info['role']);
                if ($parent_info['level_id'] > 0) {
                    $parent_level = Dever::db('setting/level')->find($parent_info['level_id']);
                } else {
                    $parent_level = array('id' => -1, 'name' => '普通', 'level' => 0, 'num' => 1, 'value' => '0');
                }
                $cash = 0;
                $level = array();

                if ($parent_per < $max_per) {
                    $order_cash = Dever::db('agent/order_cash')->getData(array('order_id' => $info['id'], 'parent_mid' => $v['uid'], 'type' => 2));

                    if ($order_cash) {
                        $cash = $order_cash['cash'];
                        $parent_level['value'] = $order_cash['per'];
                        $parent_per += $parent_level['value'];
                    } else {
                        # 根据团队业绩获取等级
                        # 获取当前用户的团队业绩
                        if (!$parent_info['group_sell']) {
                            $parent_info['group_sell'] = 0;
                        }
                        $sell = $parent_info['group_sell'] + $info['agent_cash'];

                        $level = Dever::db('setting/level')->getOne(array('target' => ($sell/10000)));
                        if ($level && $level['level'] > $parent_level['level']) {
                            # 升级
                            $level_up = true;
                            /* 本次升级不计算分润 注释这里即可 */
                            $old = $parent_level;
                            $parent_info['level_id'] = $level['id'];
                            $parent_level = $level;
                            $parent_level['name'] = $old['name'] . '->' . $level['name'];
                        }

                        # 获取直推人数
                        $child_num = Dever::load('invite/api')->getChildNum($v['uid'], 1);

                        if ($parent_level['id'] > 0 && $child_num >= $parent_level['num']) {
                            # 达到要求，开始团队分润
                            if ($parent_per > 0) {
                                $parent_level['value'] = $parent_level['value'] - $parent_per;
                            }
                            if ($parent_level['value'] > 0) {
                                $cash += $info['agent_cash'] * ($parent_level['value']/100);
                                $parent_per += $parent_level['value'];
                            }
                        }
                    }

                    # 直推佣金
                    if ($k == 0) {
                        $parent_name = $this->show_parent_reward($parent_info, $info, $role, $v, $parent_role, $parent_level, $child_num, $table);

                        $this->show_area_reward($parent_info, $info, $role, $v, $parent_role, $parent_level, $area_agent, $table);
                    }
                }

                $param = array();
                $param['type'] = 2;
                $param['order_id'] = $info['id'];
                $param['parent_mid'] = $parent_info['id']; 
                if (isset($level_up) && $level_up && isset($level) && $level) {
                    $param['parent_level'] = $level['id'];
                    $param['child_num'] = $child_num;
                }
                if ($parent_level['id'] && $parent_level['value'] > 0 && $cash > 0) {
                    $param['cash'] = $cash;
                    $param['per'] = $parent_level['value'];

                    $data_param = Dever::array_encode($param);

                    $cash = '<a style="color:blue" class="set_cash" data-param="'.$data_param.'">' . $cash . '</a>';

                    $table['body'][] = array('团队佣金', $parent_info['name'], $parent_info['mobile'], $parent_role['name'], $parent_level['name'], $parent_level['value'] . '%', $cash);
                } else {              
                    $param['cash'] = 0;
                    $param['per'] = 0;
                    $data_param = Dever::array_encode($param);

                    $html .= '<a style="color:blue;display:none;" class="set_cash" data-param="'.$data_param.'">&nbsp;&nbsp;</a>';
                }
            }
        }

        if (!$table['body']) {
            $table['head'] = array();
        }

        if (isset($process[3]['type']) && is_array($process[3]['type']) && in_array(3, $process[3]['type'])) {
            $parent_title = '（已发放分润）';
            $parent_button = array();
        } else {
            $parent_title = '（未发放分润）' . $html;
            /*
            $parent_button[] = array
            (
                'type' => 'link',
                'link' => Dever::url('lib/order_set.home?order_id='.$info['id'].'&role_id=' . $info['role'], 'agent'),
                'name' => '修改分润金额'
            );*/

            $furl = Dever::url('lib/manage.set_commit?json=1&type=3&order_id='.$info['id'], 'agent');
            $parent_button[] = array
            (
                'type' => 'click',
                'content' => 'setCash()',
                'name' => '确认发放分润<script>function setCash(){layer.confirm(\'确定进行此项操作吗？\', function(){var cash = [];$(\'.set_cash\').each(function(){cash.push($(this).attr(\'data-param\'));});$.post(\''.$furl.'\',{param:cash.join(",")}, function(t){t=JSON.parse(t);showYes(t)})})}</script>'
            );
        }
        
        $parent_name = '';
        $result['分润信息' . $parent_title] = array
        (
            'type' => 'table',
            'content' => $table,
            'head' => array('name' => '<span>' . $parent_name . '</span>', 'btn' => $parent_button),
        );
    }

    private function show_area_reward($parent_info, $info, $role, $v, $parent_role, $parent_level, $area_agent, &$table)
    {
        $order_cash = Dever::db('agent/order_cash')->getAll(array('order_id' => $info['id'], 'parent_mid' => $v['uid'], 'type' => 3));

        if ($order_cash) {
            foreach ($order_cash as $k => $v) {
                $v['cash'] = '<a style="color:blue">' . $v['cash'] . '</a>';
                $v['member'] = Dever::db('agent/member')->find($v['mid']);
                $v['level'] = Dever::db('setting/level')->find($v['member']['level_id']);
                $v['role'] = Dever::db('setting/role')->find($v['member']['role']);
                $table['body'][] = array('间推佣金', $v['member']['name'], $v['member']['mobile'], $v['role']['name'], $$v['level']['name'], $v['per'] . '%', $v['cash']);
            }
        } else {
            if (isset($area_agent['county']) && $area_agent['county'] && $area_agent['county']['id'] != $parent_info['id']) {
                $area_role_reward = Dever::db('setting/role_reward')->find(array('role_id' => $area_agent['county']['role']['id'], 't_role_id' => $role['id']));
                if ($area_role_reward) {
                    if (strstr($area_role_reward['fzt_qn_value'], ',')) {
                        $temp = explode(',', $area_role_reward['fzt_qn_value']);
                        $area_role_reward['fzt_qn_value'] = $temp[1];
                    }
                    
                    if ($area_role_reward['value_type'] == 1) {
                        $area_cash = round($info['agent_cash'] * ($area_role_reward['fzt_qn_value']/100), 2);
                        $area_per = $area_role_reward['fzt_qn_value'];
                    } else {
                        $area_cash = $area_role_reward['fzt_qn_value'];
                        $area_per = 0;
                    }

                    $area_param = array();
                    $area_param['type'] = 3;
                    $area_param['order_id'] = $info['id'];
                    $area_param['parent_mid'] = $area_agent['county']['id'];
                    $area_param['cash'] = $area_cash;
                    $area_param['per'] = $area_per;

                    $area_param = Dever::array_encode($area_param);
                    $area_cash = '<a style="color:blue" class="set_cash" data-param="'.$area_param.'">' . $area_cash . '</a>';

                    $table['body'][] = array('间推佣金', $area_agent['county']['name'], $area_agent['county']['mobile'], $area_agent['county']['role']['name'], $area_agent['county']['level']['name'], $area_per . '%', $area_cash);
                }
            }
            if (isset($area_agent['city']) && $area_agent['city'] && $area_agent['city']['id'] != $parent_info['id']) {
                $area_role_reward = Dever::db('setting/role_reward')->find(array('role_id' => $area_agent['city']['role']['id'], 't_role_id' => $role['id']));
                if ($area_role_reward) {
                    if (strstr($area_role_reward['fzt_qn_value'], ',')) {
                        $temp = explode(',', $area_role_reward['fzt_qn_value']);
                        $area_role_reward['fzt_qn_value'] = $temp[0];
                    }

                    if ($area_role_reward['value_type'] == 1) {
                        $area_cash = round($info['agent_cash'] * ($area_role_reward['fzt_qn_value']/100), 2);
                        $area_per = $area_role_reward['fzt_qn_value'];
                    } else {
                        $area_cash = $area_role_reward['fzt_qn_value'];
                        $area_per = 0;
                    }

                    $area_param = array();
                    $area_param['type'] = 3;
                    $area_param['order_id'] = $info['id'];
                    $area_param['parent_mid'] = $area_agent['city']['id'];
                    $area_param['cash'] = $area_cash;
                    $area_param['per'] = $area_per;

                    $area_param = Dever::array_encode($area_param);
                    $area_cash = '<a style="color:blue" class="set_cash" data-param="'.$area_param.'">' . $area_cash . '</a>';
                    $table['body'][] = array('间推佣金', $area_agent['city']['name'], $area_agent['city']['mobile'], $area_agent['city']['role']['name'], $area_agent['city']['level']['name'], $area_per . '%', $area_cash);
                }
            }
        }

        
    }

    private function show_parent_reward($parent_info, $info, $role, $v, $parent_role, $parent_level, $child_num, &$table)
    {
        $parent_name = '邀请人：'.$parent_info['name'].'，'.$parent_info['mobile'].'&nbsp;&nbsp;邀请人角色：';

        $order_cash = Dever::db('agent/order_cash')->getData(array('order_id' => $info['id'], 'parent_mid' => $v['uid'], 'type' => 1));
        //$parent_name .= $parent_role['name'] . '（'.$parent_level['name'].'）';
        # 根据角色获取佣金 直推
        if (!$order_cash) {
            $reward = Dever::db('setting/role_reward')->find(array('role_id' => $parent_info['role'], 't_role_id' => $info['role']));
            if ($reward) {
                $param = array();
                $param['type'] = 1;
                $param['order_id'] = $info['id'];
                $param['parent_mid'] = $parent_info['id'];
                $param['cash'] = 0;
                $param['per'] = 0;

                # 判断上级的等级，仅限区县和城市代理
                if ($parent_role && $parent_role['type'] == 2 && $parent_role['area'] <= 2) {
                    if (strstr($parent_info['area'], '-1')) {
                        $parent_info['area'] = str_replace(',-1', '', $parent_info['area']);
                    }
                    if (strstr($info['area'], $parent_info['area'])) {
                        # 区域内
                        if ($reward['zt_qn_value'] && $reward['zt_qn_value'] > 0) {
                            $reward['value'] = $reward['zt_qn_value'];
                        }
                    } else {
                        # 区域外
                        if ($reward['zt_qw_value'] && $reward['zt_qw_value'] > 0) {
                            $reward['value'] = $reward['zt_qw_value'];
                        }
                    }
                }

                # 检测有没有名额，如果有，直接使用名额内的佣金比例和权益
                if ($role['type'] == 1) {
                    $parent_goods = Dever::db('agent/member_goods')->getAll(array('mid' => $v['uid'], 'type' => 3));
                    if ($parent_goods) {
                        foreach ($parent_goods as $vg) {
                            if ($vg['num'] > 0) {
                                $parent_prize = Dever::db('setting/prize')->find($vg['type_id']);
                                if ($parent_prize && $parent_prize['type'] == 2 && $parent_prize['role'] == $role['id']) {
                                    $reward['value'] = $parent_prize['per'];
                                    $param['parent_goods_id'] = $vg['id'];
                                    $param['prize_type'] = 2;

                                    # 检测有没有名额权益
                                    $prize_goods = Dever::db('setting/prize_goods')->select(array('prize_id' => $parent_prize['id']));
                                    if ($prize_goods) {
                                        foreach ($prize_goods as $pk => $pv) {
                                            $param['goods'][] = $pv;
                                        }
                                    }

                                    break;
                                }
                            }
                        }
                    }
                }

                $reward_state = false;
                if ($reward['num'] == 1) {
                    # 每推荐1个，获取直推佣金
                    $reward_state = true;
                } elseif ($reward['num'] > 1) {
                    # 每推荐多少个，获取直推佣金
                    /*
                    if (!$child_num) {
                        $child_num = Dever::load('invite/api')->getChildNum($v['uid'], 1);
                    }*/
                    $child_num = Dever::db('agent/member')->total(array('parent_mid' => $v['uid'], 'role' => $info['role'], 'status' => 2)) + 1;
                    //$child_num = Dever::db('agent/member')->getCountByRole(array('parent_mid' => $v['uid'], 'role' => $info['role'])) + 1;
                    if ($child_num >= $reward['num'] && $child_num % $reward['num'] == 0) {
                        $reward_state = true;
                    }
                }

                if ($reward_state) {
                    if ($reward['value_type'] == 1) {
                        $param['cash'] = round($info['agent_cash'] * ($reward['value']/100), 2);
                        $param['per'] = $reward['value'];
                    } else {
                        $param['cash'] = $reward['value'];
                        $param['per'] = 0;
                    }
                }

                # 额外赠送
                $give = Dever::db('setting/role_reward_give')->getData(array('reward_id' => $reward['id']));
                if ($give) {
                    if (!$child_num) {
                        $child_num = Dever::load('invite/api')->getChildNum($v['uid'], 1);
                    }
                    foreach ($give as $gv) {
                        if ($child_num == $gv['num']) {
                            $prize_goods = Dever::db('setting/prize_goods')->select(array('reward_give_id' => $gv['id']));
                            if ($prize_goods) {
                                foreach ($prize_goods as $pk => $pv) {
                                    $param['goods'][] = $pv;
                                }
                            }
                            break;
                        }
                    }
                }
                /*
                if ($reward['is_give'] == 1) {
                    $give = Dever::array_decode($reward['give']);
                    if (!$child_num) {
                        $child_num = Dever::load('invite/api')->getChildNum($v['uid'], 1);
                    }
                    foreach ($give as $gv) {
                        if (isset($gv['num']) && $child_num >= $gv['num'] && $child_num % $gv['num'] == 0) {
                            $prize_log = Dever::db('agent/member_prize')->find(array('mid' => $v['uid'], 'prize_id' => $gv['type'], 'child_num' => $child_num));
                            if (!$prize_log) {
                                $prize = Dever::db('setting/prize')->find($gv['type']);
                                $param['prize_id'] = $prize['id'];
                                $param['child_num'] = $child_num;
                                break;
                            }
                        }
                    }
                }*/

                # 自动升级
                if (!$parent_info['group_sell']) {
                    $parent_info['group_sell'] = 0;
                }
                $group_sell = $parent_info['group_sell'] + $info['agent_cash'];
                if (!$child_num) {
                    $child_num = Dever::load('invite/api')->getChildNum($v['uid'], 1);
                }
                $role_up = Dever::db('setting/role_up')->getData(array('role_id' => $parent_role['id']));
                if ($role_up) {
                    foreach ($role_up as $rv) {
                        if ($child_num >= $rv['num'] && $group_sell >= ($rv['sell']*10000)) {
                            # 可以升级为新角色
                            $rv_role = Dever::db('setting/role')->find($rv['t_role_id']);
                            if ($rv_role) {
                                $param['role_up'] = $rv;
                                $parent_role['name'] = $parent_role['name'] . '->' . $rv_role['name'];
                                break;
                            }
                        }
                    }
                }

                if ($param['cash'] >= 0) {
                    $data_param = Dever::array_encode($param);
                    $param['cash'] = '<a style="color:blue" class="set_cash" data-param="'.$data_param.'">' . $param['cash'] . '</a>';
                } else {
                    unset($param['goods']);
                }
                $table['body'][] = array('直推佣金', $parent_info['name'], $parent_info['mobile'], $parent_role['name'], $parent_level['name'], $param['per'] . '%', $param['cash']);
            }
        } else {
            $order_cash['cash'] = '<a style="color:blue">' . $order_cash['cash'] . '</a>';
            
            $table['body'][] = array('直推佣金', $parent_info['name'], $parent_info['mobile'], $parent_role['name'], $parent_level['name'], $order_cash['per'] . '%', $order_cash['cash']);

            if ($order_cash['prize_id'] && $order_cash['prize_id'] > 0) {
                $prize = Dever::db('setting/prize')->find($order_cash['prize_id']);
            }

            if ($order_cash['goods'] && $order_cash['goods']) {
                $param['goods'] = Dever::array_decode($order_cash['goods']);
            }
        }

        /*
        if (isset($prize) && $prize) {
            $table['body'][] = array('赠送名额', $parent_info['name'], $parent_info['mobile'], $parent_role['name'], $parent_level['name'], '1', $prize['name']);
        }
        */
        if (isset($param['goods'])) {
            foreach ($param['goods'] as $pv) {
                if ($pv['type'] == 1) {
                    $goods_info = Dever::load('goods/lib/info')->getInfoBySku($pv['type_id'], $pv['sku_id']);
                    if (isset($goods_info['sku'])) {
                        $sku = '-' . $goods_info['sku']['string'];
                    } else {
                        $sku = '';
                    }
                    $pv['name'] = '<a style="color:blue">' . $goods_info['name'] . $sku . '</a>';
                } elseif ($pv['type'] == 2) {
                    $card = Dever::db('card/info')->find($pv['type_id']);
                    if ($card['create_type'] == 3) {
                        $pv['price'] = round($info['value']*($pv['num']/100), 2);
                        $pv['num'] = $pv['num'] . '%';
                    } else {
                        $pv['price'] = $card['value'] * $pv['num'];
                    }
                    
                    $pv['name'] = '<a style="color:blue">' . $pv['price'] . '元' . $card['name'] . '</a>';
                    
                }
                $table['body'][] = array('赠送权益', $parent_info['name'], $parent_info['mobile'], $parent_role['name'], $parent_level['name'], $pv['num'], $pv['name']);
            }
        }

        return $parent_name;
    }

    private function show_goods($process, $info, $role, &$result)
    {
        $t = intval($info['agent_cash']/10000);
        if ($t <= 0) {
            $t = 1;
        }
        $goods = Dever::db('agent/order_goods')->getData(array('order_id' => $info['id']));
        if (!$goods) {
            $goods = Dever::db('setting/role_goods')->getData(array('role_id' => $info['role'], 'give' => $info['order_type']));
        } else {
            $t = 1;
        }
        $process_button = array();
        if (isset($process[3]['type']) && is_array($process[3]['type']) && in_array(2, $process[3]['type'])) {
            $process_status = 1;
            $process_title = '（已发放权益）';
        } else {
            $process_status = 2;
            $process_title = '（未发放权益）';
            
             if (Dever::load('manage/auth')->checkFunc('agent.order', 'edit6', '修改权益')) {
                $process_button[] = array(
                    'type' => 'link',
                    'link' => Dever::url('lib/order_set.home?type='.$info['order_type'].'&order_id='.$info['id'].'&role_id=' . $info['role'] . '&total=' . $t, 'agent'),
                    'name' => '修改权益'
                );
            }
            if (Dever::load('manage/auth')->checkFunc('agent.order', 'edit7', '确认发放权益')) {
                $process_button[] = array(
                    'type' => 'action',
                    'link' => Dever::url('lib/manage.set_commit?json=1&type=2&order_id='.$info['id'], 'agent'),
                    'name' => '确认发放权益'
                );
            }
        }
        
        if ($goods) {
            $table = array();
            $table['head'] = array('权益类型', '权益名称', '权益价值', '数量/百分比');
            $table['body'] = array();
            
            foreach ($goods as $k => $v) {
                if ($v['type'] == 1) {
                    $goods_info = Dever::load('goods/lib/info')->getInfoBySku($v['type_id'], $v['sku_id']);
                    if (isset($goods_info['sku'])) {
                        $sku = '-' . $goods_info['sku']['string'];
                    } else {
                        $sku = '';
                    }
                    $v['num'] = $v['num'] * $t;
                    $table['body'][] = array('商品', $goods_info['name'] . $sku, $goods_info['price'], $v['num']);
                } elseif ($v['type'] == 2) {
                    $card = Dever::db('card/info')->find($v['type_id']);
                    if ($card['create_type'] == 3) {
                        $card['value'] = round($info['agent_cash']*($v['num']/100), 2);
                        $v['num'] = $v['num'] . '%';
                    } else {
                        $v['num'] = $v['num'] * $t;
                        $card['value'] = $card['value'] * $v['num'];
                    }
                    
                    $table['body'][] = array('电子券', $card['name'], $card['value'], $v['num']);
                } elseif ($v['type'] == 3) {
                    $prize = Dever::db('setting/prize')->find($v['type_id']);
                    $v['num'] = $v['num'] * $t;
                    if ($role['max_me_num'] && $role['max_me_num'] < $v['num']) {
                        $v['num'] = $role['max_me_num'];
                    }
                    $table['body'][] = array('名额', $prize['name'], $prize['price'], $v['num']);
                }
            }

            $result['权益信息' . $process_title] = array
            (
                'type' => 'table',
                'head' => array('name' => '权益列表：', 'btn' => $process_button),
                'content' => $table,
            );
        }
    }

    # 合同
    private function show_agreement($process, $info, $role, $sign_pic, &$result)
    {
        $table = array();
        $table['head'] = array('合同类型', '合同名称', '合同签名', '合同状态');
        $table['body'] = array();
        $agreement_type = Dever::db('setting/agreement')->config['config_type'];
        $agreement_status = Dever::db('agent/member_agreement')->config['status'];
        $agreement_button = array();
        if ((isset($process[3]['type']) && is_array($process[3]['type']) && in_array(5, $process[3]['type'])) || $info['import'] > 1) {
            $agreement_title = '（已生成合同）';
            
            $agreement = Dever::db('agent/member_agreement')->getData(array('order_id' => $info['id']));
            if ($agreement) {
                foreach ($agreement as $k => $v) {
                    $agreement_info = Dever::db('setting/agreement')->find($v['agreement_id']);
                    $agreement_status_name = Dever::status($agreement_status, $v['status']);

                    $table['body'][] = array(Dever::status($agreement_type, $agreement_info['type']), Dever::load('agent/lib/agreement')->name($agreement_info, $v, $role, 2), $sign_pic, $agreement_status_name);
                }
            } else {
                $agreement_title = '';
            }
        } else {
            $agreement_title = '（未生成合同）';
            
            if (Dever::load('manage/auth')->checkFunc('agent.order', 'edit8', '生成代理合同')) {
                $agreement_button[] = array(
                    'type' => 'action',
                    'link' => Dever::url('lib/manage.set_commit?json=1&type=5&order_id='.$info['id'], 'agent'),
                    'name' => '生成代理合同'
                );
            }

            $agreement = Dever::db('setting/agreement')->getData();
            $agreement_status_name = Dever::status($agreement_status, 1);
            $table['body'][] = array(Dever::status($agreement_type, $agreement[1]['type']), Dever::load('agent/lib/agreement')->name($agreement[1], $info, $role, 1), $sign_pic, $agreement_status_name);
            if ($info['soft_cash'] && $info['soft_cash'] > 0) {
                $table['body'][] = array($agreement_type[$agreement[3]['type']], Dever::load('agent/lib/agreement')->name($agreement[3], $info, $role, 1), $sign_pic, $agreement_status_name);
            }
            
            if ($info['order_type'] == 2) {
                # 升级的话，增加解除合同
                $table['body'][] = array(Dever::status($agreement_type, $agreement[2]['type']), Dever::load('agent/lib/agreement')->name($agreement[2], $info, $role, 1), $sign_pic, $agreement_status_name);
            } else {
                $table['body'][] = array(Dever::status($agreement_type, $agreement[4]['type']), Dever::load('agent/lib/agreement')->name($agreement[4], $info, $role, 1), $sign_pic, $agreement_status_name);
            }
        }

        $result['代理合同' . $agreement_title] = array
        (
            'type' => 'table',
            'head' => array('name' => '&nbsp;', 'btn' => $agreement_button),
            'content' => $table
        );
    }
    public function set_cdate($id){
        $info=Dever::db('agent/order')->one(array('id'=>$id,'state'=>1));
        if($info['cdate']){
            $data['注册']=date('Y-m-d H:i',$info['cdate']);
        }else{
             $data['注册']='-';
        }
        $order_process=Dever::db('agent/order_process')->one(array('status'=>1,'order_id'=>$info['id'],'state'=>1));
        if($order_process && $order_process['cdate']){
            $data['初审']=date('Y-m-d H:i',$order_process['cdate']);
        }else{
            $data['初审']='-';
        }
        
        $order_process=Dever::db('agent/order_process')->one(array('status'=>2,'order_id'=>$info['id'],'state'=>1));
        if($order_process && $order_process['cdate']){
            $data['终审']=date('Y-m-d H:i',$order_process['cdate']);
        }else{
            $data['终审']='-';
        }
        if($info['fdate']){
            $data['完成']=date('Y-m-d H:i',$info['fdate']);
        }else{
            $data['完成']='-';
        }
        $html = $data['注册'];
        $html .= '<br />' . $data['初审'];
        $html .= '<br />' . $data['终审'];
        $html .= '<br />' . $data['完成'];
        return $html;
        // '注册时间：'.$zhuce.'<br/>初审时间：'.$chushen.'<br/>终审时间：'.$zhongshen.'<br/>完成时间：'.$wancheng;
    }
    public function set_price($id){
        $info=Dever::db('agent/order')->one(array('id'=>$id,'state'=>1));
        $html = $info['f_price'];
        $html .= '<br />' . $info['price'];
        $html .= '<br />' . $info['agent_cash'];
        $html .= '<br />' . $info['soft_cash'];
        return $html;
        $data['注册金额']=$info['f_price'];
        $data['实付金额']=$info['price'];
        $data['代理费']=$info['agent_cash'];
        $data['软件服务费']=$info['soft_cash'];
        $html=Dever::table($data);
        return $html;
    }
    public function new_set($id){
        $info = Dever::db('agent/order')->find($id);
        $name = Dever::load("agent/lib/member.getOne", $id, "agent/order");
        $area = Dever::load("area/api.string", $info['area']);
        $html = $name.'<br/>'.$area;
        return $html;
    }
    #订单导出
    public function out_order($data){
        $header = array('邀请码', '姓名', '手机号', '身份证号', '会员角色', '代理商区域', '注册金额', '代理费', '直推业绩', '团队业绩', '申请类型','公司名称','申请时间', '初审时间','初审人','终审时间','终审人','审核状态','分润发放时间','分润发放人','权益发放时间','权益发放人','管理员备注','推荐人姓名','推荐人电话','推荐人等级','推荐人代理地区');
        
        $body = array();
        foreach($data as $k => $v){
            $config = Dever::db('agent/order')->config['set'];
            $status = Dever::status($config['status'], $v['status']);
            $member = Dever::db('agent/member')->find(array('id'=>$v['mid']));
            $code = Dever::load("invite/api.code", $member['id']);
            if($member['type'] == 1){
                $member_type = '个人';
            }else{
                $member_type = '公司';
            }
            $role = Dever::db('setting/role')->find(array('id'=>$v['role']));
            $area = Dever::load("area/api.string", $v['area']);
            
            $parent = Dever::db('agent/member')->find(array('id'=>$v['parent_mid']));
            $parent_rolename = '';
            $parent_name = '';
            $parent_mobile = '';
            $parent_area = '';
            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['area']){
                    $parent_area = Dever::load("area/api.string", $parent['area']);
                }
                if($parent['name']){
                    $parent_name = $parent['name'];
                }
                if($parent['mobile']){
                    $parent_mobile = $parent['mobile'];
                }
            }
            
            $process = Dever::db('agent/order_process')->state(array('order_id'=>$v['id']));
            $chu = '';
            $zhong = '';
            $qy = '';
            $fr = '';
            $bh = '';
            $chushen = '';
            $zhongshen = '';
            $audit_cdate = '';

            $member_goods_log = Dever::db('agent/member_goods_log')->find(array('parent_order_num'=>$v['order_num']));
            if($member_goods_log){
                $quanyi = Dever::load('manage/api')->getLog($member_goods_log['id'], 'agent', 'member_goods_log', 1);
                if($quanyi){
                    $admin = Dever::load('manage/admin-find',$quanyi['admin']);
                    if($admin){
                        $qy = $admin['username'];
                    }
                } 
            }
            
            $qydate = '';
            $member_goods = Dever::db('agent/member_goods')->getQone(array('mid'=>$v['mid'],'state'=>1));
            if($member_goods && $member_goods['cdate']){
                $qydate = date('Y-m-d H:i',$member_goods['cdate']);
            }
            
            $order_cash = Dever::db('agent/order_cash')->find(array('order_id'=>$v['id']));
            if($order_cash && $order_cash['id']){
                $fenrun = Dever::load('manage/api')->getLog($order_cash['id'], 'agent', 'order_cash', 1);
                 if($fenrun && $fenrun['admin']){
                    $admin = Dever::load('manage/admin-find',$fenrun['admin']);
                    if($admin){
                        $fr = $admin['username'];
                    }
                }
            }
            
            $frdate = '';
            if($order_cash && $order_cash['cdate']){
                $frdate = date('Y-m-d H:i',$order_cash['cdate']);
            }
            if($process){
                foreach($process as $key => $val){
                    $log = Dever::load('manage/api')->getLog($val['id'], 'agent', 'order_process', 1);
                    if($val['status'] == 1){
                        if($val && $val['admin']){
                            $admin = Dever::load('manage/admin-find',$val['admin']);
                            $chu = $admin['username'];
                        }elseif($log && $log['admin']){
                            $admin = Dever::load('manage/admin-find',$log['admin']);
                            $chu = $admin['username'];
                        }
                        $chushen = date('Y-m-d H:i',$val['cdate']);
                        
                    }elseif($val['status'] == 2){
                        $zhongshen = date('Y-m-d H:i',$val['cdate']);
                        if($val && $val['admin']){
                            $admin = Dever::load('manage/admin-find',$val['admin']);
                            $zhong  = $admin['username'];
                        }elseif($log && $log['admin']){
                            $admin = Dever::load('manage/admin-find',$log['admin']);
                            $zhong  = $admin['username'];
                        }
                    }
                }
            }
            $d = array
            (
                $code,
                $member['name'],
                $member['mobile'],
                $member['idcard'],
                $role['name'],
                $area,
                $v['f_price'],
                $v['agent_cash'],
                $member['sell'],
                $member['group_sell'],
                $member_type,
                $v['company_name'],
                date('Y-m-d H:i',$v['cdate']),
                $chushen,
                $chu,
                $zhongshen,
                $zhong,
                $status,
                $frdate,
                $fr,
                $qydate,
                $qy,
                $v['admin_desc'],
                $parent_name,
                $parent_mobile,
                $parent_rolename,
                $parent_area,
            );
            $body[] = $d;
        }
        $file = Dever::input('excel_name');;
        return Dever::excelExport($body, $header, $file);
        
    }
    public function getArea($id){
        $info = Dever::db('agent/order')->find($id);
        if($info['area']){
            $area = Dever::load("area/api.string", $info['area']);
        }else{
            $area = '';
        }
        return $area;
    }
    #软件服务费导出
    public function out_softorder($data){
        $header = array('合同乙方', '手机号码', '合同总期数（年）', '合同类型', '签订日期', '合同金额', '购买日期', '录入日期', '终审日期');

        $body = array();
        foreach($data as $k => $v){
            if($v['soft_cash'] && $v['soft_cash']>0){
                $role = Dever::db('setting/role')->find($v['role']);
                $type = 2;
                # 这里加判断
                if ($role['type'] == 2 && $role['area'] == 1) {
                    $type = 1;   
                } elseif ($v['soft_cash'] > 6000 && $v['soft_cash'] <= 30000 && $v['soft_cash']%5000 == 0) {
                    $type = 3;
                } elseif ($v['soft_cash'] <= 6000 && $v['soft_cash']%1000 == 0) {
                    $type = 4;
                } else {
                    $type = 2;
                }
                # 城市代理
                if ($type == 1) {
                    $name = '城市代理版';
                    $year = 1;
                }
                # 定制版
                elseif ($type == 2) {
                    $name = '定制版';
                    $year = 1;
                }
                # 升级版
                elseif ($type == 3) {
                    $name = '升级版';
                    $year = intval($v['soft_cash']/5000);
                    if ($year > 6) {
                        $year = 6;
                    }
                }
                # 基础版
                else {
                    $name = '基础版';
                    $year = intval($v['soft_cash']/1000);
                    if ($year > 6) {
                        $year = 6;
                    }
                }
                if($v['cdate']){
                    $cdate = date('Y-m-d H:i',$v['cdate']);
                }else{
                     $cdate = '-';
                }
                $order_process = Dever::db('agent/order_process')->one(array('status'=>1,'order_id'=>$v['id'],'state'=>1));
                if($order_process && $order_process['cdate']){
                    $chu_cdate = date('Y-m-d H:i',$order_process['cdate']);
                }else{
                     $chu_cdate = '-';
                }
                
                $order_process = Dever::db('agent/order_process')->one(array('status'=>2,'order_id'=>$v['id'],'state'=>1));
                if($order_process && $order_process['cdate']){
                    $zcdate = date('Y-m-d H:i',$order_process['cdate']);
                }else{
                    $zcdate = '-';
                }

                $d = array
                (
                    $v['name'],
                    $v['mobile'],
                    $year,
                    $name,
                    $zcdate,
                    $v['soft_cash'],
                    $cdate,
                    $cdate,
                    $zcdate,
                );

               $body[] = $d;
            }
        }
        $file = Dever::input('excel_name');
        return Dever::excelExport($body, $header, $file);
    }
    public function out_beidiaoorder($data){

        $db = Dever::db('agent/test:old');

        $header = array('姓名', '手机号', '身份证号', '注册日期', '角色', '代理金额', '直推奖励合计');

        $month_config = array('2021-08', '2021-09', '2021-10', '2021-11','2021-12', '2022-01', '2022-02', '2022-03', '2022-04','2022-05','2022-06');

        $header = array_merge($header, $month_config);

        $body = array();
        foreach($data as $k => $v){
            $cdate = '';
            if($v['cdate']){
                $cdate = date('Y-m-d H:i',$v['cdate']);
            }
            $role_name = '';
            if($v['role']){
                $role = Dever::db('setting/role')->find($v['role']);
                if($role && $role['name']){
                    $role_name = $role['name'];
                }
            }
            $cash = 0;

            $month_cash = array();
            $month = array();

            $bill = Dever::db('bill/cash')->select(array('mid' => $v['mid'], 'type' => 1));
            if ($bill) {
                foreach ($bill as $k1 => $v1) {
                    $time = date('Y-m', $v1['cdate']);
                    if (!isset($month[$time])) {
                        $month[$time] = 0;
                    }
                    $month[$time] += $v1['cash'];
                    $cash += $v1['cash'];
                }
            }

            if ($v['mid'] < 50000) {
                $member = $db->fetch('select * from ims_ewei_shop_member where id = ' . $v['mid'] . '');
                if ($member) {
                    if ($member['uid'] && $member['uid'] > 0) {
                        $record = $db->fetchAll('select * from `ims_ewei_shop_member_credit_record` where uid = '.$member['uid'].' and `remark` LIKE "%推荐%" and credittype = "credit2"');
                    } elseif ($member['openid']) {
                        $record = $db->fetchAll('select * from `ims_ewei_shop_member_credit_record` where `remark` LIKE "%推荐%" and `remark` LIKE "%'.$member['openid'].'%" and credittype = "credit2"');
                    }
                    if (isset($record) && $record) {
                        foreach ($record as $k1 => $v1) {
                            $time = date('Y-m', $v1['createtime']);
                            if (!isset($month[$time])) {
                                $month[$time] = 0;
                            }
                            $month[$time] += $v1['num'];
                            $cash += $v1['num'];
                        }
                    }
                }
            }

            if (!$cash) {
                $cash = 0;
            }
            
            $d = array
            (
                $v['name'],
                $v['mobile'],
                $v['idcard'],
                $cdate,
                $role_name,
                $v['agent_cash'],
                $cash,
            );

            foreach ($month_config as $k2 => $v2) {
                if (isset($month[$v2]) && $month[$v2]) {
                    $d[] = $month[$v2];
                } else {
                    $d[] = 0;
                }
            }
            
            $body[] = $d;
        }
        $file = Dever::input('excel_name');
        $test = Dever::input('test');
        if ($test == 1) {
            print_r($body);die;
        }
        return Dever::excelExport($body, $header, $file);
    }

    # 修改区域
    public function editArea($member, $area)
    {
        $order = Dever::db('agent/order')->find(array('mid' => $member['id'], 'role' => $member['role']));
        if ($order && $order['area'] != $area) {
            Dever::db('agent/order')->update(array('where_id' => $order['id'], 'area' => $area));
        }
    }
}