<?php
/**
 * @package merchant
 *
 * @author Qinii
 * @day 2020-06-10
 *
 *
 */
namespace app\controller\merchant\store\order;

use app\common\repositories\store\ExcelRepository;
use app\common\repositories\store\order\MerchantReconciliationRepository;
use app\common\repositories\store\order\StoreGroupOrderRepository;
use app\common\repositories\store\order\StoreOrderRepository;
use crmeb\exceptions\UploadException;
use crmeb\services\ExcelService;
use crmeb\services\SpreadsheetExcelService;
use think\App;
use crmeb\basic\BaseController;
use app\common\repositories\store\order\StoreOrderRepository as repository;
use think\facade\Db;
use think\facade\Log;

class Order extends BaseController
{
    protected $repository;

    /**
     * Product constructor.
     * @param App $app
     * @param repository $repository
     */
    public function __construct(App $app, repository $repository)
    {
        parent::__construct($app);
        $this->repository = $repository;
    }


    /**
     * 订单列表
     * @return mixed
     * @author Qinii
     */
    public function lst()
    {
        [$page, $limit] = $this->getPage();
        $where = $this->request->params(['status', 'date', 'order_sn', 'username', 'order_type', 'distribution_mode', 'keywords', 'pay_type', 'paid', 'order_ids', 'is_red_ylj', 'gzc', 'ylj_status']);
        $where['mer_id'] = $this->request->merId();
        return app('json')->success($this->repository->merchantGetListYhc($where, $page, $limit));
    }

    /**
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author xaboy
     * @day 2020/6/10
     */
    public function userLst()
    {
        [$page, $limit] = $this->getPage();
        $where = [
            'status' => (int)$this->request->get('status', 0),
            'mer_id' => $this->request->merId()
        ];
        if (input('uid')) {
            $where['uid'] = input('uid');
        }
        return app('json')->success($this->repository->getList($where, $page, $limit));
    }

    /**
     * TODO 自提订单列表
     * @return mixed
     * @author Qinii
     * @day 2020-08-17
     */
    public function takeLst()
    {
        [$page, $limit] = $this->getPage();
        $where = $this->request->params(['date', 'order_sn', 'username']);
        $where['take_order'] = 1;
        $where['status'] = -1;
        $where['verify_date'] = $where['date'];
        unset($where['date']);
        $where['mer_id'] = $this->request->merId();
        return app('json')->success($this->repository->merchantGetList($where, $page, $limit));
    }

    /**
     *  订单头部统计
     * @return mixed
     * @author Qinii
     */
    public function chart()
    {
        return app('json')->success($this->repository->merchantOrderNumber($this->request->merId()));
    }

    /**
     * TODO 自提订单头部统计
     * @return mixed
     * @author Qinii
     * @day 2020-08-17
     */
    public function takeChart()
    {
        return app('json')->success($this->repository->merchantOrderNumber($this->request->merId(),1));
    }


    /**
     * TODO 订单类型
     * @return mixed
     * @author Qinii
     * @day 2020-08-15
     */
    public function orderType()
    {
        $where['mer_id'] = $this->request->merId();
        return app('json')->success($this->repository->orderType($where));
    }

    /**
     * @param $id
     * @return mixed
     * @author Qinii
     */
    public function deliveryForm($id)
    {
        if(!$this->repository->merDeliveryExists($id,$this->request->merId()))
            return app('json')->fail('订单信息或状态错误');
        return app('json')->success(formToData($this->repository->sendProductForm($id)));
    }

    /**
     * @param $id
     * @return mixed
     * @author Qinii
     */
    public function delivery($id)
    {
        if(!$this->repository->merDeliveryExists($id,$this->request->merId()))
           return app('json')->fail('订单信息或状态错误');
        $data = $this->request->params(['delivery_type','delivery_name','delivery_id']);
        if(preg_match('/([\x81-\xfe][\x40-\xfe])/',$data['delivery_id'])) return app('json')->fail('请输入正确的单号/电话');
        $this->repository->delivery($id,$data);
        return app('json')->success('发货成功');
    }

    /**
     * @param $id
     * @return mixed
     * @author Qinii
     * @day 2020-06-11
     */
    public function updateForm($id)
    {
        if(!$this->repository->merStatusExists($id,$this->request->merId()))
            return app('json')->fail('订单信息或状态错误');
        return app('json')->success(formToData($this->repository->form($id)));
    }

