<?php
namespace Mail\Lib;

use Dever;

class Manage
{
    public function getAreaInfo($data, $name, $param)
    {
        $manage = array();
        $month = Dever::param('month', $param);
        if ($data) {
            $delete = array('一键生成区域分润');
            foreach ($data as $k => $v) {
                if ($v['cash_status'] == 1) {
                    # 已发放
                    $delete[] = '对账确认';
                    $delete[] = '确认发放';
                    $delete[] = '重新生成区域分润';
                    break;
                } else {
                    if ($v['status'] == 1) {
                        # 已确认
                        $delete[] = '对账确认';
                        $delete[] = '重新生成区域分润';
                    } else {
                        $delete[] = '确认发放';
                    }
                }
            }
            $log = Dever::db('mail/area_stat_log')->find(array('month' => $month));
            if ($log) {
                $audit = array();
                if ($log['create_admin']) {
                    $admin = Dever::db('manage/admin')->find($log['create_admin']);
                    if ($admin) {
                        $date = date('Y-m-d H:i', $log['create_date']);
                        $audit[] = '创建人：' . $admin['username'] . ' 创建时间：' . $date;
                    }
                }
                if ($log['confirm_admin']) {
                    $admin = Dever::db('manage/admin')->find($log['confirm_admin']);
                    if ($admin) {
                        $date = date('Y-m-d H:i', $log['confirm_date']);
                        $audit[] = '对账人：' . $admin['username'] . ' 对账时间：' . $date;
                    }
                }
                if ($log['send_admin']) {
                    $admin = Dever::db('manage/admin')->find($log['send_admin']);
                    if ($admin) {
                        $date = date('Y-m-d H:i', $log['send_date']);
                        $audit[] = '发放人：' . $admin['username'] . ' 发放时间：' . $date;
                    }
                }
                if ($audit) {
                    $audit = '<br />' . implode('&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;', $audit);
                } else {
                    $audit = '';
                }
                
                $manage['info'] = date('Y年m月', $month) . ' 可分润城市 ' . $log['city_num'] . ' 个 分润区县 ' . $log['county_num'] . ' 个 分润街道 ' . $log['town_num'] . ' 个（不含赠送区域） ' . $audit;

            }
            
            $manage['deleteButton'] = $delete;
        } else {
            Dever::setInput('day', Dever::input('search_option_month'));
            list($start, $end) = Dever::month();
            $tiyan = Dever::db('shop/info')->total(array('status' => 1, 'type' => 1, 'end' => $end));
            $lingshou = Dever::db('shop/info')->total(array('status' => 1, 'type' => 2, 'end' => $end));
            $total = $tiyan + $lingshou;
            $manage['info'] = date('Y年m月', $month) . ' 共有店铺 ' . $total . ' 家 体验店 ' . $tiyan . ' 家 零售店 ' . $lingshou . ' 家';
            $manage['desc'] = '';
            $manage['deleteButton'] = array('重新生成区域分润', '对账确认', '确认发放');
        }
        Dever::config('base')->manage = $manage;
    }

    public function getArea($name)
    {
        if (strstr($name, '|—')) {
            $temp = explode('|—', $name);
            return $temp[0] . '|—' . Dever::load("area/api.string", $temp[1], '-');
        } else {
            return Dever::load("area/api.string", $name, '-');
        }
    }

	#代理商日数据统计
	public function day_api(){
        $day = Dever::input('day');
        if($day){
            $start = strtotime($day);
            $end = $start+86400-1;
        }else{
            $start=mktime(0,0,0,date('m'),date('d'),date('Y'));
            $end = $start+86400-1;
        }
        
        $time = Dever::maketime(date('Y-m-d'),'00:00:00');
        $where = array();
        $where['fstart'] = $start;
        $where['fend'] = $end;
        $w = array();
        $fstart = Dever::input('start', date('Y-m-01', $start));
        $w['fstart'] = Dever::maketime($fstart . ' 00:00:00');
        $w['fend'] = strtotime(date('Y-m-d 23:59:59',
                strtotime($fstart."+1 month - 1 day")));;
        $data = array();
        $data['start'] = date('Y-m-d',$start);
        $data['day'] = $this->content_api($where,1);
        $data['money'] = $this->c_api($where);
        $data['week'] = $this->zhou_api($start);
        $data['all'] = $this->content_api($w,2);
        $data['all_money'] = $this->c_api($w);
        $data['time'] = $this->day_time_api($w);
        $data['data'] = Dever::json_encode($data['time']);
        $data['money_time'] = $this->money_time_api($w);
        $data['qu_money'] = Dever::json_encode($data['money_time']);
        $data['xzhou'] = $this->button_day_api($w,1);
        $data['zhou'] = Dever::json_encode($data['xzhou']);
        
        return Dever::render('census', $data);
	}

