<?php

namespace Agent\Lib;

set_time_limit(0);
use Dever;

class Import
{
    # 图片存放地址
    private $img_host = 'https://cryl.yijiuguanfang.com/attachment/';

    # 导入开关
    private $state = 1;

    public function __construct()
    {
        $this->db = Dever::db('agent/test:old');
        $this->state = Dever::input('state', 1);
    }

    # 获取已审核的条件
    private function get_yes_where()
    {
        //issuingstate=1 已发放权益
        return 'restatus = 0 and status = 1 and  prestatus = 1 and isagent = 1';
    }

    # 获取审核失败的条件
    private function get_no_where()
    {
        //issuingstate=1 已发放权益
        return 'restatus = 1 and isagent = 1';
    }

    # 获取待审核的条件
    private function get_where()
    {
        //issuingstate=1 已发放权益
        return 'restatus = 0 and status = 0 and isagent = 1 and contractstatus = 1';
    }

    # 获取sql
    public function get_sql_api()
    {
        $table['已审核'] = 'select count(*) as num,mobile from ims_ewei_shop_member where '.$this->get_yes_where().' group by mobile order by num desc';
        $table['审核失败'] = 'select count(*) as num,mobile from ims_ewei_shop_member where '.$this->get_no_where().' group by mobile order by num desc';
        $table['待审核'] = 'select count(*) as num,mobile from ims_ewei_shop_member where '.$this->get_where().' group by mobile order by num desc';

        echo Dever::table($table);die;
    }

    public function get_api()
    {
        $this->date = Dever::maketime('2021-09-01 00:00:00');
        Dever::config('base')->hook = true;
        $host = 'https://cryl.yijiuguanfang.com/attachment/';
        
        $state = 1;
        while($state) {
            $state = $this->get_data($host, $state);
        }

        # 导入关联表
        $this->relation_api();

        # 导入业绩
        $this->sell_api();

        # 导入地区价格
        //$this->getAreaPrice();

        # 导入余额 不导入了
        //$this->getYue();
        return 'ok';
    }

    public function get_area_api()
    {
        Dever::config('base')->hook = true;
        $data = Dever::db('agent/member')->getDataByRole(array('role' => '2,3,4'));

        if (!$data) {
            return false;
        }

        foreach ($data as $k => $v) {
            $area = explode(',', $v['area']);

            $num = count($area);

            $area_name = Dever::load("area/api.string", $v['area']);
            if ($v['role'] == 2 && $num != 2) {
                $this->log($v['id'], 9, $area_name, '城市错误');
            }
            if ($v['role'] == 3 && $num != 3) {
                $this->log($v['id'], 9, $area_name, '区县错误');
            }
            if ($v['role'] == 4 && $num != 4) {
                $this->log($v['id'], 9, $area_name, '街道错误');
            }
            if ($v['area']) {
                $check = Dever::db('agent/member')->find(array('area' => $v['area'], 'role' => $v['role']));
                if (!$check) {
                    $this->log($v['id'], 9, $area_name, '区域匹配错误');
                }
                if ($v['role'] == 2 && isset($area[1]) && $area[1]) {
                    $city = Dever::db('area/city')->find($area[1]);
                    if ($city['status'] == 1) {
                        //$this->log($v['id'], 9, $area_name, '城市占用错误');
                        Dever::load('area/api')->upStatus($v['area'], 2);
                    }
                }
                if ($v['role'] == 3 && isset($area[2]) && $area[2]) {
                    $city = Dever::db('area/county')->find($area[2]);
                    if ($city['status'] == 1) {
                        //$this->log($v['id'], 9, $area_name, '区县占用错误');
                        Dever::load('area/api')->upStatus($v['area'], 2);
                    }
                }
                if ($v['role'] == 4 && isset($area[3]) && $area[3]) {
                    $city = Dever::db('area/town')->find($area[3]);
                    if ($city['status'] == 1) {
                        //$this->log($v['id'], 9, $area_name, '街道占用错误');
                        Dever::load('area/api')->upStatus($v['area'], 2);
                    }
                }
            }
            
        }
        return 'ok';
    }