    /**
     * @param $id
     * @return mixed
     * @author Qinii
     * @day 2020-06-11
     */
    public function update($id)
    {
        $data = $this->request->params(['total_price','pay_price','total_postage','pay_postage']);
        if($data['total_price'] < 0 || $data['pay_price'] < 0 || $data['total_postage'] < 0 || $data['pay_postage'] < 0 )
            return app('json')->fail('金额不可未负数');
        if(!$this->repository->merStatusExists($id,$this->request->merId()))
            return app('json')->fail('订单信息或状态错误');
        $this->repository->eidt($id,$data);
        return app('json')->success('修改成功');
    }

    /**
     * @param $id
     * @return mixed
     * @author Qinii
     * @day 2020-06-11
     */
    public function detail($id)
    {
        $data = $this->repository->getOne($id,$this->request->merId());
        if(!$data)
            return app('json')->fail('数据不存在');


        return app('json')->success($data);
    }

    /**
     * @param $id
     * @return mixed
     * @author Qinii
     * @day 2020-06-11
     */
    public function status($id)
    {
        [$page, $limit] = $this->getPage();
        if(!$this->repository->getOne($id,$this->request->merId()))
            return app('json')->fail('数据不存在');
        return app('json')->success($this->repository->getOrderStatus($id,$page, $limit));
    }

    /**
     * @param $id
     * @return mixed
     * @author Qinii
     * @day 2020-06-11
     */
    public function remarkForm($id)
    {
        return app('json')->success(formToData($this->repository->remarkForm($id)));
    }

    /**
     * @param $id
     * @return mixed
     * @author Qinii
     * @day 2020-06-11
     */
    public function remark($id)
    {
        if(!$this->repository->getOne($id,$this->request->merId()))
            return app('json')->fail('数据不存在');
        $data = $this->request->params(['remark']);
        $this->repository->update($id,$data);

        return app('json')->success('备注成功');
    }

    /**
     * 核销
     * @param $code
     * @author xaboy
     * @day 2020/8/15
     */
    public function verify($code)
    {
        $this->repository->verifyOrder($code, $this->request->merId(), 0);
        return app('json')->success('订单核销成功');
    }

    /**
     * 自提
     * @param $code
     * @author xaboy
     * @day 2020/8/15
     */
    public function carry($code)
    {
        $order_id= input('order_id');
        $this->repository->carryOrder($code, $this->request->merId(), 0,$order_id);
        return app('json')->success('订单核销成功');
    }

    /**
     * 手动操作订单为 已自提 关单
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function carryByWithoutCode()
    {
        $order_id = input('order_id');
        $this->repository->carryOrder(null, $this->request->merId(), 0, $order_id);
        return app('json')->success('订单核销成功');
    }

    /**
     * @param $id
     * @return mixed
     * @author Qinii
     * @day 2020-06-11
     */
    public function delete($id)
    {
        if(!$this->repository->userDelExists($id,$this->request->merId()))
            return app('json')->fail('订单信息或状态错误');
        $data['is_system_del'] = 1;
        $this->repository->update($id,$data);
        return app('json')->success('删除成功');
    }


    /**
     * TODO 快递查询
     * @param $id
     * @return mixed
     * @author Qinii
     * @day 2020-06-25
     */
    public function express($id)
    {
        if(!$this->repository->getWhereCount(['order_id' => $id,'mer_id' => $this->request->merId(),'delivery_type' =>1]))
            return app('json')->fail('订单信息或状态错误');
        return app('json')->success($this->repository->express($id));
    }

    /**
     * TODO
     * @param $id
     * @return mixed
     * @author Qinii
     * @day 2020-07-30
     */
    public function reList($id)
    {
        [$page,$limit] = $this->getPage();
        $make = app()->make(MerchantReconciliationRepository::class);
        if(!$make->getWhereCount(['mer_id' => $this->request->merId(),'reconciliation_id' => $id]))
            return app('json')->fail('数据不存在');
        $where = ['reconciliation_id' => $id,'type' => 0];
        return app('json')->success($this->repository->reconList($where,$page,$limit));
    }