    public function zhou_api($time='',$format="Y-m-d"){
        $time = $time != '' ? $time : time();
        $week = date('w', $time);
        $date = [];
        if($week == 0){
            $week = 7;
        }
        for ($i=1; $i<=7; $i++){
            $date[$i] = date($format ,strtotime( '+' . $i-$week .' days', $time));
        }
        $start = strtotime($date[1]);
        $end = strtotime($date[7])+86400-1;
        $where = array();
        $where['fstart'] = $start;
        $where['fend'] = $end;
        $data = array();
        $data['week'] = date('Y.m.d',$start).' - '.date('Y.m.d',$end);
        $data['all'] = $this->content_api($where,2);
        $data['all_money'] = $this->c_api($where);
        return $data;
    }
    #按时间统计
	public function content_api($where,$type){
		$data = array();
        if($type == 2){
            $data['time'] = date('Y.m',$where['fstart']);
        }elseif($type == 1){
            $data['time'] = date('Y.m.d',$where['fstart']);
        }
        #确认代理商订单数
        $where['status'] = 4;
        $data['num'] = Dever::db('agent/order')->getNum($where);
        #确认订单总费用
        $money = Dever::db('agent/order')->getCash($where);
        if($money['total']){
        	$data['money'] = $money['total'];
        }else{
        	$data['money'] = 0;
        }
        #确认代理费
        $dl_money = Dever::db('agent/order')->getDailiCash($where);
        if($dl_money['total']){
            $data['dl_money'] = $dl_money['total'];
        }else{
            $data['dl_money'] = 0;
        }
        #确认软件服务费
        $soft_money = Dever::db('agent/order')->getSoftCash($where);
        if($soft_money['total']){
            $data['soft_money'] = $soft_money['total'];
        }else{
            $data['soft_money'] = 0;
        }
        $wh['status'] = 3;
        $wh['fstart'] = $where['fstart'];
        $wh['fend'] = $where['fend'];
        $cash = Dever::db('agent/soft_cash')->getTotal($wh);
        if($cash['total']){
            $data['cash'] = $cash['total'];
        }else{
            $data['cash'] = 0;
        }
        $data['soft_cash'] = $data['soft_money'] + $data['cash'];

        #期权价值
        $option_money = Dever::db('agent/order')->getOptionPrice($where);
        if($option_money['total']){
            $data['option_money'] = $option_money['total'];
        }else{
            $data['option_money'] = 0;
        }
        return $data;
    }
    #各角色的金额，数量，原始期权价值，软件服务费
    public function c_api($where){
        $role = Dever::db('setting/role')->getAll(array('id'=>1,'state'=>1));
        foreach($role as $k => $v){
            $where['role'] = $v['id'];
            $data[$k]['name'] = $v['name'];
            $where['status'] = 4;
            $data[$k]['num'] = Dever::db('agent/order')->getNum($where);
            // $where['status'] = 4;
            $dl = Dever::db('agent/order')->getSum($where);
            if($dl['total']){
                $data[$k]['money'] = $dl['total'];
            }else{
                $data[$k]['money'] = 0;
            }
            #期权价值：
            $option_money = Dever::db('agent/order')->getOptionPrice($where);
            if($option_money['total']){
                $data[$k]['option_money'] = $option_money['total'];
            }else{
                $data[$k]['option_money'] = 0;
            }
            #软件服务费
            $soft_money = Dever::db('agent/order')->getSoftCash($where);
            if($soft_money['total']){
                $data[$k]['soft_money'] = $soft_money['total'];
            }else{
                $data[$k]['soft_money'] = 0;
            }
            $wh['role'] = $v['id'];
            $wh['status'] = 3;
            $wh['fstart'] = $where['fstart'];
            $wh['fend'] = $where['fend'];
            $cash = Dever::db('agent/soft_cash')->getTotal($wh);
            if($cash['total']){
                $data[$k]['cash'] = $cash['total'];
            }else{
                $data[$k]['cash'] = 0;
            }
        }
        return $data;
    }
    #数据趋势
    public function day_time_api($w){
        $time = date('m',time()) - date('m',$w['fstart']);
        $start = date('Y-m-01',$w['fstart']);
        if($time<=0){
            $w['fend'] = time();
        }elseif($time>0){
            $w['fend'] = strtotime(date('Y-m-d 23:59:59',
                strtotime($start."+1 month - 1 day")));
        }
      $days = ($w['fend']-$w['fstart'])/86400+1;
      // 保存每天日期
      $day = array();
      $data = array();
      for($i=0; $i<$days; $i++){
        $day[] =  array($w['fstart']+(86400*$i),$w['fstart']+(86400*$i)+86400);
      }
      $res = array();
      $res['num'] = array();
      foreach($day as $k => $v){
        $where['fstart'] = $v[0];
        $where['fend'] =$v[1]-1;
        $data[$k]['time'] = date('m.d',$v[0]);
        #确认代理商订单数
        $where['status'] = 4;
        $res['num'][] = Dever::db('agent/order')->getNum($where);
      }
      // print_R($where);die;
      $data = array();
      $data['name'] = '数量';
      $data['type'] = 'line';
      // $data['stack'] = 'Total';
      $data['data'] = $res['num'];
      return $data;
    }
    #金额趋势
    public function money_time_api($w){
        $time = date('m',time()) - date('m',$w['fstart']);
        $start = date('Y-m-01',$w['fstart']);
        if($time<=0){
            $w['fend'] = time();
        }elseif($time>0){
            $w['fend'] = strtotime(date('Y-m-d 23:59:59',
                strtotime($start."+1 month - 1 day")));
        }
      $days = ($w['fend']-$w['fstart'])/86400+1;
      // 保存每天日期
      $day = array();
      $data = array();
      for($i=0; $i<$days; $i++){
        $day[] =  array($w['fstart']+(86400*$i),$w['fstart']+(86400*$i)+86400);
      }
      $res = array();
      $res['money'] = array();
      foreach($day as $k => $v){
        $where['fstart'] = $v[0];
        $where['fend'] =$v[1]-1;
        $data[$k]['time'] = date('m.d',$v[0]);
        #确认订单总费用
        $money = Dever::db('agent/order')->getCash($where);
        if($money['total']){
            $res['money'][] = $money['total'];
        }else{
            $res['money'][] = 0;
        }
      }
      $money = array();
      $money['name'] = '金额';
      $money['type'] = 'line';
      $money['data'] = $res['money'];
      return $money;
    }
    #趋势底部日期
    public function button_day_api($w,$type){
        $time = date('m',time()) - date('m',$w['fstart']);
        $start = date('Y-m-01',$w['fstart']);
        if($time<=0){
            $w['fend'] = time();
        }elseif($time>0){
            $w['fend'] = strtotime(date('Y-m-d 23:59:59',
                strtotime($start."+1 month - 1 day")));
        }
        $days = ($w['fend']-$w['fstart'])/86400+1;
        if($type ==1){
            $daysd = $days-1;
        }else{
            $daysd = $days;
        }
      // 保存每天日期
      $day = array();
      $data = array();
      for($i=0; $i<$daysd; $i++){
        $day[] = date('m.d',$w['fstart']+(86400*$i));
      }
      $data['type'] = 'category';
      $data['boundaryGap'] = false;
      $data['date'] = $day;
      return $day;
    }
    #代理商日统计
    public function index_api(){
        $title = '代理商日数据统计';
        $data = Dever::db('mail/feature')->find(array('key'=>'lib/cron.day'));
        $email = explode(',',$data['email_id']);
        foreach($email as $k => $v){
            $res[] = Dever::db('mail/email')->find(array('id'=>$v));
        }
        $content = $this->index_api();
        foreach($res as $key => $val){
            $this->send($val['email'], $val['name'], $title, $content);
        }
    }
    