    public function get_data($host, $index = 0)
    {
        # 获取已审核通过、权益已发放的用户
        $index = $index - 1;
        $limit = 1000;
        
        $data = $this->db->fetchAll('select * from ims_ewei_shop_member where status = 1 and  prestatus = 1 and isagent = 1 order by id asc limit ' . $index . ', ' . $limit);

        if (!$data) {
            return false;
        }

        foreach ($data as $k => $v) {

            # 创建订单
            $order = Dever::db('agent/order')->find(array('id' => $v['id'], 'clear' => true));
            if (1) {
                $update = false;
                if ($order) {
                    $update = true;
                }

                $data = array();
                $data['id'] = $v['id'];
                $data['mobile'] = $v['mobile'];
                if (!$v['mobile']) {
                    $v['mobile'] = '12345';
                }
                $data['name'] = $v['realname'];
                if (!$data['name']) {
                    $data['name'] = 'boss';
                }
                if ($v['pwd']) {
                    $data['old_pwd'] = $v['pwd'];
                    $data['old_salt'] = $v['salt'];
                }
                
                if ($v['avatar'] && strstr($v['avatar'], 'http')) {
                    $data['avatar'] = $v['avatar'];
                } elseif ($v['avatar']) {
                    $data['avatar'] = $host . $v['avatar'];
                } else {
                    $data['avatar'] = '';
                }
                
                $data['username'] = $v['nickname'];
                $data['mid'] = $v['id'];
                $data['parent_mid'] = $v['agentid'];
                $data['admin_desc'] = $v['content'];
                $data['parent_code'] = Dever::load("invite/api.code", $data['parent_mid']);
                $data['address'] = $v['province'] . $v['city'] . $v['area'] . $v['street'];
                $data['role'] = $this->getRole($v['agentlevel']);
                $role = Dever::db('setting/role')->find($data['role']);
                $data['area'] = '';
                if ($v['datavalue']) {
                    $v['datavalue'] = trim(str_replace(" ", ',', $v['datavalue']));
                    list($data['area'], $new) = Dever::load('area/api')->up($v['province'], $v['city'], $v['area'], $v['street'], $v['datavalue'], $v['streetvalue']);
                    # 记录日志
                    if ($new) {
                        $this->log($v['id'], 4, $data['address'], $new, $update);
                    }
                    
                } else {
                    if ($v['province'] && $v['city']) {
                        list($data['area'], $new) = Dever::load('area/api')->upByName($v['province'], $v['city'], $v['area'], $v['street'], $v['streetvalue']);
                        # 记录日志
                        if ($data['area'] && strstr($data['area'], '-1')) {
                            if ($this->state == 2) {
                                $this->log($v['id'], 5, $data['address'], $new, $update);
                            }
                            if ($role['id'] == 5) {
                                # 创服代理商无需记录
                                $data['area'] = '';
                            } else {
                                $date = $v['agentapplytime'];
                                if ($role['id'] == 6 && $date <= $this->date) {
                                    # 9月1日之前的创客无需导入
                                    $data['area'] = '';
                                } else {
                                    if ($this->state == 1) {
                                        $this->log($v['id'], 5, $data['address'], $new, $update);
                                    }
                                    $data['area'] = '';
                                }
                            }
                        }
                    }
                }
                
                if ($v['entertype'] == 1) {
                    $data['type'] = 1;
                } else {
                    $data['type'] = 2;
                }

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

                if ($data['price'] < 1 && $this->state == 2) {
                    $this->log($v['id'], 6, $data['price'], $data['price'], $update);
                }

                if ($role['type'] == 1) {
                    //$data['f_price'] = $role['price'];
                } elseif ($role['type'] == 2) {
                    /*
                    $data['f_price'] = Dever::load('area/api')->getPrice($role['area'], $data['area']);
                    if ($data['f_price'] <= 0) {
                        $data['f_price'] = $data['price'];
                    }
                    */

                    # 区域要进行占用
                    if ($data['area']) {
                        Dever::load('area/api')->upStatus($data['area'], 2);
                        $area_data = array('mid' => $v['id'], 'order_id' => $v['id'], 'role' => $data['role'], 'area' => $data['area']);
                        $area_info = Dever::db('agent/member_area')->getOne($area_data);
                        if (!$area_info) {
                            $area_data['type'] = 4;
                            $area_data['price'] = $data['f_price'];
                            $area_data['cdate'] = $v['agentapplytime'];
                            Dever::db('agent/member_area')->insert($area_data);
                        }
                    }
                }
                $data['agent_cash'] = $data['f_price'];

                $data['sign'] = $v['contractsign'] ? $host . $v['contractsign'] : '';
                $data['idcard'] = $v['idnumber'];
                $data['idcard_front'] = $data['idcard_back'] = '';
                if ($v['identity']) {
                    $identity = Dever::json_decode($v['identity']);
                    if (isset($identity[0])) {
                        $data['idcard_front'] = $host . $identity[0];
                    }
                    if (isset($identity[1])) {
                        $data['idcard_back'] = $host . $identity[1];
                    }
                }
                $data['company_name'] = $v['company'];

                $data['pay_type'] = 2;
                if ($v['receipt']) {
                    $receipt = Dever::json_decode($v['receipt']);
                    $data['pay_pic'] = array();
                    foreach ($receipt as $v1) {
                        $data['pay_pic'][] = $host . $v1;
                    }
                    $data['pay_pic'] = implode(',', $data['pay_pic']);
                }

                $data['status'] = $this->getStatus($v);
                $data['audit_desc'] = $v['refuse'];

                if ($v['issuingstate'] == 1) {
                    $data['goods_status'] = 3;
                } else {
                    $data['goods_status'] = 1;
                }
                $data['pay_status'] = 2;
                $data['import'] = $v['olduid'] > 0 ? 3 : 2;

                $data['order_num'] = Dever::load('agent/lib/order')->getOrderId();
                $data['cdate'] = $v['agentapplytime'];
                if ($data['status'] == 4) {
                    $data['fdate'] = $v['agenttime'];
                }
                $data['order_type'] = 1;
                $data['company_pic'] = '';

                if ($update) {
                    $data['where_id'] = $order['id'];
                    $order_id = Dever::db('agent/order')->update($data);
                } else {
                    $order_id = Dever::db('agent/order')->insert($data);
                }

                if ($order_id) {

                    if (!$v['preagenttime']) {
                        $v['preagenttime'] = $v['agenttime'];
                    }
                    if (!$update) {
                        if ($data['status'] == 2) {
                            $this->addProcess($order_id, 1, $v['preagenttime'], $data);
                        } elseif ($data['status'] == 3) {
                            $this->addProcess($order_id, 1, $v['preagenttime'], $data);
                            $this->addProcess($order_id, 2, $v['agenttime'], $data);
                        } elseif ($data['status'] == 4) {
                            $this->addProcess($order_id, 1, $v['preagenttime'], $data);
                            $this->addProcess($order_id, 2, $v['agenttime'], $data);
                            $this->addProcess($order_id, 3, $v['agenttime'], $data);
                        }
                    }

                    if ($data['status'] == 4) {
                        # 生成合同
                        if (!$update && $data['sign']) {
                            $data['sdate'] = $data['cdate'];
                            $this->addAgreement($data);
                            unset($data['sdate']);
                        }

                        $member = Dever::db('agent/member')->find($v['id']);

                        if ($data['status'] == 4) {
                            $data['status'] = 2;
                        } elseif ($data['status'] == 5) {
                            $data['status'] = 1;
                            $data['state'] = 2;
                        } else {
                            $data['status'] = 1;
                        }

                        $mc_member = $this->db->fetch('select * from ims_mc_members where uid = ' . $v['uid']);
                        $data['rdate'] = $v['agenttime'];
                        //$data['cash'] = ($mc_member && $mc_member['credit2']) ? $mc_member['credit2'] : $v['credit2'];
                        if ($this->state == 1) {
                            $data['group_sell'] = $v['allcommission'];
                        }
                        $data['old_agentdownnum'] = $v['agentdownnum'];
                        $data['old_group_sell'] = $v['allcommission'];

                        if (!$member) {
                            Dever::db('agent/member')->insert($data);
                        } else {
                            $data['where_id'] = $member['id'];
                            Dever::db('agent/member')->update($data);
                        }

                        if (!$update && $data['parent_mid']) {
                            # 添加直推关系
                            Dever::load('invite/lib/relation')->add($data['parent_mid'], $data['mid'], 1);
                            # 为上级增加增加业绩
                            Dever::load('bill/lib/sell')->up($data['parent_mid'], 1, $data['f_price'], $data['role'], $order_id, '邀请' . $data['name'] . '['.$data['mobile'].']新增直推业绩', 3, $data['cdate']);

                            if ($this->state == 2) {
                                Dever::load('bill/lib/sell')->up($data['parent_mid'], 2, $data['f_price'], $data['role'], $order_id, '邀请' . $data['name'] . '['.$data['mobile'].']新增团队业绩', 3, $data['cdate']);
                            }
                        }

                        if ($this->state == 1) {
                            if (!$update) {
                                Dever::load('bill/lib/sell')->up($data['mid'], 2, $data['group_sell'], $data['role'], $order_id, '新增团队业绩', 3, time());
                            }
                        }
                    }
                    echo $v['id'];
                    echo "\r\n";
                }
            }
        }
        $index = $index + 1;
        return $index + $limit;
    }