    /**
     * TODO 导出文件
     * @author Qinii
     * @day 2020-07-30
     */
    public function excel()
    {
        $where = $this->request->params(['status', 'date', 'order_sn', 'username', 'order_type', 'keywords', 'pay_type', 'paid', 'order_ids', 'is_red_ylj', 'ylj_status']);
        $where['mer_id'] = $this->request->merId();
        $data=$this->repository->merchantGetListYhc($where, 1, 10000);
        if($data['count']<1){
            return app('json')->fail('没有数据');
        }
        $list=$this->orderList2($data['list']->toArray());
//        var_dump($list);die;

        app()->make(ExcelRepository::class)->create($list, $this->request->adminId(), 'order', $this->request->merId());
        return app('json')->success('开始导出数据');
    }
    public function orderList2(array $data){
        $result = [];
        if(empty($data)) return $result;
        $i = 1;
        // '序号','订单编号','收货人','商品信息','实际支付', '支付类型','支付方式','支付状态',订单状态'下单时间','养老金','养老金状态',
        foreach ($data as $item){

            if($item['status']==5){
                $item['pay_price']='0';
            }
            $item['leixing']='';
            $item['ddzt']='';
            $item['is_red_ylj_text']='未结算';
            if($item['paid']==1){
                if($item['pay_type']==0){
                    $item['leixing']='虚拟支付';
                }else if ($item['pay_type']==1){
                    $item['leixing']='微信支付';
                }else if ($item['pay_type']==5){
                    $item['leixing']='红积分兑换';
                }
            }
            if($item['status'] == 5) $item['ddzt']='待付款';
            if($item['status'] == 0) $item['ddzt']='待发货';
            if($item['status'] == 1) $item['ddzt']='待收货';
            if($item['status'] == 2) $item['ddzt']='待评价';
            if($item['status'] == 3) $item['ddzt']='已完成';
            if($item['status'] == 4) $item['ddzt']='已申请退款';
            if($item['status'] == -1) $item['ddzt']='已退款';
            if($item['status'] == 6) $item['ddzt']='已取消';

            if($item['is_red_ylj']==1){
                $item['is_red_ylj_text']='待审核';
            }
            if($item['is_red_ylj']==2){
                $item['is_red_ylj_text']='已结算';
            }
            $item['sp']='';
            $item['sp_num']='';

//            <div v-for="(val, i ) in scope.row.orderProduct" :key="i" class="tabBox acea-row row-middle">
//                        <div class="demo-image__preview">
//                            <el-image :src="val.cart_info.product.image" :preview-src-list="[val.cart_info.product.image]" />
//                        </div>
//                        <span class="tabBox_tit">{{ val.cart_info.product.store_name + ' | ' }}{{ val.cart_info.productAttr.sku }}</span>
//                        <span class="tabBox_pice">
//                            {{ '￥'+ val.cart_info.productAttr.price + ' x '+ val.product_num }}
//                            <em v-if="val.refund_num < val.product_num && val.refund_num > 0" style="color: red;font-style: normal;">(-{{ val.product_num - val.refund_num }})</em>
//                        </span>
//                    </div>

            foreach ($item['orderProduct'] as $vv){
                $item['sp'].=$vv['cart_info']['product']['store_name'].'  ';
                $item['sp_num'].=$vv['cart_info']['productAttr']['price'].' x' . $vv['product_num'].' ';
            }

            $result[] = [
                $i,
                $item['order_sn'],
                $item['real_name'],
                $item['user_phone'],
                $item['sp'],
                $item['sp_num'],
                $item['pay_price'],
                $item['leixing'],
                $item['paid'] ? '已支付':'未支付',
                $item['ddzt'],
                $item['create_time'] ,
                $item['ylj'] ,
                $item['is_red_ylj_text'] ,
            ];
            $i++;
        }
        return $result;
    }

    /**
     * TODO 打印小票
     * @param $id
     * @return mixed
     * @author Qinii
     * @day 2020-07-30
     */
    public function printer($id)
    {
        $merId = $this->request->merId();
        if(!merchantConfig($merId,'printing_status'))
            return app('json')->fail('未开启打印机设置');
        if(!$this->repository->getOne($id,$merId))
            return app('json')->fail('数据不存在');
        $this->repository->printer($id,$merId);
        return app('json')->success('打印成功');
    }