    #代理商统计发送邮件
    public function send($email, $username, $title, $content)
    {
        $config = Dever::config('base', 'project')->email;

        Dever::apply('src/PHPMailer', 'email');
        Dever::apply('src/Exception', 'email');
        Dever::apply('src/SMTP', 'email');
        $mail = new \PHPMailer\PHPMailer\PHPMailer();

        $mail->isSMTP();
        //$mail->SMTPDebug = 2;
        $mail->CharSet = 'UTF-8';
        $mail->Host = $config['smtp'];
        $mail->Port = 465;
        $mail->SMTPSecure = 'ssl';
        $mail->SMTPAuth = true;
        $mail->Username = $config['username'];
        $mail->Password = $config['password'];
        $mail->setFrom($config['from'][0], '统计');
        $mail->addAddress($email, $username);
        $mail->Subject = "=?utf-8?B?" . base64_encode($title) . "?=";
        $mail->Body = $content;
        $mail->isHTML(true);
        //$mail->addAttachment($file);
        if (!$mail->send()) {
            Dever::alert("Mailer Error: " . $mail->ErrorInfo);
        } else {
            return 'ok';
        }
    }
    #期权统计
    public function option_api(){
        #主账户数量
        $data['account'] = Dever::db('option/account')->getCount(array('state'=>1));
        #所有数量
        $data['member'] = Dever::db('option/member')->getCount(array('state'=>1));
        #已认证完成
        $data['y_num'] = Dever::db('option/account')->getCount(array('audit'=>3,'state'=>1));
        #尚未任何交付的
        $data['no_num'] = Dever::db('option/bill_jiaofu')->getCount(array('status'=>2,'state'=>1));
        #原始期权待交付
        $yq_nonum = Dever::db('option/bill_jiaofu')->getCash(array('status'=>2,'type'=>2,'state'=>1));
        if($yq_nonum['total']){
            $data['yq_nonum'] = $yq_nonum['total'];
        }else{
            $data['yq_nonum'] = 0;
        }
        
        #原始期权已交付未发放
        $yq_nof = Dever::db('option/bill_jiaofu')->getCash(array('status'=>1,'type'=>2,'state'=>1));
        
        if($yq_nof['total']){
            $data['yq_nof'] = $yq_nof['total'];
        }else{
            $data['yq_nof'] = 0;
        }
        #原始期权已发放
        $yq_fnum = Dever::db('option/bill_fafang')->getCash(array('status'=>1,'type'=>2,'state'=>1));
        if($yq_fnum['total']){
            $data['yq_fnum'] = $yq_fnum['total'];
        }else{
            $data['yq_fnum'] = 0;
        }
        
        #期权待交付
        $q_nonum = Dever::db('option/bill_jiaofu')->getCash(array('status'=>2,'type'=>1,'state'=>1));
        if($q_nonum['total']){
            $data['q_nonum'] = $q_nonum['total'];
        }else{
            $data['q_nonum'] = 0;
        }
        
        #期权已交付未发放
        $q_nof = Dever::db('option/bill_jiaofu')->getCash(array('status'=>1,'type'=>1,'state'=>1));
        if($q_nof['total']){
            $data['q_nof'] = $q_nof['total'];
        }else{
            $data['q_nof'] = 0;
        }
        
        #期权已发放
        $q_fnum = Dever::db('option/bill_fafang')->getCash(array('status'=>1,'type'=>1,'state'=>1));
        if($q_fnum['total']){
            $data['q_fnum'] = $q_fnum['total'];
        }else{
            $data['q_fnum'] = 0;
        }
        
        return Dever::render('qiquan', $data);
    }
    #代理商期权待交付	
    public function option_nopay_api($start,$end,$type=false){
        $start = Dever::input('start',$start);
        $end = Dever::input('end',$end);
        if($start && $end){
            $start = strtotime($start);
            $end = strtotime($end);
        }else{
            $start=Dever::maketime(date('Y-m-01') . ' 00:00:00');
            $end = strtotime(date('Y-m-d 23:59:59',
                strtotime(date('Y-m-01')."+1 month - 1 day")));
        }
        $where['start'] = $start;
        $where['end'] = $end;
        $where['state'] = 1;
        $rest = array();
        $rest['start'] = date('Y-m-d',$start);
        $rest['end'] = date('Y-m-d',$end);
        $rest['data'] = array();
        $data = Dever::db('agent/order')->getAll($where);
        if($data){
            foreach($data as $k => $v){
                #单独购买的软件服务费
                $cash = Dever::db('agent/soft_cash')->getTotal(array('fstart'=>$start,'fend'=>$end,'mid'=>$v['mid']));
                 $data[$k]['buy_cash'] = $cash['total'];
                 $option = Dever::db('agent/soft_cash')->getPrice(array('fstart'=>$start,'fend'=>$end,'mid'=>$v['mid']));
                 $data[$k]['y_price'] = $option['total'];
            }
            $rest['page'] = Dever::page("current");
            $rest['data'] = $data;
            if($type == 1){
                return $rest['data'];
            }else{
                return Dever::render('option_nopay', $rest);
            }
        }else{
            return Dever::render('option_nopay', $rest);
        }
        
        
    }
    #代理商期权待交付导出
    public function out_option_nopay_api(){
        $start = Dever::input('start');
        $end = Dever::input('end');
        if($start && $end){
            $start = strtotime($start);
            $end = strtotime($end);
        }else{
            $start=Dever::maketime(date('Y-m-01') . ' 00:00:00');
            $end = strtotime(date('Y-m-d 23:59:59',
                strtotime(date('Y-m-01')."+1 month - 1 day")));
        }
        $data = $this->option_nopay_api($start,$end,1);
        $header = array('用户姓名', '手机号', '身份证号', '软件服务费（订单）', '软件服务费（购买）', '原始期权', '期权赠送');
        if($data){
            $body = array();
            foreach($data as $k => $v){
                $d = array
                (
                    $v['name'],
                    $v['mobile'],
                    $v['idcard'],
                    $v['soft_cash'],
                    $v['buy_cash'],
                    $v['y_price'],
                    $v['option_price'],
                );
                $body[] = $d;
            }
            $file = '代理商期权待交付';
            Dever::excelExport($body, $header, $file);
        }
    }
    #代理商期权发放统计
    public function option_grant_api($start,$end,$type=false){
        $start = Dever::input('start',$start);
        $end = Dever::input('end',$end);
        if($start && $end){
            $start = strtotime($start);
            $end = strtotime($end);
        }else{
            $start=Dever::maketime(date('Y-m-01') . ' 00:00:00');
            $end = strtotime(date('Y-m-d 23:59:59',
                strtotime(date('Y-m-01')."+1 month - 1 day")));
        }
        $data = array();
        $data['start'] = date('Y-m-d',$start);
        $data['end'] = date('Y-m-d',$end);
        $res = Dever::db('agent/member')->getAll(array('start'=>$start,'end'=>$end,'state'=>1));
        foreach($res as $k=>$v){
            $role = Dever::db('setting/role')->find($v['role']);
            $res[$k]['role_name'] = $role['name'];
            $res[$k]['cv_num'] = Dever::db('agent/member')->getNum(array('parent_mid'=>$v['id'],'fstart'=>$start,'fend'=>$end,'role'=>8,'state'=>1));
            $res[$k]['ck_num'] = Dever::db('agent/member')->getNum(array('parent_mid'=>$v['id'],'fstart'=>$start,'fend'=>$end,'role'=>6,'state'=>1));
            $res[$k]['cash'] = Dever::db('bill/cash')->getCash(array('mid'=>$v['id'],'type'=>'1,2','state'=>1));
        }
        $data['page'] = Dever::page("current");
        $data['data'] = $res;
        if($type == 1){
            return $res;
        }else{
            return Dever::render('option_grant', $data);
        }
    }
    #期权发放导出
    public function out_option_grant_api(){
        $start = Dever::input('start');
        $end = Dever::input('end');
        if($start && $end){
            $start = strtotime($start);
            $end = strtotime($end);
        }else{
            $start=Dever::maketime(date('Y-m-01') . ' 00:00:00');
            $end = strtotime(date('Y-m-d 23:59:59',
                strtotime(date('Y-m-01')."+1 month - 1 day")));
        }
        $data = $this->option_grant_api($start,$end,1);
        $header = array('用户姓名', '手机号', '身份证号', '角色', '完成团队业绩', '完成直推创v', '完成直推创客');
        if($data){
            $body = array();
            foreach($data as $k => $v){
                $d = array
                (
                    $v['name'],
                    $v['mobile'],
                    $v['idcard'],
                    $v['role_name'],
                    $v['group_sell'],
                    $v['cv_num'],
                    $v['ck_num'],
                );
                $body[] = $d;
            }
            $file = '代理商期权发放';
            Dever::excelExport($body, $header, $file);
        }
    }
    #软件服务费数据统计
    public function soft_cash_api(){
        $start = Dever::input('start');
        $end = Dever::input('end');
        $where = array();
        if($start && $end){
            $where['fstart'] = strtotime($start.'00:00:00');
            $where['fend'] = strtotime($end.'23:59:59');
        }else{
            $where['fstart']=Dever::maketime(date('Y-m-01') . ' 00:00:00');
            $where['fend'] = strtotime(date('Y-m-d 23:59:59',
                strtotime(date('Y-m-01')."+1 month - 1 day")));
        }
        $where['state'] = 1;
        $data = array();
        $data['start'] = date('Y-m-d',$where['fstart']);
        $data['end'] = date('Y-m-d',$where['fend']);
        #软件服务费的已确认数量
        $where['soft_cash']=1;
        $where['status'] = 4;
        $order = Dever::db('agent/order')->getSoftNum($where);
        $where['status'] = 3;
        $soft_cash = Dever::db('agent/soft_cash')->getSoftNum($where);
        $data['num'] = $order + $soft_cash;
        #软件服务费未确认的数量
        $where['status'] = '-2,-1,1,2,3';
        $order = Dever::db('agent/order')->getSoftNoNum($where);
        $where['status'] = '1,2';
        $soft_cash = Dever::db('agent/soft_cash')->getSoftNoNum($where);
        $data['no_num'] = $order + $soft_cash;
        #总数量
        $data['total_num'] = $data['num'] + $data['no_num'];
        
        #已确认软件服务费
        $where['status'] = 4;
        $order = Dever::db('agent/order')->getSoftCash($where);
        $where['status'] = 3;
        $soft_cash = Dever::db('agent/soft_cash')->getSoftCash($where);
        $data['money'] = $order['total'] + $soft_cash['total'];
        #未确认软件服务费
        $where['status'] = '-2,-1,1,2,3';
        $order = Dever::db('agent/order')->getSoftNoCash($where);
        $where['status'] = '1,2';
        $soft_cash = Dever::db('agent/soft_cash')->getSoftNoCash($where);
        $data['no_money'] = $order['total'] + $soft_cash['total'];
        #总钱数
        $data['total_money'] = $data['money'] + $data['no_money'];
        #合同已确认数量：
        $where['status'] = 2;
        $data['a_num'] = Dever::db('agent/member_agreement')->getNum($where);
        #合同未确认数量：
        $where['status'] = 1;
        $data['a_nonum'] = Dever::db('agent/member_agreement')->getNoNum($where);
        $data['a_totalnum'] = $data['a_num'] + $data['a_nonum'];
        #合同已确认软件服务费
        $where['status'] = 2;
        $price = Dever::db('agent/member_agreement')->getPrice($where);
        if($price['total']){
            $data['a_price'] = $price['total'];
        }else{
            $data['a_price'] = 0;
        }
        
        #合同未确认软件服务费
        $where['status'] = 1;
        $noprice = Dever::db('agent/member_agreement')->getNoPrice($where);
        if($noprice['total']){
            $data['a_noprice'] = $noprice['total'];
        }else{
            $data['a_noprice'] = 0;
        }
        
        #总钱数
        $data['total_price'] = $data['a_price'] + $data['a_noprice'];
        return Dever::render('soft_cash', $data);
    }
    public function out_option_qiquan_api($data)
    {
        // print_R($data);die;
        $header = array('索引', '账户名称', '账户类型', '手机号', '身份证号', '邮箱', '邮箱认证', '账户认证', '合同审核状态','待交付期权', '待交付原始期权', '已交付期权', '已交付原始期权');
        // $data = Dever::db('option/member')->state();
        $body = array();
        $main = '';
        $f_money = 0;
        $j_money = 0;
        $dj_money = 0;
        $d_money = 0;
        $status = array();
        $set = Dever::db('option/account')->config['set'];
        $ag_audit = Dever::db('option/agreement')->config['audit'];
        foreach ($data as $k1 => $v1) {
            $member[$v1['id']] = Dever::db('option/member')->select(array('aid' => $v1['id']));
            $agreement = Dever::db('option/agreement')->find(array('aid' => $v1['id']));
            $status[$v1['id']] = array
            (
                'email' => $v1['email'],
                'is_email' => $v1['is_email'] == 1 ? '已验证' : '未验证',
                'audit' => $set['audit'][$v1['audit']],
                'agreement' => $agreement ? $ag_audit[$agreement['audit']] : '未签署',
            );
        }
        foreach ($member as $k => $v1) {
            foreach ($v1 as $v) {
                $daijiaofu_qiquan = $daijiaofu_yuanshiqiquan = $jiaofu_qiquan = $jiaofu_yaunshiqiquan = 0;
                if ($v['main'] == 1) {
                    $main = '主账户';
                } else {
                    $main = '子账户';
                }
                $where = array();
                $where['mid'] = $v['id'];
                /*
                $ff = Dever::db('option/bill_fafang')->getSearch($where);
                if ($ff && $ff['total']) {
                    $f_money = $ff['total'];
                }
                $duifu = Dever::db('option/bill_duifu')->getSearch($where);
                if ($duifu && $duifu['total']){
                    $d_money = $duifu['total'];
                }
                */

                $where['status'] = 2;
                $where['type'] = 1;
                $jiaofu = Dever::db('option/bill_jiaofu')->getSearch($where);
                if ($jiaofu && $jiaofu['total']){
                    $daijiaofu_qiquan = $jiaofu['total'];
                }
                $where['status'] = 2;
                $where['type'] = 2;
                $jiaofu = Dever::db('option/bill_jiaofu')->getSearch($where);
                if ($jiaofu && $jiaofu['total']){
                    $daijiaofu_yuanshiqiquan = $jiaofu['total'];
                }
                $where['status'] = 1;
                $where['type'] = 1;
                $jiaofu = Dever::db('option/bill_jiaofu')->getSearch($where);
                if ($jiaofu && $jiaofu['total']){
                    $jiaofu_qiquan = $jiaofu['total'];
                }

                $where['status'] = 1;
                $where['type'] = 2;
                $jiaofu = Dever::db('option/bill_jiaofu')->getSearch($where);
                if ($jiaofu && $jiaofu['total']){
                    $jiaofu_yaunshiqiquan = $jiaofu['total'];
                }
                
                $d =array
                (
                    $v['key'],
                    $v['name'],
                    $main,
                    $v['mobile'],
                    $v['idcard'],
                    $status[$v['aid']]['email'],
                    $status[$v['aid']]['is_email'],
                    $status[$v['aid']]['audit'],
                    $status[$v['aid']]['agreement'],
                    
                    $daijiaofu_qiquan,
                    $daijiaofu_yuanshiqiquan,
                    $jiaofu_qiquan,
                    $jiaofu_yaunshiqiquan,
                );
                $body[] = $d;
            }
            
        }
        $file = '期权导出';
        return Dever::excelExport($body, $header, $file);
    }

