<?php
/*
 本代码由 焕岱科技 创建
 技术支持 WX：15285007200
 严禁反编译、逆向等任何形式的侵权行为，违者将追究法律责任
*/

namespace app\admin\controller\bbfxshop\order;

use app\admin\controller\bbfxshop\Base;
use think\Db;

use app\common\model\bbfxshop\Fenxiao;
use app\common\model\bbfxshop\User;
use app\common\model\bbfxshop\FenxiaoLevel;

use Exception;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;

use think\Cache;

class Order extends Base 
{
    protected $order_type = 0;
    public $model = null;
    public function _initialize(){
        parent::_initialize();
        $this->model = new \app\common\model\bbfxshop\Order;
    }

    public function import(){
        $file = $this->param('file/s');
        if (!$file) {
            __error("请上传文件");
        }
        $filePath = ROOT_PATH . 'public' . replaceSiteroot($file);
        
        if (!is_file($filePath)) {
            __error("未找到文件");
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            __error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, "w");
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding != 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }

        //加载文件
        $insert = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                __error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[] = $val;
                }
            }
            
            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : $val;
                }
                
                // print_r($values);die;
                if(!empty($values)){
                    
                    // 日期转换 \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($values[5])->format('Y-m-d')
                    
                    $insert[] = array(
                        "order_no"=>$values[0],
                        "express_name"=>$values[1],
                        "express_no"=>$values[2]
                    );
                }
                else{
                    $insert[] = [];
                }
            }
        } catch (Exception $exception) {
            __error($exception->getMessage());
        }
        if (!$insert) {
            __error(__('No rows were updated'));
        }
        // unlink($filePath);
        // echo "<pre>";
        // print_r($insert);die;
        // $order_ons = array_column($insert,"order_no");
        $order_ons = [];
        $n = 0;
        foreach ($insert as $key => $val){
            if(!empty($val['order_no'])){
                $order_ons[] = $val['order_no'];
            }
        }
        $order_list = Db::name("bbfx_order")->where(['uniacid'=>UNIACID,'is_pay'=>1,'order_no'=>['in',$order_ons]])->field("id,order_no,status,is_pay,order_type,is_hexiao,refund_status,paytype,platform,delivery_method,delivery_mobile")->select();
        $orders = [];
        if(!empty($order_list)){
            $orders = array_skey($order_list,"order_no");
        }
        
        $express_list = Db::name("bbfx_express")->where(['status'=>1])->field("id,name")->select();
        $expresss = [];
        if(!empty($express_list)){
            $expresss = array_skey($express_list,"name");
        }
        
        // unlink($filePath);
        // echo "<pre>";
        // print_r($expresss);die;
        $log = "";
        
        $success = 0;
        $order_ids = [];
        foreach ($insert as $key => $val){
            if(empty($val['order_no'])){
                $log .= "第".($key+2)."行，订单编号缺失<br>";
                continue;
            }
            if(empty($val['express_name'])){
                $log .= "第".($key+2)."行，快递公司名称缺失<br>";
                continue;
            }
            if(empty($val['express_no'])){
                $log .= "第".($key+2)."行，快递单号缺失<br>";
                continue;
            }
            
            // $order = Db::name("bbfx_order")->where(['uniacid'=>UNIACID,'order_no'=>$val['order_no']])->find();
            $order = $orders[$val['order_no']];
            if(empty($order)){
                $log .= "第".($key+2)."行，订单不存在<br>";
                continue;
            }
            if($order['is_pay'] != 1){
                $log .= "第".($key+2)."行，订单未支付<br>";
                continue;
            }
            if($order['status'] != 1){
                $log .= "第".($key+2)."行，订单已发货<br>";
                continue;
            }
            if($order['order_type'] != 2 || $order['is_hexiao'] == 1){
                $log .= "第".($key+2)."行，不是发货订单<br>";
                continue;
            }
            
            // $express = Db::name("bbfx_express")->where(['name'=>['like','%'.$val['express_name'].'%']])->find();
            $express = $expresss[$val['express_name']];
            if(empty($express)){
                foreach ($express_list as $v){
                    if(strstr($v['name'], $val['express_name'])){
                        $express = $v;
                        break;
                    }
                }
            }
            if(empty($express)){
                $log .= "第".($key+2)."行，快递公司不存在<br>";
                continue;
            }
            
            $express = [
                [
                    "express_id"=>$express['id'],
                    "express_name"=>$express['name'],
                    "express_no"=>$val['express_no'],
                    "goods_id"=>""
                ]
            ];
            
            
            $data = [
                'express'=>iserializer($express),
                'status'=>2,
                'deliverytime'=>time(),
                'deliver_type'=>1
            ];
            
            
            try {
                Db::startTrans();
                
                Db::name("bbfx_order")->where(['id'=>$order['id']])->update($data);
                
                $order['express'] = $data['express'];
                $order['status'] = $data['status'];
                $order['deliverytime'] = $data['deliverytime'];
                $order['deliver_type'] = $data['deliver_type'];
                $this->model->sendGoods($order);
                
                $order_ids[] = $order['id'];
                Db::commit();
                $success++;
            } catch (Exception $e) {
                Db::rollback();
                $log .= "第".($key+2)."行，导入失败：".$e->getMessage()."<br>";
            }
            
            // break;
        }
        
        $data = [
            "uniacid"=>UNIACID,
            "type"=>0,
            "content"=>$log,
            "admin_id"=>$this->auth->id,
            "createtime"=>time()
        ];
        
        Db::name("bbfx_import_log")->insert($data);
        // 删除表格
        unlink($filePath);
        
        if($success == 0){
            __error("导入失败",['log_content'=>$log]);
        }
        if(empty($log)){
            $log = '已成功导入：'.$success.'条';
        }

        \app\admin\model\AdminLog::record("","",['id'=>implode(",",$order_ids)],'bbfx_order');

        __success("导入成功",['log_content'=>$log]);
    }
    
    
    public function newOrder(){
        // $new_order_id = Db::name("bbfx_base")->where(['uniacid'=>UNIACID])->value("new_order_id");

        $new_order_id = Cache::get("new_order_id_".UNIACID);
        $new_score_order_id = Cache::get("new_score_order_id_".UNIACID);

        $bbfx = Db::name("bbfx")->find();
        $order_id = Db::name("bbfx_order")->where(['uniacid'=>UNIACID,'is_pay'=>1])->order("pay_time desc")->value("id");
        $order_id = intval($order_id);
        $score_order_id = Db::name("bbfx_scoreshop_order")->where(['uniacid'=>UNIACID,'status'=>['>=',1]])->order("pay_time desc")->value("id");
        $score_order_id = intval($score_order_id);

        Cache::set("new_order_id_".UNIACID,$order_id);
        Cache::set("new_score_order_id_".UNIACID,$score_order_id);



        $where = array("uniacid"=>UNIACID);
        $list1 = Db::name("bbfx_site_message")->where($where)->field("id")->order('id desc')->select();
        if(empty($list1)) $list1 = [];
        $list2 = [];
        $result = ihttp_get("http://www.baibianfenxiao.com/api/message/getList");
        $result = json_decode($result['content'],true);
        if($result['code'] == 1){
            $list2 = $result['data']['list'];
        }
        
        $sids = array_column($list1,'id');
        $read_count1 = Db::name("bbfx_site_message_log")->where(["uniacid"=>UNIACID,'type'=>1,"admin_id"=>$this->auth->id,'pid'=>['in',$sids]])->count();
        $sids = array_column($list2,'id');
        $read_count2 = Db::name("bbfx_site_message_log")->where(["uniacid"=>UNIACID,'type'=>2,"admin_id"=>$this->auth->id,'pid'=>['in',$sids]])->count();
        $new_msg_count = count($list1) + count($list2) - $read_count1 - $read_count2;

        




        if(($new_order_id === $order_id || $order_id <= 0) && ($new_score_order_id === $score_order_id || $score_order_id <= 0)){
            __error("没有新订单！",['version'=>$bbfx['version'],'version_name'=>$bbfx['version_name'],'new_msg_count'=>$new_msg_count,'order_id'=>$order_id,'score_order_id'=>$score_order_id]);
        }
        
        // Db::name("bbfx_base")->where(['uniacid'=>UNIACID])->update(['new_order_id'=>$order_id]);
        
        
        __success("您有新订单！",['version'=>$bbfx['version'],'version_name'=>$bbfx['version_name'],'new_msg_count'=>$new_msg_count]);
    }

    public function extractData(){
        $params = $this->param();
        
        $order_id = intval($params['order_id']);
        $order = Db::name("bbfx_order")->where(['id'=>$order_id])->find();
        if(empty($order)){
            __error("订单不存在");
        }
        $order['order_trade_no'] = $this->model->getOrderTradeNo($order['order_no']);
        return ['order_id'=>$order_id,'order'=>$order,'params'=>$params];
    }
    
    public function print(){
        $extractData = $this->extractData();
        extract($extractData);
        
        $result = \app\common\model\bbfxshop\Printer::orderPrint($order['id']);
        if($result['code'] == 1){
            $data = ['id'=>$order['id'],'order_trade_no'=>$order['order_trade_no'],'order_no'=>$order['order_no'],'user_id'=>$order['user_id']];
            \app\admin\model\AdminLog::record("","",$data,'bbfx_order');
        }
        __result($result);
    }
    
    public function refund(){
        $extractData = $this->extractData();
        extract($extractData);
        if($order['is_pay'] != 1){
            __error("订单未支付");
        }
        
        if($order['refund_status'] == 1){
            __error("订单已退款");
        }
        if($order['order_source'] == 2){
            __error("云仓提货商品不支持退款");
        }
        if($order['order_source'] == 4 || $order['order_source'] == 5 || $order['order_source'] == 6){
            __error("该类型的订单不可退款");
        }
        if($order['gift_status'] == 1){
            __error("该订单礼品已被领取不可退款");
        }
        if($order['pintuan_miandan_status'] == 1){
            __error("拼团免单订单不支持重复退款");
        }
        
        $type = intval($params['type']);
         
        if($type == 1){
            $refund = Db::name("bbfx_order_refund")->where(['order_id'=>$order_id,'uniacid'=>UNIACID])->find();
            if(empty($refund)){
                $order_no = date('YmdHis').random(8,true);
                $data = array(
                    "uniacid"=>UNIACID,
                    "user_id"=>$order['user_id'],
                    "order_no"=>$order_no,
                    "money"=>$order['price'],
                    "order_id"=>$order_id,
                    "content"=>"平台退款",
                    "createtime"=>time()
                );

                if($order['is_hexiao'] == 1){
                    $data['mobile'] = $order['hexiao_mobile'];
                }
                else{
                    if(empty($order['delivery_mobile'])){
                        $data['mobile'] = $order['delivery_mobile'];
                    }
                }
                $refund_id = Db::name("bbfx_order_refund")->insertGetId($data);
        
                if(empty($refund_id)){
                    __error("退款失败");
                }
                Db::name("bbfx_order")->where(['id'=>$order_id])->update(['refund_status'=>0]);
            }
            else{
                if($refund['status'] == 1){
                    Db::name("bbfx_order")->where(['id'=>$order_id])->update(['refund_status'=>1]);
                    __error("退款失败");
                }
            }
            $status = 1;
        }
        else{
            $status = intval($params['status']);
        }
        
        $result = $this->model->refund($order_id,$status,$type);
        if($result['code'] == 1){
            $data = ['id'=>$order['id'],'order_trade_no'=>$order['order_trade_no'],'order_no'=>$order['order_no'],'user_id'=>$order['user_id'],'refund_status'=>$status];
            \app\admin\model\AdminLog::record("","",$data,'bbfx_order');
        }
        __result($result);
    }
    
    public function updateDeliver(){
        $extractData = $this->extractData();
        extract($extractData);
        if($order['is_pay'] != 1){
            __error("订单未支付");
        }
        if($order['refund_status'] != -1){
            __error("订单已申请售后");
        }
        if($order['status'] > 1){
            __error("订单已发货");
        }
        
        $delivery_username = $params['delivery_username'];
        $delivery_mobile = $params['delivery_mobile'];
        $delivery_address = $params['delivery_address'];
        $delivery_dz = $params['delivery_dz'];
        
        $data = array(
            "delivery_username"=>$delivery_username,
            "delivery_mobile"=>$delivery_mobile,
            "delivery_province"=>$delivery_dz[0],
            "delivery_city"=>$delivery_dz[1],
            "delivery_area"=>$delivery_dz[2],
            "delivery_street"=>$delivery_dz[3],
            "delivery_address"=>$delivery_address,
        );
        
        if(empty($data['delivery_username'])){
            __error("请填写收货人");
        }
        if(empty($data['delivery_mobile'])){
            __error("请填写收货人电话");
        }
        if(empty($data['delivery_province']) || empty($data['delivery_city']) || empty($data['delivery_area'])){
            __error("请选择地区");
        }
        if(empty($data['delivery_address'])){
            __error("请填写详细地址");
        }
        
        $res = Db::name("bbfx_order")->where(['id'=>$order['id']])->update($data);
        
        if($res){
            $data['id'] = $order['id'];
            $data1 = ['id'=>$order['id'],'order_trade_no'=>$order['order_trade_no'],'order_no'=>$order['order_no'],'user_id'=>$order['user_id']];
            $data = array_merge($data,$data1);
            \app\admin\model\AdminLog::record("","",$data,'bbfx_order');
            __success("修改成功");
        }
        else{
            __error("修改失败");
        }
    }
    
    public function updateRemarks(){
        $extractData = $this->extractData();
        extract($extractData);
        
        $content = $params['content'];
        
        $res = Db::name("bbfx_order")->where(['id'=>$order['id']])->update(['remarks'=>$content]);
        
        if($res){
            $data = ['id'=>$order['id'],'order_trade_no'=>$order['order_trade_no'],'order_no'=>$order['order_no'],'user_id'=>$order['user_id']];
            $data['remarks'] = $content;
            \app\admin\model\AdminLog::record("","",$data,'bbfx_order');
            __success("修改成功");
        }
        else{
            __error("修改失败");
        }
    }
    
    public function takeDelivery(){
        $extractData = $this->extractData();
        extract($extractData);
        $result = $this->model->takeDelivery($order['id']);
        if($result['code'] == 1){
            $data = ['id'=>$order['id'],'order_trade_no'=>$order['order_trade_no'],'order_no'=>$order['order_no'],'user_id'=>$order['user_id']];
            \app\admin\model\AdminLog::record("","",$data,'bbfx_order');
        }
        __result($result);
    }
    
    public function send(){
        $extractData = $this->extractData();
        extract($extractData);
        
        $result = $this->model->checkFahuo($order);
        if($result['code'] != 1){
           __result($result); 
        }
        
        if($order['order_type'] == 2){

            if($order['gift_status'] != -1){
                if(empty($order['delivery_mobile'])){
                    __error("该礼品订单商品收货信息不完整");
                }
            }
            
            $expressInfo = $params['expressInfo'];
            $deliver_type = intval($params['deliver_type']);
            if(empty($expressInfo)){
                __error("请填写快递信息");
            }
            
            foreach($expressInfo as $key => $val){
                if(empty($val['express_id'])){
                    __error("请选择快递公司");
                }
                if(empty($val['express_no'])){
                    __error("请填写快递单号");
                }
                if($deliver_type != 1 && empty($val['goods_id'])){
                    __error("请选择商品");
                }
                
            }
            
            if($order['status'] == 2){
                $res = true;
            }
            else if($order['status'] == 1){
                $res = Db::name("bbfx_order")->where(['id'=>$order['id'],'status'=>1])->update(['status'=>2]);
            }

            if($res){
                
                $udata = [];
                if($order['status'] == 1){
                    $udata = ['deliverytime'=>time()];
                }
                $udata['express'] = iserializer($expressInfo);
                $udata['deliver_type'] = $deliver_type;
                
                Db::name("bbfx_order")->where(['id'=>$order['id']])->update($udata);
                
                \app\common\model\bbfxshop\Message::sendShippingnoticeMsg($order['id']);
                
                \app\common\model\bbfxshop\Sms::sendOrderDeliveryNotice($order['id']);

                $this->model->sendGoods($order['id']);

                
                if($order['status'] == 1){
                    $this->model->sendGoods($order['id']);
                    $udata['status'] = 2;
                    $udata['id'] = $order['id'];
                }
                $udata1 = ['id'=>$order['id'],'order_trade_no'=>$order['order_trade_no'],'order_no'=>$order['order_no'],'user_id'=>$order['user_id']];
                $udata = array_merge($udata,$udata1);
                \app\admin\model\AdminLog::record("","",$udata,'bbfx_order');
                __success("发货成功");
            }
            else{
                __error("发货失败");
            }
        }
        else if($order['order_type'] == 1 || $order['order_type'] == 4){
            
            $res = $this->model->takeDelivery($order['id']);
            if(!empty($res) && $res['code'] == 1){
                Db::name("bbfx_order")->where(['id'=>$order['id']])->update(['deliverytime'=>time()]);
                $data = ['id'=>$order['id'],'order_trade_no'=>$order['order_trade_no'],'order_no'=>$order['order_no'],'user_id'=>$order['user_id']];
                \app\admin\model\AdminLog::record("","",$data,'bbfx_order');
                __success("发货成功");
            }
            else{
                 __error($res['message']);
            }
        }
        else{
            __error("商品类型错误");
        }
        
    }
    
    public function queryExpressDelivery(){
        $extractData = $this->extractData();
        extract($extractData);
        $express_no = $this->param("express_no/s");
        
        if($order['order_type'] == 2 && $order['delivery_method'] != 1){
            __error("不是快递订单");
        }
        if($order['status'] <= 1){
            __error("订单未发货");
        }
        $express = iunserializer($order['express']);
        $new_express_no = $express_no;
        if(!strstr($new_express_no, ':')){
            foreach ($express as $key => $val){
                if($val['express_no'] == $express_no && $val['express_name'] == '中通快递'){
                    $new_express_no = $express_no.":".mb_substr($order['delivery_mobile'], -4);
                }
            }
            unset($val);
        }
        
        $result = \app\common\model\bbfxshop\Delivery::queryExpressDelivery($new_express_no);
        if($result['code'] == 1){
            
            $res = $result['data'];
            foreach ($express as $key => &$val){
                if($val['express_no'] == $express_no){
                    $val['express_data'] = $res;
                }
            }
            unset($val);
            
            Db::name("bbfx_order")->where(['id'=>$order['id']])->update(['express'=>iserializer($express)]);
        }
        if($result['code'] == 1){
            $data = ['id'=>$order['id'],'order_trade_no'=>$order['order_trade_no'],'order_no'=>$order['order_no'],'user_id'=>$order['user_id']];
            \app\admin\model\AdminLog::record("","",$data,'bbfx_order');
        }
        __result($result);
    }

    public function getOrderHexiaoStoreList(){
        $order_id = $this->param("order_id/d");
        $order_goods = Db::name("bbfx_order_goods")->where(['order_id'=>$order_id,'uniacid'=>UNIACID])->field("id,goods_id")->select();
        if(empty($order_goods)){
            __error("订单信息错误");
        }
        $goods_ids = [];
        foreach ($order_goods as $key => &$val){
            $goods_ids[] = $val['goods_id'];
        }
        $list = $this->model->getOrderHexiaoStoreList($goods_ids);
        __success("操作成功",['list'=>$list]);
    }
    
    public function detail(){
        global $_W;
        $base = $_W['base'];
        $texts = $base['fenxiao']['texts'];
        $extractData = $this->extractData();
        extract($extractData);
        
        $order_goods = Db::name("bbfx_order_goods")->where(['order_id'=>$order['id'],'uniacid'=>UNIACID])->select();
        $goods_list = [];
        $goods_all = [];
        $serial_numbers = [];
        $goods_ids = [];
        foreach ($order_goods as $key => &$val){
            $goods_ids[] = $val['goods_id'];
            $goods_info = iunserializer($val['goods_info']);
            $goods_info['thumb'] = cdnurl($goods_info['thumb']);
            
            if($order['status'] == 3 && $order['order_type'] == 1){
                $serial_number = Db::name("bbfx_serial_number")->where(['pid'=>$val['id'],'uniacid'=>UNIACID])->field(['id','val','pid'])->select();
                if(empty($serial_number)) $serial_number = [];
                foreach ($serial_number as $k => &$v){
                    $v['goods'] = $goods_info;
                }
                unset($v);
                $serial_numbers = array_merge($serial_numbers,$serial_number);
            }
            
            $val['goods_info'] = $goods_info;
            $goods_info['total'] = $val['total'];
            $goods_list[$val['goods_id']] = $goods_info;
            $goods_all[] = $goods_info;
        }
        unset($val);
        $order['paytypeText'] = $this->model->getOrderPaytype($order);

        $levels = FenxiaoLevel::getLevels(1);
        
        $order['user'] = User::getUser($order['user_id'],false);
        if(!empty($order['user'])){
            $order['user']['levelname'] = "普通用户";
            if($order['user']['is_distributor'] == 1 && $order['user']['distributor_status'] == 1){
                $order['user']['levelname'] = $levels[$order['user']['level']]['title'];
            }
        }
        
	    $order['typeText'] = $this->model->getOrderType($order['order_type']);
        $order['statusText'] = $this->model->getOrderStatus($order,1);
        $order['refund_statusText'] = $this->model->getOrderRefundStatus($order['refund_status']);
        if($order['deliverytime'] > 0){
            $order['deliverytime'] = date("Y-m-d H:i:s",$order['deliverytime']);
        }
        else{
            $order['deliverytime'] = "";
        }
        if($order['completetime'] > 0){
            $order['completetime'] = date("Y-m-d H:i:s",$order['completetime']);
        }
        else{
            $order['completetime'] = "";
        }
        $order['createtime'] = date("Y-m-d H:i:s",$order['createtime']);
        $order['pay_time'] = date("Y-m-d H:i:s",$order['pay_time']);
        
        $order['serial_numbers'] = $serial_numbers;
        
        
        $order_commission = Db::name("bbfx_fenxiao_order")->where(['uniacid'=>UNIACID,'user_id'=>['>',0],'money_type'=>['in',[1,3]],'order_id'=>$order_id])->sum("money");
        $order['order_commission'] = round($order_commission,2);
        $order['goods_profit'] = round($order['price'] - $order_commission,2);
        
        $order_profit = $order['price'] - $order['cost_price'] - $order_commission;
	    if($order['delivery_method'] == 1 && $order['order_type'] == 2){
	        $order_profit -= $order['express_fee'];
	    }
	    $order['order_profit'] = max(0,round($order_profit,2));

        if($order['paytype'] == 6){
            $order['pay_voucher'] = cdnurl(Db::name("bbfx_pay_order")->where(['uniacid'=>UNIACID,'paytype'=>6,'order_no'=>$order['order_no']])->order("id desc")->value("pay_voucher"));
        }
        
        if($order['refund_status'] != -1){
            
            $refund = Db::name("bbfx_order_refund")->where("order_id",$order['id'])->find();
            if(!empty($refund)){
                $refund['images'] = iunserializer($refund['images']);
                foreach ($refund['images'] as $key => &$val){
                    $val = cdnurl($val);
                }
                unset($val);
                $refund['createtime'] = date("Y-m-d H:i:s",$refund['createtime']);
                $order['refund'] = $refund;
            }
        }
        
        if((($order['order_type'] == 2 || $order['order_type'] == 4) && $order['is_hexiao'] == 1) || $order['order_type'] == 3){
            $hexiao_record = Db::name("bbfx_order_hexiao_record")->where(['uniacid'=>UNIACID,'order_id'=>$order['id']])->select();
            foreach ($hexiao_record as $key => &$val){
                $val['info'] = iunserializer($val['info']);
                if($val['user_id'] > 0){
                    $val['info']['user']['avatar'] = cdnurl($val['info']['user']['avatar']);
                }
                $val['createtime'] = date("Y-m-d H:i:s",$val['createtime']);
            }
            unset($val);
            $order['hexiao_record'] = $hexiao_record;
            $hexiao_store = iunserializer($order['hexiao_store']);
            if(!empty($hexiao_store)){
                $hexiao_store['logo'] = cdnurl($hexiao_store['logo']);
                $order['hexiao_store'] = $hexiao_store;
            }
            else{
                $order['hexiao_store'] = null;
            }
        }

        if($order['order_type'] == 3){
            $order_yuyue = Db::name("bbfx_order_yuyue")->where(['uniacid'=>UNIACID,'order_id'=>$order['id']])->order("id desc")->select();
            if(!empty($order_yuyue)){

                foreach ($order_yuyue as $key => &$val){
                    $val['createtime'] = date("Y-m-d H:i:s",$val['createtime']);
                    $val['yy_time'] = date("Y-m-d",$val['yy_stime'])." ".date('H:i',$val['yy_stime']).' - '.date('H:i',$val['yy_etime']);
                    if($val['hx_time'] > 0){
                        $val['hx_time'] = date("Y-m-d H:i:s",$val['hx_time']);
                    }
                    else{
                        $val['hx_time'] = "";
                    }
                }
                unset($val);
            }
            $order['order_yuyue'] = $order_yuyue;
        }
        
        $order['extend'] = iunserializer($order['extend']);
        
        $result = ['order'=>$order,'order_goods'=>$order_goods];
        
        if($order['order_type'] == 2){
            $express_list = Db::name("bbfx_express")->where(['status'=>1])->field(['id','name','coding'])->order('sort desc')->select();
            $result['express_list'] = $express_list;
        }
        if($order['order_type'] == 2 && $order['status'] > 1){
            $express = iunserializer($order['express']);
            foreach ($express as $key => &$val){
                $val['deliverytime'] = $order['deliverytime'];
                if($order['deliver_type'] == 1){
                    $val['goods'] = $goods_all;
                }
                else if($order['deliver_type'] == 2 || $order['deliver_type'] == 3){
                    $val['goods'] = [$goods_list[$val['goods_id']]];
                }
            }
            unset($val);
            $result['express'] = $express;
        }

        if($order['is_hexiao'] == 1 && $order['status'] < 3){
            $hexiao_store_list = $this->model->getOrderHexiaoStoreList($goods_ids);
            $result['hexiao_store_list'] = $hexiao_store_list;
        }
        
        $fenxiao_order_list = Db::name("bbfx_fenxiao_order")->where(['uniacid'=>UNIACID,'order_type'=>0,'user_id'=>['>',0],'order_id'=>$order_id])->order('type asc')->select();
        if(empty($fenxiao_order_list)){
            $fenxiao_order_list = [];
        }
        
        $texts = $_W['base']['fenxiao']['texts'];
        
        foreach ($fenxiao_order_list as $key => &$val){
            $user = Db::name("bbfx_user")->where(['id'=>$val['user_id']])->field(['id','avatar','nickname','level','sup_uid'])->find();
            $sup_user = Db::name("bbfx_user")->where(['id'=>$user['sup_uid']])->field(['id','avatar','nickname','level','sup_uid'])->find();
            if(!empty($user)){
                $user['level_name'] = $levels[$val['level']]['title'];
                // $user['level_name'] = $levels[$user['level']]['title'];
                $user['avatar'] = cdnurl($user['avatar']);
                $val['user'] = $user;
            }
            if(!empty($sup_user)){
                $sup_user['level_name'] = $levels[$sup_user['level']]['title'];
                $sup_user['avatar'] = cdnurl($sup_user['avatar']);
                $val['sup_user'] = $sup_user;
            }
            
	        $val['typeText']= Fenxiao::getTypeText($val['type'],$val['money_type']);
	        if($val['money_type'] == 2){
                $val['moneyText'] = "+".floatval($val['money']).$base['texts']['score_unit'];
            }
            else{
                $val['moneyText'] = "+".floatval($val['money']).$texts['yuan'];
            }
        }
        unset($val);
        
        $result['fenxiao_order_list'] = $fenxiao_order_list;
        
        __success("操作成功",$result);
    }
    
    public function hexiao(){
        $store_id = $this->param('store_id/d');
        $extractData = $this->extractData();
        extract($extractData);
        $result = $this->model->hexiao($order_id,$store_id);
        if($result['code'] == 1){
            $data = ['id'=>$order['id'],'order_trade_no'=>$order['order_trade_no'],'order_no'=>$order['order_no'],'user_id'=>$order['user_id']];
            \app\admin\model\AdminLog::record("","",$data,'bbfx_order');
        }
        __result($result);
    }

    public function cashShenhe(){
        $extractData = $this->extractData();
        extract($extractData);
        $status = $this->param('status/d');
        if($status != 1) $status = 2;
        
        $result = $this->model->cashPay($order_id,$status);
        if($result['code'] == 1){
            $data = ['id'=>$order['id'],'order_trade_no'=>$order['order_trade_no'],'order_no'=>$order['order_no'],'user_id'=>$order['user_id']];
            \app\admin\model\AdminLog::record("","",$data,'bbfx_order');
        }
        __result($result);
    }
    
    public function close(){
        $extractData = $this->extractData();
        extract($extractData);
        
        $result = $this->model->closeOrder($order_id);
        if($result['code'] == 1){
            $data = ['id'=>$order['id'],'order_trade_no'=>$order['order_trade_no'],'order_no'=>$order['order_no'],'user_id'=>$order['user_id']];
            \app\admin\model\AdminLog::record("","",$data,'bbfx_order');
        }
        __result($result);
    }
    
    public function createElectronicWaybill(){
        $extractData = $this->extractData();
        extract($extractData);
        $result = \app\common\model\bbfxshop\ElectronicWaybill::createWaybill($order_id);
        if($result['code'] == 1){
            $data = ['id'=>$order['id'],'order_trade_no'=>$order['order_trade_no'],'order_no'=>$order['order_no'],'user_id'=>$order['user_id']];
            \app\admin\model\AdminLog::record("","",$data,'bbfx_order');
        }
        __result($result);
    }
    
    public function list(){
        $params = $this->param();
        
        
        $pindex = max(1, intval($params["page"]));
        $psize = intval($params["limit"])?intval($params["limit"]):10;
        
        $where = ["a.uniacid"=>UNIACID,'a.order_source'=>['<>',8]];
        
        $keyword = trim($params['keyword']);
        $startTime = trim($params['startTime']);
        $endTime = trim($params['endTime']);
        $hx_startTime = trim($params['hx_startTime']);
        $hx_endTime = trim($params['hx_endTime']);
        $status = intval($params['status']);
        $paytype = intval($params['paytype']);
        $store_id = intval($params['store_id']);
        
        $refund_status = intval($params['refund_status']);
        $type = intval($params['type']);
        $mid = intval($params['mid']);
        $min = round($params['min_price'],2);
        $max = round($params['max_price'],2);
        $sup_uid = intval($params['sup_uid']);
        if($status != -1){
            if($status == 4){
                 $where['a.status'] = ['>=',1];
                if($refund_status != -1){
                    $where['a.refund_status'] = $refund_status;
                }
                else{
                    $where['a.refund_status'] = ['neq',-1];
                }
            }
            else if($status == 9){
                $where['a.status'] = 1;
                $where['a.is_hexiao'] = 1;
            }
            else{
                $where['a.status'] = $status;
            }
        }
        if($store_id > 0){
            $where['a.store_id'] = $store_id;
            $where['a.is_hexiao'] = 1;
        }

        if($this->order_type > 0){
            $where['a.order_type'] = $this->order_type;
        }
        else{
            $where['a.order_type'] = ['in',[1,2,4]];
        }
        
        if($keyword){
            if($type == 1){
                $where['a.order_no'] = ['like',"%".$keyword."%"];
            }
            else if($type == 2){
                $where['b.nickname'] = ['like',"%".$keyword."%"];
            }
            else if($type == 3){
                $where['a.delivery_username'] = ['like',"%".$keyword."%"];
            }
            else if($type == 4){
                $where['a.user_id'] = intval($keyword);
            }
            else if($type == 5){
                $where['a.goods_info'] = ['like','%'.$keyword.'%'];
            }
            else if($type == 6){
                $uids = User::getLevel1UserIds(intval($keyword));
                $where['a.user_id'] = ['in',$uids];
            }
            else if($type == 7){
                $where['a.express'] = ['like','%'.$keyword.'%'];
            }
            else if($type == 8){
                $where['a.delivery_mobile'] = $keyword;
            }
        }
        if($paytype > 0){
            $where['a.paytype'] = $paytype;
        }
        
        if($mid > 0){
            $where['a.mid'] = $mid;
        }
        
        $whereTime = [];
        if($startTime){
            $startTime = strtotime($startTime." 00:00:00");
            $where['a.createtime'] = ['>=',$startTime];
        } 
        
        if($endTime){
            $endTime = strtotime($endTime." 23:59:59");
            $whereTime['a.createtime'] = ['<=',$endTime];
        }
        if($hx_startTime && $hx_endTime){
            $where['a.is_hexiao'] = 1;
            $where['a.completetime'] = ['between',[strtotime($hx_startTime." 00:00:00"),strtotime($hx_endTime." 00:00:00")]];
        }
        else if(!empty($hx_startTime) && empty($hx_startTime)){
            $where['a.is_hexiao'] = 1;
            $where['a.completetime'] = ['>',strtotime($hx_startTime." 00:00:00")];
        }
        else if(empty($hx_startTime) && !empty($hx_endTime)){
            $where['a.is_hexiao'] = 1;
            $where['a.completetime'] = ['<',strtotime($hx_endTime." 00:00:00")];
        }

        if($min > 0){
            $where['a.price'] = ['>=',$min];
        }
        if($max > 0){
            $whereTime['a.price'] = ['<=',$max];
        }
        $export = intval($params['export']); 
        $order_goods_all = [];
        $sup_user_all = [];
        $order_commission_all = [];
        $merchant_all = [];
        $store_all = [];
        $pay_voucher_all = [];
        if($export == 1){
            $this->exportBatch();
            $list = Db::name("bbfx_order")->alias("a")->join("bbfx_user b","a.user_id=b.id")->where($where)->where($whereTime)->field('a.id,a.user_id,a.price,a.repurchase_currency,a.score,a.balance,a.status,a.is_pay,a.paytype,a.total_price,a.mid,a.store_id,a.pay_time,a.createtime,a.is_electronic_waybill_print,a.order_type,a.refund_status,a.extend,a.one_share,a.cost_price,a.is_hexiao,a.express,a.order_no,a.delivery_username,a.delivery_mobile,a.delivery_province,a.delivery_city,a.delivery_area,a.delivery_address,a.extend,a.remarks,b.avatar,b.nickname')->order('a.createtime desc')->select();
        }
        else{
            $list = Db::name("bbfx_order")->alias("a")->join("bbfx_user b","a.user_id=b.id")->where($where)->where($whereTime)->field('a.*,b.avatar,b.nickname')->order('a.createtime desc')->limit(($pindex - 1) * $psize,$psize)->select();
        }

        if(!empty($list)){
            $oids = [];
            $one_shares = [];
            $mids = [];
            $store_ids = [];
            $order_nos = [];
            foreach ($list as $key => $val){
                $oids[] = $val['id'];
                if(!in_array($val['one_share'],$one_shares)){
                    $one_shares[] = $val['one_share'];
                }
                if($val['mid'] > 0 && !in_array($val['mid'],$mids)){
                    $mids[] = $val['mid'];
                }
                if($val['store_id'] > 0 && !in_array($val['store_id'],$store_ids)){
                    $store_ids[] = $val['store_id'];
                }
                if($val['paytype'] == 6){
                    $order_nos[] = $val['order_no'];
                }
            }
            $sup_user_all_list = Db::name('bbfx_user')->where(['id'=>['in',$one_shares]])->field("id,nickname,avatar")->select();
            $order_goods_list = Db::name("bbfx_order_goods")->where(["uniacid"=>UNIACID,"order_id"=>['in',$oids]])->field("id,order_id,goods_info,total,price,cost_price,sku_id,sku_name,sku")->select();
            $order_commission_all = Db::name("bbfx_fenxiao_order")->where(['uniacid'=>UNIACID,'user_id'=>['>',0],'money_type'=>['in',[1,3]],'order_id'=>['in',$oids]])->field("id,order_id,sum(money) as money")->group('order_id')->select();
            if(!empty($order_commission_all)){
                $order_commission_all = array_skey($order_commission_all,"order_id");
            }
            foreach ($sup_user_all_list as $item){
                $sup_user_all[$item['id']] = $item;
            }
            
            foreach ($order_goods_list as $item){
                if(empty($order_goods_all[$item['order_id']])){
                    $order_goods_all[$item['order_id']] = [];
                }
                $order_goods_all[$item['order_id']][] = $item;
            }
            
            if(!empty($mids)){
                $merchant_list = Db::name("bbfx_merchant")->where(['id'=>['in',$mids]])->field("id,name")->select();
                foreach ($merchant_list as $item){
                    $merchant_all[$item['id']] = $item['name'];
                }
            }
            
            if(!empty($store_ids)){
                $store_list = Db::name("bbfx_store")->where(['id'=>['in',$store_ids]])->field("id,name")->select();
                foreach ($store_list as $item){
                    $store_all[$item['id']] = $item['name'];
                }
            }
            
            if(!empty($order_nos)){
                $pay_voucher_list = Db::name("bbfx_pay_order")->where(['uniacid'=>UNIACID,'paytype'=>6,'order_no'=>['in',$order_nos]])->field("order_no,pay_voucher")->select();
                foreach ($pay_voucher_list as $item){
                    $pay_voucher_all[$item['order_no']] = cdnurl($item['pay_voucher']);
                }
            }
        }
    	
    	$export_list = [];
    	foreach($list as $key => &$val){
    	    
    	    if($val['mid'] > 0){
    	        $val['merchant_name'] = isset($merchant_all[$val['mid']]) ? $merchant_all[$val['mid']] : "";
    	    }
    	    else{
    	        $val['merchant_name'] = "";
    	    }
    	    
    	    if($val['store_id'] > 0){
    	       $val['store_name'] = isset($store_all[$val['store_id']]) ? $store_all[$val['store_id']] : "";
    	    }
    	    else{
    	        $val['store_name'] = "";
    	    }
    	    
    	    $val['avatar'] = cdnurl($val['avatar']);

    	    $order_goods = isset($order_goods_all[$val['id']]) ? $order_goods_all[$val['id']] : [];
            $sup_user = isset($sup_user_all[$val['one_share']]) ? $sup_user_all[$val['one_share']] : [];
            $order_commission = isset($order_commission_all[$val['id']]['money']) ? round($order_commission_all[$val['id']]['money'],2) : 0;
            
            
    	    foreach ($order_goods as $k => &$v){
    	        $goods_info = iunserializer($v['goods_info']);
    	        unset($v['goods_info']);
    	        $goods_info['thumb'] = cdnurl($goods_info['thumb']);
    	        $v['goods'] = [
    	            'id'=>$goods_info['id'],
    	            'title'=>$goods_info['title'],
    	            'thumb'=>$goods_info['thumb'],
    	            'price'=>$goods_info['price'],
    	            'product_code'=>$goods_info['product_code'],
    	            'sku_id'=>$goods_info['sku_id'],
    	            'sku_name'=>$goods_info['sku_name'],
    	            'sku'=>$goods_info['sku'],
    	        ];
    	    }
    	    unset($v);
    	    $val['order_goods'] = $order_goods;
    	    $val['paytypeText'] = "";
    	    if($val['is_pay'] == 1){
    	        $val['pay_time'] = date("Y-m-d H:i:s",$val['pay_time']);
    	        $val['paytypeText'] = $this->model->getOrderPaytype($val);
    	    }
    	    else{
    	        $val['pay_time'] = "";
    	    }
    	    
    	    if($val['is_electronic_waybill_print'] == 1){
    	        $extend = iunserializer($val['extend']);
                $expressPrintTemplate = str_replace("kg "," ",$extend['express']['PrintTemplate']);
    	        $val['expressPrintTemplate'] = $expressPrintTemplate;
    	    }
    	     
    	    $val['createtime'] = date("Y-m-d H:i:s",$val['createtime']);
    	    
    	    $val['typeText'] = $this->model->getOrderType($val['order_type']);
    	    $val['refund_statusText'] = $this->model->getOrderRefundStatus($val['refund_status']);
    	    $val['statusText'] = $this->model->getOrderStatus($val);
    	    
    	    
    	    if(!empty($sup_user)){
    	        $sup_user['avatar'] = cdnurl($sup_user['avatar']);
    	        $val['sup_user'] = $sup_user;
    	    }
    	    
    	    
    	    $order_profit = $val['price'] - $val['cost_price'] - $order_commission;
    	    if($val['delivery_method'] == 1 && $val['order_type'] == 2){
    	        $order_profit -= $val['express_fee'];
    	    }
    	    $val['order_profit'] = max(0,round($order_profit,2));

            if($val['order_type'] == 2 && $val['is_hexiao'] == 0 && $val['status'] > 1){
                $val['express'] = iunserializer($val['express']);
            }
            if($val['paytype'] == 6){
                $val['pay_voucher'] = isset($pay_voucher_all[$val['order_no']]) ? $pay_voucher_all[$val['order_no']] : '';
            }

            $extend = iunserializer($val['extend']);
    	    
    	    if($export == 1){
    	        
    	        $delivery = $val['delivery_username']." ".$val['delivery_mobile'].','.$val['delivery_province'].$val['delivery_city'].$val['delivery_area'].$val['delivery_street'].$val['delivery_address'];
    	        if(empty($val['delivery_mobile'])){
                    $delivery = '';
                }
    	        $sup_user = "总店";
    	        if(!empty($val['sup_user'])){
    	            $sup_user = "(ID:".$val['sup_user']['id'].")".$val['sup_user']['nickname'];
    	        }

                $form_list = [];
                foreach($extend['form'] as $k => $v){
                    $form_list[] = $v['label']."：".$v['value'];
                }
                $order_form = implode("，",$form_list);
    	        
    	        foreach ($order_goods as $k => $v){
    	            
    	            $profit_amount = max(0,round($v['price'] - $v['cost_price'],2));
    	            
        	        $goods = $v['goods'];

                    $product_code = $goods['product_code'];
                    if(!empty($goods['sku'])){
                        $product_code = $goods['sku']['product_code'];
                    }

        	        $export_list[] = array(
        	            $val['id'],
        	            $val['order_no'],
        	            $val['merchant_name'],
        	            $val['store_name'],
        	            "(ID:{$val['user_id']})".$val['nickname'],
        	            $sup_user,
        	            $val['price'],
        	            $val['order_profit'],
        	            $goods['title'],
                        $product_code,
        	            $v['price'],
        	            $v['total'],
        	            $delivery,
        	            $val['typeText'],
        	            $val['statusText'],
        	            $val['refund_statusText'],
        	            $val['remarks'],
        	            $order_form,
        	            $val['createtime']
        	        );
        	    }
        	    
    	    }
    	}
        unset($val);
    	
    	if($export == 1){
    	    $headArr = ["订单ID","订单编号","所属商户","核销门店","用户信息","推荐人","订单金额","利润金额","商品名称","商品编码","商品金额","商品数量","收货信息","订单类型","订单状态","退款状态","订单备注","提交表单","下单时间"];
    	    $result = \app\common\model\PhpOffice::excelExport("order-".date("Y-m-d"),$headArr,$export_list,['mergek'=>0,'merges'=>[0,1,2,3,4,5,6,7,12,13,14,15,16,17,18]]);
    	}
      
        $total = Db::name("bbfx_order")->alias("a")->join("bbfx_user b","a.user_id=b.id")->where($where)->where($whereTime)->count();
    	
    	__success("操作成功",['total'=>$total,'list'=>$list]);
    }
    
    public function exportBatch(){
        $params = $this->param();
        
        $where = ["a.uniacid"=>UNIACID,'a.order_source'=>['<>',8]];
        
        $keyword = trim($params['keyword']);
        $startTime = trim($params['startTime']);
        $endTime = trim($params['endTime']);
        $hx_startTime = trim($params['hx_startTime']);
        $hx_endTime = trim($params['hx_endTime']);
        $status = intval($params['status']);
        $paytype = intval($params['paytype']);
        $store_id = intval($params['store_id']);
        
        $refund_status = intval($params['refund_status']);
        $type = intval($params['type']);
        $mid = intval($params['mid']);
        $min = round($params['min_price'],2);
        $max = round($params['max_price'],2);
        $sup_uid = intval($params['sup_uid']);
        
        if($status != -1){
            if($status == 4){
                 $where['a.status'] = ['>=',1];
                if($refund_status != -1){
                    $where['a.refund_status'] = $refund_status;
                }
                else{
                    $where['a.refund_status'] = ['neq',-1];
                }
            }
            else if($status == 9){
                $where['a.status'] = 1;
                $where['a.is_hexiao'] = 1;
            }
            else{
                $where['a.status'] = $status;
            }
        }
        if($store_id > 0){
            $where['a.store_id'] = $store_id;
            $where['a.is_hexiao'] = 1;
        }
        
        if($keyword){
            if($type == 1){
                $where['a.order_no'] = ['like',"%".$keyword."%"];
            }
            else if($type == 2){
                $where['b.nickname'] = ['like',"%".$keyword."%"];
            }
            else if($type == 3){
                $where['a.delivery_username'] = ['like',"%".$keyword."%"];
            }
            else if($type == 4){
                $where['a.user_id'] = intval($keyword);
            }
            else if($type == 5){
                $where['a.goods_info'] = ['like','%'.$keyword.'%'];
            }
            else if($type == 6){
                $uids = User::getLevel1UserIds(intval($keyword));
                $where['a.user_id'] = ['in',$uids];
            }
            else if($type == 7){
                $where['a.express'] = ['like','%'.$keyword.'%'];
            }
            else if($type == 8){
                $where['a.delivery_mobile'] = $keyword;
            }
        }
        if($paytype > 0){
            $where['a.paytype'] = $paytype;
        }
        
        if($mid > 0){
            $where['a.mid'] = $mid;
        }
        
        $whereTime = [];
        if($startTime){
            $startTime = strtotime($startTime." 00:00:00");
            $where['a.createtime'] = ['>=',$startTime];
        } 
        
        if($endTime){
            $endTime = strtotime($endTime." 23:59:59");
            $whereTime['a.createtime'] = ['<=',$endTime];
        }

        if($hx_startTime && $hx_endTime){
            $where['a.is_hexiao'] = 1;
            $where['a.completetime'] = ['between',[strtotime($hx_startTime." 00:00:00"),strtotime($hx_endTime." 00:00:00")]];
        }
        else if(!empty($hx_startTime) && empty($hx_startTime)){
            $where['a.is_hexiao'] = 1;
            $where['a.completetime'] = ['>',strtotime($hx_startTime." 00:00:00")];
        }
        else if(empty($hx_startTime) && !empty($hx_endTime)){
            $where['a.is_hexiao'] = 1;
            $where['a.completetime'] = ['<',strtotime($hx_endTime." 00:00:00")];
        }

        if($min > 0){
            $where['a.price'] = ['>=',$min];
        }
        if($max > 0){
            $whereTime['a.price'] = ['<=',$max];
        }
        
        $total = Db::name("bbfx_order")->alias("a")->join("bbfx_user b","a.user_id=b.id")->where($where)->where($whereTime)->count();
        
        if($total == 0){
            __error("没有可导出的数据");
        }
        
        $batch_size = 1000;
        $total_batches = ceil($total / $batch_size);
        
        $export_list = [];
        $headArr = ["订单ID","订单编号","所属商户","核销门店","用户信息","推荐人","订单金额","支付方式","利润金额","商品名称","商品编码","商品金额","商品数量","收货信息","订单类型","订单状态","退款状态","订单备注","提交表单","下单时间"];
        
        for($batch = 0; $batch < $total_batches; $batch++){
            $offset = $batch * $batch_size;
            
            $list = Db::name("bbfx_order")->alias("a")
                ->join("bbfx_user b","a.user_id=b.id")
                ->where($where)
                ->where($whereTime)
                ->field('a.id,a.user_id,a.price,a.repurchase_currency,a.score,a.balance,a.status,a.is_pay,a.paytype,a.total_price,a.mid,a.store_id,a.pay_time,a.createtime,a.is_electronic_waybill_print,a.order_type,a.refund_status,a.extend,a.one_share,a.cost_price,a.is_hexiao,a.express,a.order_no,a.delivery_username,a.delivery_mobile,a.delivery_province,a.delivery_city,a.delivery_area,a.delivery_address,a.extend,a.remarks,b.avatar,b.nickname')
                ->order('a.createtime desc')
                ->limit($offset, $batch_size)
                ->select();
            
            if(!empty($list)){
                $oids = [];
                $one_shares = [];
                $mids = [];
                $store_ids = [];
                $order_nos = [];
                foreach ($list as $key => $val){
                    $oids[] = $val['id'];
                    if(!in_array($val['one_share'],$one_shares)){
                        $one_shares[] = $val['one_share'];
                    }
                    if($val['mid'] > 0 && !in_array($val['mid'],$mids)){
                        $mids[] = $val['mid'];
                    }
                    if($val['store_id'] > 0 && !in_array($val['store_id'],$store_ids)){
                        $store_ids[] = $val['store_id'];
                    }
                    if($val['paytype'] == 6){
                        $order_nos[] = $val['order_no'];
                    }
                }
                
                $sup_user_all = [];
                $order_goods_all = [];
                $order_commission_all = [];
                $merchant_all = [];
                $store_all = [];
                $pay_voucher_all = [];
                
                $sup_user_all_list = Db::name('bbfx_user')->where(['id'=>['in',$one_shares]])->field("id,nickname,avatar")->select();
                $order_goods_list = Db::name("bbfx_order_goods")->where(["uniacid"=>UNIACID,"order_id"=>['in',$oids]])->field("id,order_id,goods_info,total,price,cost_price,sku_id,sku_name,sku")->select();
                $order_commission_list = Db::name("bbfx_fenxiao_order")->where(['uniacid'=>UNIACID,'user_id'=>['>',0],'money_type'=>['in',[1,3]],'order_id'=>['in',$oids]])->field("id,order_id,sum(money) as money")->group('order_id')->select();
                
                foreach ($sup_user_all_list as $item){
                    $sup_user_all[$item['id']] = $item;
                }
                
                foreach ($order_goods_list as $item){
                    if(empty($order_goods_all[$item['order_id']])){
                        $order_goods_all[$item['order_id']] = [];
                    }
                    $order_goods_all[$item['order_id']][] = $item;
                }
                
                if(!empty($order_commission_list)){
                    $order_commission_all = array_skey($order_commission_list,"order_id");
                }
                
                if(!empty($mids)){
                    $merchant_list = Db::name("bbfx_merchant")->where(['id'=>['in',$mids]])->field("id,name")->select();
                    foreach ($merchant_list as $item){
                        $merchant_all[$item['id']] = $item['name'];
                    }
                }
                
                if(!empty($store_ids)){
                    $store_list = Db::name("bbfx_store")->where(['id'=>['in',$store_ids]])->field("id,name")->select();
                    foreach ($store_list as $item){
                        $store_all[$item['id']] = $item['name'];
                    }
                }
                
                if(!empty($order_nos)){
                    $pay_voucher_list = Db::name("bbfx_pay_order")->where(['uniacid'=>UNIACID,'order_no'=>['in',$order_nos]])->field("order_no,pay_voucher")->select();
                    foreach ($pay_voucher_list as $item){
                        $pay_voucher_all[$item['order_no']] = cdnurl($item['pay_voucher']);
                    }
                }
                
                foreach($list as $key => $val){
                    $val['merchant_name'] = isset($merchant_all[$val['mid']]) ? $merchant_all[$val['mid']] : "";
                    $val['store_name'] = isset($store_all[$val['store_id']]) ? $store_all[$val['store_id']] : "";
                    $val['avatar'] = cdnurl($val['avatar']);
                    
                    $order_goods = isset($order_goods_all[$val['id']]) ? $order_goods_all[$val['id']] : [];
                    $sup_user = isset($sup_user_all[$val['one_share']]) ? $sup_user_all[$val['one_share']] : [];
                    $order_commission = isset($order_commission_all[$val['id']]['money']) ? round($order_commission_all[$val['id']]['money'],2) : 0;
                    
                    foreach ($order_goods as $k => &$v){
                        $goods_info = iunserializer($v['goods_info']);
                        $goods_info['thumb'] = cdnurl($goods_info['thumb']);
                        $v['goods'] = [
                            'id'=>$goods_info['id'],
                            'title'=>$goods_info['title'],
                            'thumb'=>$goods_info['thumb'],
                            'price'=>$goods_info['price'],
                            'product_code'=>$goods_info['product_code'],
                            'sku_id'=>$goods_info['sku_id'],
                            'sku_name'=>$goods_info['sku_name'],
                            'sku'=>$goods_info['sku'],
                        ];
                    }
                    unset($v);
                    
                    $val['paytypeText'] = "";
                    if($val['is_pay'] == 1){
                        $val['pay_time'] = date("Y-m-d H:i:s",$val['pay_time']);
                        $val['paytypeText'] = $this->model->getOrderPaytype($val);
                    }
                    else{
                        $val['pay_time'] = "";
                    }
                    
                    $val['createtime'] = date("Y-m-d H:i:s",$val['createtime']);
                    $val['typeText'] = $this->model->getOrderType($val['order_type']);
                    $val['refund_statusText'] = $this->model->getOrderRefundStatus($val['refund_status']);
                    $val['statusText'] = $this->model->getOrderStatus($val);
                    
                    if(!empty($sup_user)){
                        $sup_user['avatar'] = cdnurl($sup_user['avatar']);
                        $val['sup_user'] = $sup_user;
                    }
                    
                    $order_profit = $val['price'] - $val['cost_price'] - $order_commission;
                    if($val['delivery_method'] == 1 && $val['order_type'] == 2){
                        $order_profit -= $val['express_fee'];
                    }
                    $val['order_profit'] = max(0,round($order_profit,2));
                    
                    $extend = iunserializer($val['extend']);
                    
                    $delivery = $val['delivery_username']." ".$val['delivery_mobile'].','.$val['delivery_province'].$val['delivery_city'].$val['delivery_area'].$val['delivery_street'].$val['delivery_address'];
                    if(empty($val['delivery_mobile'])){
                        $delivery = '';
                    }
                    
                    $sup_user_text = "总店";
                    if(!empty($val['sup_user'])){
                        $sup_user_text = "(ID:".$val['sup_user']['id'].")".$val['sup_user']['nickname'];
                    }
                    
                    $form_list = [];
                    if(!empty($extend['form'])){
                        foreach($extend['form'] as $k => $v){
                            $form_list[] = $v['label']."：".$v['value'];
                        }
                    }
                    $order_form = implode("，",$form_list);
                    
                    foreach ($order_goods as $k => $v){
                        $goods = $v['goods'];
                        
                        $product_code = $goods['product_code'];
                        if(!empty($goods['sku'])){
                            $product_code = $goods['sku']['product_code'];
                        }
                        
                        $export_list[] = array(
                            $val['id'],
                            $val['order_no'],
                            $val['merchant_name'],
                            $val['store_name'],
                            "(ID:{$val['user_id']})".$val['nickname'],
                            $sup_user_text,
                            $val['price'],
                            $val['paytypeText'],
                            $val['order_profit'],
                            $goods['title'],
                            $product_code,
                            $v['price'],
                            $v['total'],
                            $delivery,
                            $val['typeText'],
                            $val['statusText'],
                            $val['refund_statusText'],
                            $val['remarks'],
                            $order_form,
                            $val['createtime']
                        );
                    }
                }
            }
        }
        
        $result = \app\common\model\PhpOffice::excelExport("order-".date("Y-m-d"),$headArr,$export_list,['mergek'=>0,'merges'=>[0,1,2,3,4,5,6,7,12,13,14,15,16,17,18]]);
    }
    
    public function exportCsv(){
        try {
            @set_time_limit(0);
            @ini_set('memory_limit', '512M');
            @ini_set('display_errors', 0);
            @ini_set('log_errors', 1);
            
            if (ob_get_level() > 0) {
                ob_end_clean();
            }
            
            $params = $this->param();
            
            $where = ["a.uniacid"=>UNIACID,'a.order_source'=>['<>',8]];
            
            $keyword = trim($params['keyword']);
            $startTime = trim($params['startTime']);
            $endTime = trim($params['endTime']);
            $hx_startTime = trim($params['hx_startTime']);
            $hx_endTime = trim($params['hx_endTime']);
            
            $status = intval($params['status']);
            $paytype = intval($params['paytype']);
            $store_id = intval($params['store_id']);
            
            $refund_status = intval($params['refund_status']);
            $type = intval($params['type']);
            $mid = intval($params['mid']);
            $min = round($params['min_price'],2);
            $max = round($params['max_price'],2);
            $sup_uid = intval($params['sup_uid']);
            
            if($status != -1){
                if($status == 4){
                     $where['a.status'] = ['>=',1];
                    if($refund_status != -1){
                        $where['a.refund_status'] = $refund_status;
                    }
                    else{
                        $where['a.refund_status'] = ['neq',-1];
                    }
                }
                else if($status == 9){
                    $where['a.status'] = 1;
                    $where['a.is_hexiao'] = 1;
                }
                else{
                    $where['a.status'] = $status;
                }
            }
            if($store_id > 0){
                $where['a.store_id'] = $store_id;
                $where['a.is_hexiao'] = 1;
            }
            
            if($keyword){
                if($type == 1){
                    $where['a.order_no'] = ['like',"%".$keyword."%"];
                }
                else if($type == 2){
                    $where['b.nickname'] = ['like',"%".$keyword."%"];
                }
                else if($type == 3){
                    $where['a.delivery_username'] = ['like',"%".$keyword."%"];
                }
                else if($type == 4){
                    $where['a.user_id'] = intval($keyword);
                }
                else if($type == 5){
                    $where['a.goods_info'] = ['like','%'.$keyword.'%'];
                }
                else if($type == 6){
                    $uids = User::getLevel1UserIds(intval($keyword));
                    $where['a.user_id'] = ['in',$uids];
                }
                else if($type == 7){
                    $where['a.express'] = ['like','%'.$keyword.'%'];
                }
                else if($type == 8){
                    $where['a.delivery_mobile'] = $keyword;
                }
            }
            if($paytype > 0){
                $where['a.paytype'] = $paytype;
            }
            
            if($mid > 0){
                $where['a.mid'] = $mid;
            }
            
            $whereTime = [];
            if($startTime){
                $startTime = strtotime($startTime." 00:00:00");
                $where['a.createtime'] = ['>=',$startTime];
            } 
            
            if($endTime){
                $endTime = strtotime($endTime." 23:59:59");
                $whereTime['a.createtime'] = ['<=',$endTime];
            }

            if($hx_startTime && $hx_endTime){
                $where['a.is_hexiao'] = 1;
                $where['a.completetime'] = ['between',[strtotime($hx_startTime." 00:00:00"),strtotime($hx_endTime." 00:00:00")]];
            }
            else if(!empty($hx_startTime) && empty($hx_startTime)){
                $where['a.is_hexiao'] = 1;
                $where['a.completetime'] = ['>',strtotime($hx_startTime." 00:00:00")];
            }
            else if(empty($hx_startTime) && !empty($hx_endTime)){
                $where['a.is_hexiao'] = 1;
                $where['a.completetime'] = ['<',strtotime($hx_endTime." 00:00:00")];
            }

            if($min > 0){
                $where['a.price'] = ['>=',$min];
            }
            if($max > 0){
                $whereTime['a.price'] = ['<=',$max];
            }
            
            $total = Db::name("bbfx_order")->alias("a")->join("bbfx_user b","a.user_id=b.id")->where($where)->where($whereTime)->count();
            
            if($total == 0){
                __error("没有可导出的数据");
            }
            
            if($total > 100000){
                __error("数据量过大（{$total}条），建议缩小查询范围或联系技术人员使用异步导出功能");
            }
            
            $filename = "order-".date("Y-m-d-His").".csv";
            
            header('Content-Type: text/csv;charset=utf-8');
            header('Content-Disposition: attachment;filename="'.$filename.'"');
            header('Cache-Control: no-cache,no-store,must-revalidate');
            header('Pragma: no-cache');
            header('Expires: 0');
            header('Connection: close');
            
            $output = fopen('php://output', 'w');
            
            if ($output === false) {
                throw new \Exception("无法打开输出流");
            }
            
            fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF));
            
            $headArr = ["订单ID","订单编号","所属商户","核销门店","用户信息","推荐人","订单金额","利润金额","商品名称","商品编码","商品金额","商品数量","收货信息","订单类型","订单状态","退款状态","订单备注","提交表单","下单时间"];
            fputcsv($output, $headArr);
            flush();
            
            $batch_size = 200;
            $total_batches = ceil($total / $batch_size);
            
            for($batch = 0; $batch < $total_batches; $batch++){
                $offset = $batch * $batch_size;
                
                $list = Db::name("bbfx_order")->alias("a")
                    ->join("bbfx_user b","a.user_id=b.id")
                    ->where($where)
                    ->where($whereTime)
                    ->field('a.id,a.user_id,a.price,a.status,a.is_pay,a.paytype,a.total_price,a.mid,a.store_id,a.pay_time,a.createtime,a.is_electronic_waybill_print,a.order_type,a.refund_status,a.extend,a.one_share,a.cost_price,a.is_hexiao,a.express,a.order_no,a.delivery_username,a.delivery_mobile,a.delivery_province,a.delivery_city,a.delivery_area,a.delivery_address,a.delivery_street,a.delivery_method,a.express_fee,a.extend,a.remarks,b.avatar,b.nickname')
                    ->order('a.createtime desc')
                    ->limit($offset, $batch_size)
                    ->select();
                
                if(!empty($list)){
                    $oids = [];
                    $one_shares = [];
                    $mids = [];
                    $store_ids = [];
                    foreach ($list as $key => $val){
                        $oids[] = $val['id'];
                        if(!in_array($val['one_share'],$one_shares)){
                            $one_shares[] = $val['one_share'];
                        }
                        if($val['mid'] > 0 && !in_array($val['mid'],$mids)){
                            $mids[] = $val['mid'];
                        }
                        if($val['store_id'] > 0 && !in_array($val['store_id'],$store_ids)){
                            $store_ids[] = $val['store_id'];
                        }
                    }
                    
                    $sup_user_all = [];
                    $order_goods_all = [];
                    $order_commission_all = [];
                    $merchant_all = [];
                    $store_all = [];
                    
                    $sup_user_all_list = Db::name('bbfx_user')->where(['id'=>['in',$one_shares]])->field("id,nickname,avatar")->select();
                    $order_goods_list = Db::name("bbfx_order_goods")->where(["uniacid"=>UNIACID,"order_id"=>['in',$oids]])->field("id,order_id,goods_info,total,price,cost_price,sku_id,sku_name,sku")->select();
                    $order_commission_list = Db::name("bbfx_fenxiao_order")->where(['uniacid'=>UNIACID,'user_id'=>['>',0],'money_type'=>['in',[1,3]],'order_id'=>['in',$oids]])->field("id,order_id,sum(money) as money")->group('order_id')->select();
                    
                    foreach ($sup_user_all_list as $item){
                        $sup_user_all[$item['id']] = $item;
                    }
                    
                    foreach ($order_goods_list as $item){
                        if(empty($order_goods_all[$item['order_id']])){
                            $order_goods_all[$item['order_id']] = [];
                        }
                        $order_goods_all[$item['order_id']][] = $item;
                    }
                    
                    if(!empty($order_commission_list)){
                        $order_commission_all = array_skey($order_commission_list,"order_id");
                    }
                    
                    if(!empty($mids)){
                        $merchant_list = Db::name("bbfx_merchant")->where(['id'=>['in',$mids]])->field("id,name")->select();
                        foreach ($merchant_list as $item){
                            $merchant_all[$item['id']] = $item['name'];
                        }
                    }
                    
                    if(!empty($store_ids)){
                        $store_list = Db::name("bbfx_store")->where(['id'=>['in',$store_ids]])->field("id,name")->select();
                        foreach ($store_list as $item){
                            $store_all[$item['id']] = $item['name'];
                        }
                    }
                    
                    foreach($list as $key => $val){
                        $val['merchant_name'] = isset($merchant_all[$val['mid']]) ? $merchant_all[$val['mid']] : "";
                        $val['store_name'] = isset($store_all[$val['store_id']]) ? $store_all[$val['store_id']] : "";
                        
                        $order_goods = isset($order_goods_all[$val['id']]) ? $order_goods_all[$val['id']] : [];
                        $sup_user = isset($sup_user_all[$val['one_share']]) ? $sup_user_all[$val['one_share']] : [];
                        $order_commission = isset($order_commission_all[$val['id']]['money']) ? round($order_commission_all[$val['id']]['money'],2) : 0;
                        
                        foreach ($order_goods as $k => &$v){
                            $goods_info = iunserializer($v['goods_info']);
                            $v['goods'] = [
                                'id'=>$goods_info['id'],
                                'title'=>$goods_info['title'],
                                'price'=>$goods_info['price'],
                                'product_code'=>$goods_info['product_code'],
                                'sku'=>$goods_info['sku'],
                            ];
                        }
                        unset($v);
                        
                        $val['paytypeText'] = "";
                        if($val['is_pay'] == 1){
                            $val['pay_time'] = date("Y-m-d H:i:s",$val['pay_time']);
                            $val['paytypeText'] = $this->model->getOrderPaytype($val);
                        }
                        else{
                            $val['pay_time'] = "";
                        }
                        
                        $val['createtime'] = date("Y-m-d H:i:s",$val['createtime']);
                        $val['typeText'] = $this->model->getOrderType($val['order_type']);
                        $val['refund_statusText'] = $this->model->getOrderRefundStatus($val['refund_status']);
                        $val['statusText'] = $this->model->getOrderStatus($val);
                        
                        $order_profit = $val['price'] - $val['cost_price'] - $order_commission;
                        if($val['delivery_method'] == 1 && $val['order_type'] == 2){
                            $order_profit -= $val['express_fee'];
                        }
                        $val['order_profit'] = max(0,round($order_profit,2));
                        
                        $extend = iunserializer($val['extend']);
                        
                        $delivery = $val['delivery_username']." ".$val['delivery_mobile'].','.$val['delivery_province'].$val['delivery_city'].$val['delivery_area'].$val['delivery_street'].$val['delivery_address'];
                        if(empty($val['delivery_mobile'])){
                            $delivery = '';
                        }
                        
                        $sup_user_text = "总店";
                        if(!empty($sup_user)){
                            $sup_user_text = "(ID:".$sup_user['id'].")".$sup_user['nickname'];
                        }
                        
                        $form_list = [];
                        if(!empty($extend['form'])){
                            foreach($extend['form'] as $k => $v){
                                $form_list[] = $v['label']."：".$v['value'];
                            }
                        }
                        $order_form = implode("，",$form_list);
                        
                        $goods_count = count($order_goods);
                        $goods_index = 0;

                        addFileLog("ggg111",json_encode($order_goods));
                        
                        foreach ($order_goods as $k => $v){
                            $goods = $v['goods'];
                            
                            $product_code = $goods['product_code'];
                            if(!empty($goods['sku'])){
                                $product_code = $goods['sku']['product_code'];
                            }
                            
                            if($goods_index == 0){
                                $row = array(
                                    $val['id'],
                                    $val['order_no'],
                                    $val['merchant_name'],
                                    $val['store_name'],
                                    "(ID:{$val['user_id']})".$val['nickname'],
                                    $sup_user_text,
                                    $val['price'],
                                    $val['order_profit'],
                                    $goods['title'],
                                    $product_code,
                                    $v['price'],
                                    $v['total'],
                                    $delivery,
                                    $val['typeText'],
                                    $val['statusText'],
                                    $val['refund_statusText'],
                                    $val['remarks'],
                                    $order_form,
                                    $val['createtime']
                                );
                            }
                            else{
                                $row = array(
                                    '',
                                    '',
                                    '',
                                    '',
                                    '',
                                    '',
                                    '',
                                    '',
                                    $goods['title'],
                                    $product_code,
                                    $v['price'],
                                    $v['total'],
                                    '',
                                    '',
                                    '',
                                    '',
                                    '',
                                    '',
                                    ''
                                );
                            }
                            
                            fputcsv($output, $row);
                            $goods_index++;
                        }
                    }
                    
                    unset($list);
                    unset($sup_user_all);
                    unset($order_goods_all);
                    unset($order_commission_all);
                    unset($merchant_all);
                    unset($store_all);
                }
                
                if($batch % 3 == 0){
                    gc_collect_cycles();
                }
                
                flush();
                
                if (connection_aborted()) {
                    break;
                }
            }
            
            fclose($output);
            
        } catch (\Exception $e) {
            $error_msg = "导出失败: " . $e->getMessage();
            \think\Log::write($error_msg, 'error');
            
            if (headers_sent()) {
                echo "\n错误: " . $e->getMessage();
            } else {
                __error($error_msg);
            }
        }
        
        exit();
    }
    
    public function delete(){
        $this->commonDelete("bbfx_order");
    }
}