    /**
     * @param $id
     * @param StoreGroupOrderRepository $groupOrderRepository
     * @param repository $orderRepository
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author xaboy
     * @day 2020/6/10
     */
    public function cancelGroupOrder($id, StoreGroupOrderRepository $groupOrderRepository, StoreOrderRepository $orderRepository)
    {
        $data = $this->request->params(['change_message', 'remark']);
        $merId = $this->request->merId();
        $order = $orderRepository->getWhere(['group_order_id' => $id]);
        if ($order['mer_id'] != $merId)
            return app('json')->fail('数据不存在');
        try {
            $groupOrderRepository->cancel((int)$id, 0, $data['change_message'], $data['remark']);
        } catch (\Throwable $e) {
            Log::error('关闭订单失败:' . json_encode([
                    'error_message' => $e->getMessage(),
                    'error_file' => $e->getFile(),
                    'error_line' => $e->getLine(),
                    'error_code' => $e->getCode(),
                    'exception_class' => get_class($e),
                    'trace' => $e->getTraceAsString()
                ], JSON_UNESCAPED_UNICODE));
            return app('json')->fail('关闭订单失败');
        }
        return app('json')->success('取消成功');
    }

    //设置成支付成功
    public function order_zhifu($id)
    {
        $admin_id = $this->request->adminId();
        $admin_info = Db::name('merchant_admin')->where('merchant_admin_id',$admin_id)->find();
        if(!$admin_info){
            return app('json')->fail('没有权限');
        }
        if($admin_info['roles'] && !in_array('53',explode(',',$admin_info['roles']))){
            return app('json')->fail('没有权限');
        }
        $domain = $this->request->domain();

        $order=Db::name('store_order')->find($id);
        if(!$order){
            return app('json')->fail('数据不存在');
        }
        if($order['paid']!=0 || $order['status']!=5){
            return app('json')->fail('订单不是待支付状态');
        }
//        $pay_type=5;
        $group_order=Db::name('store_group_order') -> where('group_order_id',$order['group_order_id']) -> find();
        Db::name('store_group_order') -> where('group_order_id',$order['group_order_id']) -> update(['rand'=>mt_rand(1000,9999)]);

        $orderSn = $group_order['group_order_sn'];
        $groupOrder = app()->make(StoreGroupOrderRepository::class)->getWhere(['group_order_sn' => $orderSn]);
        if (!$groupOrder || $groupOrder->paid == 1) return;
        $total_price=$order['total_price']+$order['youhui_price'];
        $pay_price=$order['pay_price']+$order['youhui_price'];
        Db::name('store_order')->where('order_id',$id)->update(['total_price'=>$total_price,'pay_price'=>$pay_price,'youhui_price'=>0]);
        app()->make(StoreOrderRepository::class)->paySuccess($groupOrder);
        return app('json')->success('设置成功');
//        event('pay_success_order', ['order_sn' => $requestId[0],'pay_type'=>$pay_type]);
//        dump('成功');
//        dump($this->randomFromDev(20));
    }

    /**
     * 判断是不是红积分支付的订单
     * @return mixed
     */
    public function order_red_num()
    {
        $order_ids=input('order_ids','');
        $merId = $this->request->merId();

        $where['o.paid']=1;
//        $where['o.pay_type'] = 5;
        $where['o.is_red_ylj']=0;
        $where['o.mer_id']=$merId;
        $where['u.commission_type']=5;
        $where['u.gzc']=3;
        $where['u.status']=0;
        $order=Db::name('store_order')
            ->alias('o')
            ->join('user_bill u','u.order_sn=o.order_sn')
            ->where($where)
            ->whereIN('o.pay_type',[0,5])
            ->whereIn('o.order_id',$order_ids)
            ->column('o.order_id,o.order_sn,u.number,u.mark');
        if($order){
            $data['num']=count($order);
            $order_ids2=[];
            $ylj=0;
            foreach ($order as $v){
                $order_ids2[]=$v['order_id'];
                $ylj+=$v['number'];
            }
            $data['order_ids']=implode(',',$order_ids2);
            $data['ylj']=$ylj;

            $data['company_name']='北京天地博爱';
            $data['company_bank_name']='开户行开户行开户行开户行';
            $data['company_bank_card']='银行卡号银行卡号银行卡号银行卡号';

            return app('json')->success('ok',$data);
        }

        return app('json')->fail('只能结算红积分和虚拟支付类型的订单~');
    }