    # 体验店毛利：采购价-成本价
    public function t_buy($where, $shop_id, $shop_name, $per, &$no_t)
    {
        $where['type'] = 1;
        $where['type_id'] = $shop_id;
        $where['status'] = '5,6';
        $order = Dever::db('shop/buy_order')->getNewAll($where);
        $total = 0;
        $shop = array();
        
        if ($order) {
            foreach($order as $k => $v) {
                if (!isset($shop[$v['type_id']])) {
                    $shop[$v['type_id']] = 0;
                }
                
                $order_goods = Dever::db('shop/buy_order_goods')->select(array('order_id' => $v['id'], 'status' => 1));
                $c_price = 0;
                $price = 0;
                foreach($order_goods as $k1 => $v1){
                    $goods = Dever::load('goods/lib/info')->getPayInfo($v1['goods_id'], $v1['sku_id']);
                    $price += $v1['price'] * $v1['num'];
                    if ($goods['c_price'] && $goods['c_price'] >= 0) {
                        $c_price += $goods['c_price'] * $v1['num'];
                    } else {
                        $no_t[$v1['goods_id'] . '_' . $v1['sku_id']] = $goods['name'] . '_' . $goods['sku_name'];
                    }
                }
                $price = ($price - $c_price);
                if ($price < 0) {
                    $price = 0;
                }
                $total += $price;
                $shop[$v['type_id']] += $price * $per;
                $shop[$v['type_id']] = round($shop[$v['type_id']], 2);
            }
        }
        
        return array(round($total, 2), round($total*$per, 2), $shop);
    }
    # 零售店毛利
    public function l_buy($where, $shop_id, $shop_name, $per, &$no_l)
    {
        /*
        $where['shop_id'] = $shop_id;
        $data = Dever::db('mail/area_entry')->getBuy($where);
        $total = 0;
        $shop = array();
        if ($data) {
            foreach ($data as $k => $v) {
                if (!isset($shop[$v['shop_id']])) {
                    $shop[$v['shop_id']] = 0;
                }
                $price = $v['buy'];
                $total += $price;
                $shop[$v['shop_id']] += $price * $per;
                $shop[$v['shop_id']] = round($shop[$v['shop_id']], 2);
            }
        }
        return array(round($total, 2), round($total*$per, 2), $shop);
        */
        $total = 0;
        $shop = array();
        foreach ($shop_id as $k => $v) {
            $where['shop_id'] = $v;
            $data = Dever::db('mail/area_entry')->getBuyTotal($where);
            if ($data && $data['total'] >= 0) {
                $total += $data['total'];
                if (!isset($shop[$v])) {
                    $shop[$v] = 0;
                }
                $shop[$v] += $data['total'] * $per;
                $shop[$v] = round($shop[$v], 2);
            } else {
                $no_l[$v] = $shop_name[$k];
            }
        }
        return array(round($total, 2), round($total*$per, 2), $shop);
    }