    # 设置邀请关系 要跑完所有数据才能设置
    public function relation_api()
    {
        Dever::config('base')->hook = true;

        $state = 1;
        while($state) {
            $state = $this->setRelation($state);
        }

        return 'ok';
    }

    private function setRelation($index)
    {
        # 获取已审核通过、权益已发放的用户
        $index = $index - 1;
        $limit = 500;
        
        $data = Dever::db('invite/relation')->fetchAll('select * from {table} where level = 1 order by id desc limit ' . $index . ', ' . $limit);

        if (!$data) {
            return false;
        }

        //$data = Dever::db('invite/relation')->all(array('level' => 1));
        foreach ($data as $k => $v) {
            $check = Dever::db('invite/relation')->one(array('to_uid' => $v['to_uid'], 'level' => 2, 'clear' => true));
            if (!$check) {
                $order = Dever::db('agent/order')->find(array('id' => $v['to_uid'], 'status' => 4));
                if ($order) {
                    $this->addRelation($v['to_uid'], $v['uid'], 2, $order);
                }
            }
            
            echo $v['id'];
            echo "\r\n";
        }

        $index = $index + 1;
        return $index + $limit;
    }

    private function addRelation($cur, $parent, $level, $order)
    {
        $info = Dever::db('invite/relation')->one(array('to_uid' => $parent));
        if ($info) {
            $state = Dever::load('invite/lib/relation')->add($info['uid'], $cur, $level, $order);
            if ($state) {
                # 新增团队业绩
                if ($this->state == 2) {
                    Dever::load('bill/lib/sell')->up($info['uid'], 2, $order['f_price'], $order['role'], $order['id'], '邀请' . $order['name'] . '['.$order['mobile'].']新增团队业绩', 3, $order['cdate']);
                }
            } else {
                return $this->addRelation($cur, $parent, $level, $order);
            }
            $level = $level + 1;
            return $this->addRelation($cur, $info['uid'], $level, $order);
        }
    }