    /**
     * 养老金提交打款凭证
     * @return mixed
     */
    public function order_red_add()
    {
        $order_ids=input('order_ids','');
        $pics=input('pics','');
        if($order_ids==''){
            return app('json')->fail('只能结算红积分和虚拟支付类型的订单~');
        }
        if($pics==''){
            return app('json')->fail('请上传打款凭证');
        }
        $merId = $this->request->merId();
        $where['o.paid']=1;
//        $where['o.pay_type'] = 5;
        $where['o.is_red_ylj']=0;
        $where['o.mer_id']=$merId;
        $where['u.commission_type']=5;
        $where['u.gzc']=3;
        $where['u.status']=0;
        $order=Db::name('store_order')
            ->alias('o')
            ->join('user_bill u','u.order_sn=o.order_sn')
            ->where($where)
            ->whereIN('o.pay_type',[0,5])
            ->whereIn('o.order_id',$order_ids)
            ->column('o.order_id,o.order_sn,u.number,u.mark');
        if($order){
            $data['num']=count($order);
            $order_ids2=[];
            $ylj=0;
            foreach ($order as $v){
                $order_ids2[]=$v['order_id'];
                $ylj+=$v['number'];
            }
            $data['order_ids']=implode(',',$order_ids2);
            $data['ylj']=$ylj;
            $data['pics']=$pics;
            $data['mer_id']=$merId;

            $re=Db::name('enterprise_red_order_voucher')->insert($data);

            Db::name('store_order')->whereIn('order_id',$order_ids2)->where('is_red_ylj',0)->update(['is_red_ylj'=>1]);
            if($re){
                return app('json')->success('提交成功');
            }
            return app('json')->fail('提交失败');
        }

        return app('json')->fail('只能结算红积分和虚拟支付类型的订单~');

    }