    # 区域分润
    public function area_api()
    {
        /*
        $month = Dever::input('month', date('Y-m'));
        $start_time = $month .'-01 00:00:00';
        $where = array();
        $end_time = date('Y-m-d', strtotime($start_time. ' +1 month -1 day')).' 23:59:59';
        $where['start'] = Dever::maketime($start_time);
        $where['end'] = Dever::maketime($end_time);
        */

        # 设置利润计算规则：
        $config = array
        (
            1 => 0.01,
            2 => 0.03,
            3 => 0.05,
        );
        # 传入day，获取月开始和月结束日期
        list($where['start'], $where['end']) = Dever::month();
        $month = Dever::maketime(date('Y-m', $where['start']));

        # 获取本月未对账的对账单
        $cash_shop_where = $where;
        $cash_shop_where['status'] = 1;
        $cash_shop = Dever::db('cash/shop')->getData($cash_shop_where);
        if ($cash_shop) {
            $shop_data = array();
            foreach ($cash_shop as $k => $v) {
                $shop = Dever::db('shop/info')->find($v['shop_id']);
                if ($shop && $shop['type'] != 10) {
                    $shop_data[$v['shop_id']] = $shop['name'];
                }
            }
            if ($shop_data) {
                Dever::alert('以下门店未完成对账：' . implode(',', $shop_data));
            }
        }

        # 获取区域
        $area = array();
        $shop = Dever::db('shop/info')->select(array('status' => 1));
        $num = array();
        if ($shop) {
            foreach ($shop as $k => $v) {
                if ($v['type'] != 10) {
                    if ($v['city'] > 0) {
                        $key = $v['province'] . ',' . $v['city'];
                        $area[$key]['shop_id'][$v['type']][] = $v['id'];
                        $area[$key]['shop_name'][$v['type']][] = $v['name'];
                        $area[$key]['type'] = 1;
                    }
                    if ($v['county'] > 0) {
                        $key = $v['province'] . ',' . $v['city'] . ',' . $v['county'];
                        $area[$key]['shop_id'][$v['type']][] = $v['id'];
                        $area[$key]['shop_name'][$v['type']][] = $v['name'];
                        $area[$key]['type'] = 2;
                    }
                    if ($v['town'] > 0) {
                        $key = $v['province'] . ',' . $v['city'] . ',' . $v['county'] . ',' . $v['town'];
                        $area[$key]['shop_id'][$v['type']][] = $v['id'];
                        $area[$key]['shop_name'][$v['type']][] = $v['name'];
                        $area[$key]['type'] = 3;
                    }
                }
            }

            $area_id = array();
            $shop_data = array();
            $area_stat = array();

            # 记录体验店和零售店的错误信息
            $no_t = array();
            $no_l = array();

            foreach ($area as $k => $v) {
                $update = array();
                $update['month'] = $month;
                $update['name'] = $k;

                # 设置金额
                $update['t_num'] = $update['l_num'] = $update['t_cash'] = $update['l_cash'] = $update['t_buy'] = $update['l_buy'] = 0;
                $update['data'] = array();
                foreach ($v['shop_id'] as $k1 => $v1) {
                    if ($k1 == 1) {
                        # 体验店
                        $update['t_num'] = count($v1);
                        list($update['t_buy'], $update['t_cash'], $shop_data) = $this->t_buy($where, $v1, $v['shop_name'][$k1], $config[$v['type']], $no_t);
                        if ($shop_data) {
                            $update['data'] += $shop_data;
                        }
                    } elseif ($k1 == 2) {
                        # 零售店
                        $update['l_num'] = count($v1);
                        list($update['l_buy'], $update['l_cash'], $shop_data) = $this->l_buy($where, $v1, $v['shop_name'][$k1], $config[$v['type']], $no_l);
                        if ($shop_data) {
                            $update['data'] += $shop_data;
                        }
                    }
                }

                if ($update['t_buy'] == 0 && $update['l_buy'] == 0) {
                    //continue;
                }

                $update['type'] = $v['type'];

                # 设置收益代理商
                $update['mid'] = -1;
                $member = Dever::db('agent/member')->getAreaAll(array('area' => $k, 'role' => $v['type'] + 1));
                if ($member) {
                    $update['mid'] = $member['id'];
                    /*
                    $order = Dever::db('agent/order')->find(array('mid' => $member['id'], 'order_type' => 1));
                    if ($order && $order['price'] > 1) {
                        $update['mid'] = $member['id'];
                    }*/
                }

                if ($update['mid'] > 0) {
                    # 记录可分润区域
                    if (!isset($num[$v['type']])) {
                        $num[$v['type']] = 0;
                    }
                    $num[$v['type']]++;
                }
                $update['data'] = Dever::json_encode($update['data']);
                $area_stat[$k] = $update;
            }

            if ($no_t) {
                Dever::alert('以下商品未填写成本价：<br />' . implode(',', $no_t));
            }
            if ($no_l) {
                Dever::alert('以下门店未填写毛利：<br />' . implode(',', $no_l));
            }

            if ($area_stat) {
                foreach ($area_stat as $k => $v) {
                    # 设置上级id，用来做列表层级展示
                    if ($v['type'] == 1) {
                        $v['parent_id'] = -1;
                    } elseif ($v['type'] == 2) {
                        $area_value = explode(',', $k);
                        $k2 = $area_value[0] . ',' . $area_value[1];
                        $v['parent_id'] = isset($area_id[$k2]) ? $area_id[$k2] : -1;
                    } elseif ($v['type'] == 3) {
                        $area_value = explode(',', $k);
                        $k2 = $area_value[0] . ',' . $area_value[1] . ',' . $area_value[2];
                        $v['parent_id'] = isset($area_id[$k2]) ? $area_id[$k2] : -1;
                    }

                    $info = Dever::db('mail/area_stat')->find(array('month' => $v['month'], 'name' => $v['name'], 'clear' => true));
                    if (!$info) {
                        $stat_id = Dever::db('mail/area_stat')->insert($v);
                    } else {
                        $stat_id = $v['where_id'] = $info['id'];
                        Dever::db('mail/area_stat')->update($v);
                    }

                    if ($v['type'] == 1) {
                        $area_id[$k] = $stat_id;
                    } elseif ($v['type'] == 2) {
                        $area_id[$k] = $stat_id;
                    }
                }
            }
        }

        $this->addAreaLog('create', $month, $num);
        return 'reload';
    }