    # 对业绩进行整理
    public function sell_api()
    {
        # 获取所有用户
        $data = Dever::db('agent/member')->select();

        if ($data) {
            foreach ($data as $k => $v) {
                $update = array();

                # 获取直推代理人数
                $num = Dever::load('invite/api')->getChildNum($v['id'], 1);
                if ($num != $v['old_agentdownnum']) {
                    # 记录日志 无需记录 数据无误
                    if ($this->state == 2) {
                        $this->log($v['id'], 2, $v['old_agentdownnum'], $num);
                    }
                }

                # 获取直推业绩
                $sell = Dever::db('bill/sell')->getNumByTimeOne(array('mid' => $v['id'], 'type' => 1, 'stype' => 3));
                if ($sell && $sell['num']) {
                    $update['sell'] = $sell['num'];
                }
                # 获取团队业绩
                $sell = Dever::db('bill/sell')->getNumByTimeOne(array('mid' => $v['id'], 'type' => 2, 'stype' => 3));
                if ($sell && $sell['num']) {
                    $update['group_sell'] = $sell['num'];
                    if ($update['group_sell'] != $v['old_group_sell']) {
                        # 记录日志 无需记录
                        if ($this->state == 2) {
                            $this->log($v['id'], 3, $v['old_group_sell'], $update['group_sell']);
                        }
                    }

                    if ($v['level_id'] > 0) {
                        $cur_level = Dever::db('setting/level')->find($v['level_id']);
                    } else {
                        $cur_level = array('id' => -1, 'name' => '普通', 'level' => 0, 'num' => 1, 'value' => '0');
                    }
                    $level = Dever::db('setting/level')->getOne(array('target' => ($update['group_sell']/10000)));
                    if ($level && $level['level'] > $cur_level['level']) {
                        $update['level_id'] = $level['id'];
                        Dever::load('agent/lib/level_log')->up($v['id'], -1, $cur_level['id'], $level['id'], $update['group_sell'], $update['group_sell'], $num);
                    }
                }

                if ($update) {
                    $update['where_id'] = $v['id'];
                    Dever::db('agent/member')->update($update);
                }

                echo $v['id'];
                echo "\r\n";
            }
        }
    }