    /**
     * 养老金打款凭证 列表
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function order_red_list()
    {
        [$page, $limit] = $this->getPage();
        $where = $this->request->params(['status', 'date']);
        $where['mer_id'] = $this->request->merId();
        $query =Db::name('enterprise_red_order_voucher')->when(isset($where['date']) && $where['date'] !== '', function ($query) use ($where) {
            getModelTime($query, $where['date']);
        })->when(isset($where['status']) && $where['status'] !== '', function ($query) use ($where) {
            $query->where('status',$where['status']);
        });
        $data['count'] = $query->count();
        $data['list'] = $query->page($page, $limit)->order('id desc')->select();

        return app('json')->success('ok',$data);

    }

    public function reward_list()
    {
        [$page, $limit] = $this->getPage();
        $where = $this->request->params(['type', 'account', 'date','identity']);
        $where['b.mer_id'] = $this->request->merId();
        $query =Db::name('enterprise_user_bill')->alias('b')->join('user u','u.uid=b.uid')->join('enterprise_user eu','eu.uid=b.uid')->field('b.*,u.nickname,u.account,eu.identity')
            ->when(isset($where['date']) && $where['date'] !== '', function ($query) use ($where) {
            getModelTime($query, $where['date'],'b.create_time');
        })->when(isset($where['type']) && $where['type'] !== '', function ($query) use ($where) {
            $query->where('b.type',$where['type']);
        })->when(isset($where['identity']) && $where['identity'] !== '', function ($query) use ($where) {
            $query->where('eu.identity',$where['identity']);
        })->when(isset($where['account']) && $where['account'] !== '', function ($query) use ($where) {
            $query->whereLike('u.account','%'.$where['account'].'%');
        });
        $query->where('type','<>',8);
        $data['count'] = $query->count();
        $data['list'] = $query->page($page, $limit)->order('b.enterprise_user_bill desc')->select()->each(function ($v) use ($where){
            if($v['identity']==0){
                $identity_name='普通用户';
            }else if ($v['identity']==100){
                $identity_name='合伙人';
            }else{
                $identity_name=Db::name('enterprise_performance_divvy')->where('state',1)->where('mer_id', $where['b.mer_id'])->where('id',$v['identity'])->value('name');
            }
            $v['identity_name']=$identity_name?$identity_name:'普通用户';
            return $v;
        });
        $count = $query->whereIn('type', [1,2,3,4,6,7])->sum('money');

        $query_sql_1 = clone $query;
        $query_sql_2 = clone $query;
        $query_sql_3 = clone $query;
        $query_sql_4 = clone $query;
        $query_sql_6 = clone $query;
        $query_sql_7 = clone $query;

        //type 1-推荐奖 2-业绩奖 3-服务中心分红 4-推荐代理商收益  5- 消费增值
        $count1 = $query_sql_1->where('type', 1)->sum('money');
        $count2 = $query_sql_2->where('type', 2)->sum('money');
        $count3 = $query_sql_3->where('type', 3)->sum('money');
        $count4 = $query_sql_4->where('type', 4)->sum('money');
        $count6 = $query_sql_6->where('type', 6)->sum('money');
        $count7 = $query_sql_7->where('type', 7)->sum('money');
        $data['countmoyer']=[
            ['className' => 'el-icon-s-goods', 'count' => $count, 'field' => '元', 'name' => '奖励总额', 'info' => '奖励总额 = 分享奖+业绩奖+代理商分红+推荐代理商收益+运营中心收益+人工奖励佣金'],
            ['className' => 'el-icon-s-goods', 'count' => $count1, 'field' => '元', 'name' => '分享奖', 'info' => ''],
            ['className' => 'el-icon-s-goods', 'count' => $count2, 'field' => '元', 'name' => '业绩奖', 'info' => ''],
            ['className' => 'el-icon-s-goods', 'count' => $count3, 'field' => '元', 'name' => '代理商分红', 'info' => ''],
            ['className' => 'el-icon-s-goods', 'count' => $count4, 'field' => '元', 'name' => '推荐代理商收益', 'info' => ''],
            ['className' => 'el-icon-s-goods', 'count' => $count6, 'field' => '元', 'name' => '运营中心收益', 'info' => ''],
            ['className' => 'el-icon-s-goods', 'count' => $count7, 'field' => '元', 'name' => '人工奖励佣金', 'info' => ''],
        ];
        return app('json')->success('ok', $data);
    }

    //商户后台-奖励统计 导出功能
    public function reward_excel()
    {
        $where = $this->request->params(['type', 'account', 'date', 'identity']);
        $where['b.mer_id'] = $this->request->merId();
        $query = Db::name('enterprise_user_bill')->alias('b')->join('user u', 'u.uid=b.uid')->join('enterprise_user eu', 'eu.uid=b.uid')->field('b.*,u.nickname,u.account,eu.identity')
            ->when(isset($where['date']) && $where['date'] !== '', function ($query) use ($where) {
                getModelTime($query, $where['date'], 'b.create_time');
            })->when(isset($where['type']) && $where['type'] !== '', function ($query) use ($where) {
                $query->where('b.type', $where['type']);
            })->when(isset($where['identity']) && $where['identity'] !== '', function ($query) use ($where) {
                $query->where('eu.identity', $where['identity']);
            })->when(isset($where['account']) && $where['account'] !== '', function ($query) use ($where) {
                $query->whereLike('u.account', '%' . $where['account'] . '%');
            });
        $list = $query->order('b.enterprise_user_bill desc')->select();
        foreach ($list as $k=>$v){
            $v['type_name']='';
            $v['identity_name']='';
            if($v['type'] == 1) $v['type_name']='分享奖';
            if($v['type'] == 2) $v['type_name']='业绩奖';
            if($v['type'] == 3) $v['type_name']='代理商分红';
            if($v['type'] == 4) $v['type_name']='推荐代理商收益';
            if($v['type'] == 5) $v['type_name']='消费增值系统佣金';

            if($v['identity'] == 0){
                $v['identity_name']='普通用户';
            }else if($v['identity'] == 100){
                $v['identity_name']='合伙人';
            }else{
                $identity_name=Db::name('enterprise_performance_divvy')->where('state',1)->where('mer_id', $where['b.mer_id'])->where('id',$v['identity'])->value('name');
                $v['identity_name']=$identity_name?$identity_name:'普通用户';
            }

            $arr[]=array(
                $v['enterprise_user_bill'],
                $v['create_time'],
                $v['nickname'],
                $v['account'],
                $v['type_name'],
                $v['money'],
                $v['identity_name'],
                $v['title'],
            );
        }
        $header =    [
            'ID','创建时间','用户昵称','用户账号(手机号)','佣金名称','金额(元)','当前身份','奖励来源'
        ];
        $filename = '奖励统计'.date('YmdHis').'_'.rand(10000,99999);
        $title = '奖励统计';
        $name = '奖励统计';
        $info = '生成时间:' . date('Y-m-d H:i:s',time());
        $suffix='xlsx';
        $path='extract';
        unset($_instance);

        $_instance = SpreadsheetExcelService::instance_xin();

        $_path =$_instance
            ->createOrActive()
            ->setExcelHeader($header)
            ->setExcelTile($title, $name, $info)
            ->setExcelContent($arr)
            ->excelSave($filename, $suffix, $path);

        $data= [
            'name' => $filename.'.'.$suffix,
            'status' => 1,
            'path' => '/'.$_path
        ];

        return app('json')->success('ok',$data);


    }
}