    private function addAreaLog($col, $month, $num = array())
    {
        $admin = Dever::load('manage/auth.info');
        $update['month'] = $month;
        $log = Dever::db('mail/area_stat_log')->find(array('month' => $month));
        $update[$col . '_date'] = time();
        $update[$col . '_admin'] = $admin['id'];
        if ($num) {
            $update['city_num'] = isset($num[1]) ? $num[1] : 0;
            $update['county_num'] = isset($num[2]) ? $num[2] : 0;
            $update['town_num'] = isset($num[3]) ? $num[3] : 0;
        }
        if ($log) {
            $update['where_id'] = $log['id'];
            Dever::db('mail/area_stat_log')->update($update);
        } else {
            Dever::db('mail/area_stat_log')->insert($update);
        }
    }

    # 确认对账
    public function areaYes_commit_api()
    {
        $month = Dever::input('month');
        if ($month) {
            $month = Dever::maketime($month);
            $state = Dever::db('mail/area_stat')->updates(array('option_month' => $month, 'option_status' => 2, 'set_status' => 1));
            if ($state) {
                $this->addAreaLog('confirm', $month);
            }
        }
        return 'reload';
    }

    # 确认发放
    public function areaCash_commit_api()
    {
        $month = Dever::input('month');
        if ($month) {
            $month = Dever::maketime($month);
            $data = Dever::db('mail/area_stat')->select(array('month' => $month, 'cash_status' => 2));
            if ($data) {
                $date = date('Y年m月', $month);
                foreach ($data as $k => $v) {
                    if ($v['mid']) {
                        $cash = $v['t_cash'] + $v['l_cash'];
                        $member = Dever::db('agent/member')->find($v['mid']);
                        if ($cash > 0 && $member && $member['status'] == 2) {

                            $desc = Dever::load("area/api.string", $v['name'], '') . $date . '区域运营收益';
                            $state = Dever::load('bill/lib/cash')->up($v['mid'], 15, $cash, $member['role'], $v['id'], $desc, 2, true);
                            if ($state) {
                                $where = array();
                                $where['where_id'] = $v['mid'];
                                $where['cash'] = $cash;
                                $where['clear'] = true;
                                Dever::db('agent/member')->upCash($where);
                                Dever::db('mail/area_stat')->update(array('where_id' => $v['id'], 'cash_status' => 1));
                            }
                        }
                    }
                }
                $this->addAreaLog('send', $month);
            }
        }
        return 'reload';
    }