    # 图片本地化
    public function local_api()
    {
        $data = Dever::db('agent/member')->select();
        # avatar sign idcard_front idcard_back pay_pic(多个) 9
        $key = 9;
        if ($data) {
            foreach ($data as $k => $v) {
                if ($v['id'] >= 50000) {
                    continue;
                }
                $update = array();
                $order_update = array();
                if ($v['avatar']) {
                    $update['avatar'] = $this->upload($v['avatar']);
                }
                if ($v['sign']) {
                    $update['sign'] = $this->upload($v['sign']);
                    $order_update['sign'] = $update['sign'];
                }
                if ($v['idcard_front']) {
                    $update['idcard_front'] = $this->upload($v['idcard_front']);
                    $order_update['idcard_front'] = $update['idcard_front'];
                }
                
                if ($v['idcard_back']) {
                    $update['idcard_back'] = $this->upload($v['idcard_back']);
                    $order_update['idcard_back'] = $update['idcard_back'];
                }

                if ($update) {
                    $update['where_id'] = $v['id'];
                    Dever::db('agent/member')->update($update);

                    $order = Dever::db('agent/order')->find($v['id']);
                    if ($order && $order_update) {
                        if ($order['pay_pic']) {
                            $temp = explode(',', $order['pay_pic']);
                            foreach ($temp as $k1 => $v1) {
                                $temp[$k1] = $this->upload($v1);
                            }
                            $order_update['pay_pic'] = implode(',', $temp);
                        }
                        if ($order_update) {
                            $order_update['where_id'] = $v['id'];
                            Dever::db('agent/order')->update($update);
                        }
                    }
                }
                
                echo $v['id'];
                echo "\r\n";
            }
        }
    }

    private function upload($file)
    {
        if ($file && strstr($file, 'http') && !strstr($file, '7.churenyiliao')) {
            $data = Dever::load('upload/save')->copy($file, 9);
            if (isset($data['url'])) {
                return $data['url'];
            } else {
                return $file;
            }
        } else {
            return $file;
        }
    }

    # 同步pwd和salt
    public function pwd_api()
    {
        $data = Dever::db('agent/member')->select();
        if ($data) {
            foreach ($data as $k => $v) {

                $info = $this->db->fetch('select * from ims_ewei_shop_member where id =' . $v['id']);
                if (!$info) {
                    continue;
                }
                if (!$info['pwd']) {
                    continue;
                }
                $update = array();
                $update['old_pwd'] = $info['pwd'];
                $update['old_salt'] = $info['salt'];

                $update['where_id'] = $v['id'];
                Dever::db('agent/member')->update($update);
                echo $v['id'];
                echo "\r\n";
            }
        }
    }

    # 导入创客名额
    public function chuangke_api()
    {
        $data = Dever::db('agent/member')->select();
        $type = 3;
        $type_id = 1;
        $desc = '自动发放';
        if ($data) {
            foreach ($data as $k => $v) {

                $info = $this->db->fetch('select * from ims_ewei_shop_member where id =' . $v['id']);
                if (!$info) {
                    continue;
                }
                if (!$info['direct_num']) {
                    continue;
                }
                $direct_num = unserialize($info['direct_num']);
                if (isset($direct_num[4]) && $direct_num[4]) {
                    $total = $direct_num[4];

                    $prize = Dever::db('setting/prize')->find($type_id);
                    $price = $prize['price'];
                    $cash = $prize['price'] * $total;
                    $name = $prize['name'];

                    $w = array();
                    $w['type'] = $type;
                    $w['type_id'] = $type_id;
                    $w['sku_id'] = -1;
                    $w['mid'] = $v['id'];

                    $state = Dever::db('agent/member_goods')->one($w);
                    $w['total_num'] = $total;
                    $w['cash'] = $cash;
                    $w['price'] = $price;
                    $w['name'] = $name;
                    if (!$state) {
                        $state = Dever::db('agent/member_goods')->insert($w);
                        if ($state) {
                            Dever::load('agent/lib/member_set')->log($w['mid'], '', $w['type'], $w['type_id'], $w['sku_id'], $total, 0, $w['total_num'], $name, $desc);
                        }
                    }

                    $this->log($v['id'], 7, $total, $total, true);
                    echo $v['id'];
                    echo "\r\n";
                }
            }
        }
    }