    public function area_member($id){
        $info = Dever::db('mail/area_stat')->find($id);
        $res = '-';
        if($info['mid']){
            $member = Dever::db('agent/member')->find($info['mid']);
            if ($member) {
                $res = $member['name']."<br/>".$member['mobile'];
            }
        }
        return $res;
    }

    public function entry_member($id){
        $info = Dever::db('mail/area_entry')->find($id);
        if($info['shop_id']){
            $member = Dever::db('shop/info')->find($info['shop_id']);
            // print_R($member);die;
            $res = $member['name'].'<br/>'.$member['sid'];
        }else{
            $res = '-';
        }
        return $res;
    }

    public function updateArea_entry($id,$name,$data){
        $sid = Dever::param('sid',$data);
        $month = Dever::param('month',$data);
        if ($id && $sid) {
            $info = Dever::db('mail/area_entry')->find($id);
            $member = Dever::db('shop/info')->find(array('sid'=>$sid));
            // print_R($member);die;
            $where['where_id'] = $id ;
            $where['shop_id'] = $member['id'];
            $where['month'] = strtotime($month);
            Dever::db('mail/area_entry')->update($where);
        }
    }

    public function out_area_entry($data)
    {
        $header = array('月份','门店名称','门店编号','毛利');
        $body = array();
        if ($data) {
            // print_R($data);die;
            foreach ($data as $k => $v) {
                $shop_name = '';
                $sid = '';
                $month = '';
                if ($v['month']) {
                    $month = date('Y-m',$v['month']);
                }
                $shop = Dever::db('shop/info')->find($v['shop_id']);
                if ($shop) {
                    $shop_name = $shop['name'];
                    $sid = $shop['sid'];
                }
                // print_R($shop);die;
                $d = array
                (
                    $month,
                    $shop_name,
                    $sid,
                    $v['buy'],
                );
                $body[] = $d;
            }
            $file = Dever::input('excel_name');
            return Dever::excelExport($body, $header, $file);
        }
    }
    public function import($file)
    {
        $file = Dever::local($file);
        $data = Dever::excelImport($file,0);
        if ($data) {
            $res = array();
            foreach($data as $k=>$v){
                if ($k>=2) {
                    if ($v['A']) {
                        $where['month'] = strtotime($v['A']);
                    }
                    if ($v['C']) {
                        $v['C'] = trim($v['C']);
                        $shop = Dever::db('shop/info')->find(array('sid'=>$v['C']));
                        if ($shop) {
                            $where['shop_id'] = $shop['id'];
                        }
                    }
                    if ($v['D']) {
                        $where['buy'] = $v['D'];
                    }
                    if ($where) {
                        Dever::db('mail/area_entry')->insert($where);
                    }
                } 
            }
        }
    }

    public function area_stat_view($id)
    {
        $info = Dever::db('mail/area_stat')->find($id);

        if ($info['data']) {
            $info['data'] = Dever::json_decode($info['data']);
            if ($info['data']) {
                $table['head'] = array('门店名称', '门店编号', '收益（元）');
                foreach ($info['data'] as $k => $v) {
                    $shop = Dever::db('shop/info')->one($k);
                    $table['body'][] = array($shop['name'], $shop['sid'], $v);
                }

                $result[] = array
                (
                    'type' => 'table',
                    'content' => $table,
                );
                return Dever::show('', $result);
            }
        }
        return '';

    }
}