    # 同步邀请码
    public function invite_code_api()
    {
        $data = Dever::db('agent/order')->select();
        if ($data) {
            foreach ($data as $k => $v) {

                if ($v['parent_mid'] && $v['parent_mid'] > 0) {
                    $parent_code = Dever::load("invite/api.code", $v['parent_mid']);

                    if ($parent_code) {
                        $update = array();
                        $update['parent_code'] = $parent_code;
                        $update['where_id'] = $v['id'];
                        Dever::db('agent/order')->update($update);
                        echo $v['id'];
                        echo "\r\n";
                    }
                }
            }
        }
    }

    # 计算支付金额和角色是否能对应
    public function role_api()
    {
        $data = Dever::db('agent/order')->select();
        if ($data) {
            foreach ($data as $k => $v) {
                $role = Dever::db('setting/role')->find($v['role']);
                $price = 0;
                if ($role['type'] == 1) {
                    $price = $role['price'];
                } elseif ($role['type'] == 2) {
                    $price = Dever::load('area/api')->getPrice($role['area'], $v['area']);
                }
                if ($price > 0 && $price != $v['price']) {
                    $this->log($v['mid'], 8,  $v['price'], $price, true);
                }
                echo $v['id'];
                echo "\r\n";
            }
        }
    }

    # 导入日志记录
    public function log($mid, $type, $before, $after, $update = true)
    {
        # 地区、直推代理人数、团队业绩
        $data['mid'] = $mid;
        $data['type'] = $type;
        $data['before'] = $before;
        $data['after'] = $after;
        if ($type == 4 || $type == 7) {
            $data['status'] = 2;
        }
        if ($update) {
            $info = Dever::db('agent/import_log')->find($data);
            if (!$info) {
                Dever::db('agent/import_log')->insert($data);
            }
        } else {
            Dever::db('agent/import_log')->insert($data);
        }
    }

    public function get_cash_api()
    {
        # 获取已审核通过、权益已发放的用户
        /*
        # 团队业绩
        $data = $this->db->fetchAll('select a.*,b.credit3 as bcredit3 from ims_ewei_shop_member as a left join ims_mc_members as b on b.uid = a.uid where a.status = 1 and a.prestatus = 1 and a.isagent = 1 and (b.credit3 > 0 || a.credit3 > 0) order by a.id asc ');

        if (!$data) {
            return false;
        }

        foreach ($data as $k => $v) {
            if ($v['bcredit3'] > 0) {
                $num = $v['bcredit3'];
            } else {
                $num = $v['credit3'];
            }
            $this->cash_log($v['id'], 2, $num);
            echo $v['id'];
            echo "\r\n";
        }

        # 团队业绩
        $data = $this->db->fetchAll('select a.*,b.credit2 as bcredit2 from ims_ewei_shop_member as a left join ims_mc_members as b on b.uid = a.uid where a.status = 1 and a.prestatus = 1 and a.isagent = 1 and (b.credit2 > 0 || a.credit2 > 0) order by a.id asc ');

        if (!$data) {
            return false;
        }

        foreach ($data as $k => $v) {
            if ($v['bcredit2'] > 0) {
                $num = $v['bcredit2'];
            } else {
                $num = $v['credit2'];
            }
            $this->cash_log($v['id'], 1, $num);
            echo $v['id'];
            echo "\r\n";
        }
        */
        $data = Dever::db('agent/member')->getDataByArea(array('area' => '150000,150100'));

        if (!$data) {
            return false;
        }

        foreach ($data as $k => $v) {
            $num = Dever::db('agent/member')->total(array('parent_mid' => $v['id'], 'role' => 6));
            if ($num > 0) {
                $this->cash_log($v['id'], 3, $num);
            }
            
            echo $v['id'];
            echo "\r\n";
        }

        return 'ok';
    }

    public function cash_log($mid, $type, $num)
    {
        # 地区、直推代理人数、团队业绩
        $data['mid'] = $mid;
        $data['type'] = $type;
        $data['num'] = $num;
        $info = Dever::db('agent/import_cash_log')->find($data);
        if (!$info) {
            Dever::db('agent/import_cash_log')->insert($data);
        } else {
            $data['where_id'] = $info['id'];
            Dever::db('agent/import_cash_log')->update($data);
        }
    }

    # 验证直推代理人数是否正确 agentdownnum

    # 导入区域价格
    private function getAreaPrice()
    {
        $data = $this->db->fetchAll('select * from ims_ewei_shop_wang_city_other where deleted=0 and hide=0');
        if ($data) {
            foreach ($data as $k => $v) {
                $province = Dever::db('area/province')->one(array('name' => $v['province']));
                if ($province && $v['city']) {
                    $city = Dever::db('area/city')->one(array('name' => $v['city'], 'province_id' => $province['id']));
                    if ($city && $v['district']) {
                        $county = Dever::db('area/county')->one(array('name' => $v['district'], 'city_id' => $city['id']));
                        if ($county && $v['identity'] == 3) {
                            # 区县
                            Dever::db('area/county')->update(array('where_id' => $county['id'], 'price' => $v['money']));
                        } elseif ($county && $v['street'] && $v['identity'] == 4) {
                            # 街道
                            if (strstr($v['street'], '燕郊')) {
                                Dever::db('area/town')->update(array('where_id' => 131082450, 'price' => $v['money']));
                                Dever::db('area/town')->update(array('where_id' => 131082109, 'price' => $v['money']));
                            } else {
                                $town = Dever::db('area/town')->one(array('name' => $v['street'], 'county_id' => $county['id']));
                                if ($town) {
                                    Dever::db('area/town')->update(array('where_id' => $town['id'], 'price' => $v['money']));
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    # 导入余额日志[不包括提现]
    private function getYue()
    {
        $data = $this->db->fetchAll('select * from mc_credits_record where credittype = "credit2" order by id asc');
        if ($data) {
            foreach ($data as $k => $v) {
                if ($v['credittype'] == 'credit2') {
                    # 直推佣金
                    $type = 1;
                } elseif ($v['credittype'] == 'credit3') {
                    # 市场培训费
                    $type = 2;
                } else {
                    continue;
                }
                $remark = $v['remark'];
                if (strstr($remark, '提现')) {
                    continue;
                }
                $info = Dever::db('bill/cash')->one(array('id' => $v['id'], 'clear' => true));
                if (!$info) {
                    $update['id'] = $v['id'];
                    $update['type'] = $type;

                    if ($v['uid'] > 0) {
                        $member = $this->db->fetch('select * from ims_ewei_shop_member where uid = ' . $v['uid'] . ' and isagent = 1 and status = 1 and prestatus = 1');
                        if ($member) {
                            $update['mid'] = $member['id'];
                        }
                    } elseif ($remark) {
                        $temp = explode('OPENID: ', $remark);
                        $temp = explode(' 剩余', $temp[1]);
                        if (isset($temp[0]) && $temp[0]) {
                            $member = $this->db->fetch('select * from ims_ewei_shop_member where openid = "' . $temp[0] . '" and isagent = 1 and status = 1 and prestatus = 1');
                            if ($member) {
                                $update['mid'] = $member['id'];
                            }
                        }
                    }
                    
                    if (isset($update['mid']) && $update['mid'] > 0) {
                        if (strstr($remark, '消费')) {
                            $type = 12;
                        }
                        $update['cash'] = $v['num'];
                        $update['yue'] = $v['presentcredit'];
                        $update['status'] = 2;
                        $update['audit'] = 2;
                        $update['cdate'] = $update['operdate'] = $v['createtime'];
                        $update['order_num'] = Dever::load('bill/lib/cash')->getOrderId();
                        Dever::db('bill/cash')->insert($update);
                    }
                }
            }
        }
    }

    # 获取提现
    private function getTixian()
    {
        $data = $this->db->fetchAll('select * from ims_ewei_shop_member_log where type > 0');
        if ($data) {
            foreach ($data as $k => $v) {
                $v['id'] = 50000 + $v['id'];
                $info = Dever::db('bill/cash')->one(array('id' => $v['id'], 'clear' => true));
                if (!$info) {
                    $update['id'] = $v['id'];
                    $update['type'] = 11;

                    if ($v['uid'] > 0) {
                        $member = $this->db->fetch('select * from ims_ewei_shop_member where uid = ' . $v['uid'] . ' and isagent = 1 and status = 1 and prestatus = 1');
                        if ($member) {
                            $update['mid'] = $member['id'];
                        }
                    } elseif ($remark) {
                        $member = $this->db->fetch('select * from ims_ewei_shop_member where openid = "' . $v['openid'] . '" and isagent = 1 and status = 1 and prestatus = 1');
                        if ($member) {
                            $update['mid'] = $member['id'];
                        }
                    }

                    if (isset($update['mid']) && $update['mid'] > 0) {
                        $update['cash'] = $v['num'];
                        $update['yue'] = $v['presentcredit'];
                        $status = 1;
                        $fstatus = -1;
                        if ($v['status'] == 0 && $v['check'] == 0) {
                            # 待审核
                            $status = 1;
                        } elseif ($v['status'] != -1 && $v['check'] == 1) {
                            # 已审核
                            $status = 2;
                        } elseif ($v['status'] == 0 && $v['check'] == 1) {
                            # 待发放
                            $status = 2;
                            $fstatus = 1;
                        } elseif ($v['status'] == 1 && $v['check'] == 1) {
                            # 已发放
                            $status = 2;
                            $fstatus = 2;
                        } elseif ($v['check'] == -1) {
                            # 已拒绝
                            $status = 3;
                        }
                        
                        $update['status'] = $status;
                        $update['audit'] = $status;
                        $update['cdate'] = $v['createtime'];
                        $update['operdate'] = $v['checktime'];
                        $update['order_num'] = Dever::load('bill/lib/cash')->getOrderId();
                        $id = Dever::db('bill/cash')->insert($update);
                        if ($id) {
                            $tixian['order_num'] = Dever::load('bill/lib/tixian')->getOrderId();
                            $tixian['id'] = $v['id'];
                            $tixian['cash_id'] = $v['id'];
                            $tixian['mid'] = $update['mid'];
                            $tixian['ycash'] = $v['money'];
                            $tixian['cash'] = $v['realmoney'];
                            $tixian['yue'] = $v['deductionmoney'];
                            $tixian['name'] = $v['realname'];
                            $tixian['bank'] = $this->upBank($v['bankname']);
                            $tixian['bankname'] = $v['bankopen'];
                            $tixian['card'] = $v['bankcard'];
                            $tixian['status'] = $fstatus;
                            Dever::db('bill/tixian')->insert($tixian);
                        }
                    }
                }
            }
        }
    }

    # 导入关联表
    private function getRelation()
    {
        $data = $this->db->fetchAll('select * from ims_ewei_shop_commission_relation');
        if ($data) {
            foreach ($data as $k => $v) {
                $where['uid'] = $v['pid'];
                $where['to_uid'] = $v['id'];
                $where['level'] = $v['level'];
                $info = Dever::db('invite/relation')->one($where);
                if (!$info) {
                    Dever::db('invite/relation')->insert($where);
                }
            }
        }
    }

    # 生成合同
    private function addAgreement($data)
    {
        Dever::load('agent/lib/agreement')->up($data);
    }

    # 更新进度
    private function addProcess($order_id, $status, $time, $data)
    {
        $where['order_id'] = $order_id;
        $where['status'] = $status;
        $info = Dever::db('agent/order_process')->find($where);
        if (!$info) {
            if ($status == 3) {
                $where['type'] = '1,2,3,5';
            }
            $where['cdate'] = $time;
            Dever::db('agent/order_process')->insert($where);
        }
    }

    # 状态对应
    private function getStatus($data)
    {
        # 完成权益发放issuingstate、财务审核status、初审prestatus的认为订单有效
        if ($data['issuingstate'] == 1 && $data['status'] == 1 && $data['prestatus'] == 1) {
            return 4;
        } elseif ($data['status'] == 1 && $data['prestatus'] == 1) {
            return 4;
        } elseif ($data['prestatus'] == 1) {
            return 2;
        } elseif ($data['restatus'] == 1) {
            # 审核失败
            return 5;
        } elseif ($data['trainersign'] && $data['contractsign']) {
            return 1;
        } else {
            return -2;
        }
    }

    # 代理商角色对应
    private function getRole($role)
    {
        # key是历史数据 value是最新数据
        $config = array
        (
            # 创服
            5 => 5,

            # 创客
            4 => 6,

            # 逍客
            8 => 7,

            # 城市
            1 => 2,

            # 区县
            2 => 3,

            # 街道
            3 => 4,

            # 炒菜机分享会员
            6 => 8,

            # 热敏炉分享会员
            7 => 9,
        );

        if (isset($config[$role]) && $config[$role]) {
            return $config[$role];
        }

        return 1;
    }
}