<?php
namespace app\admin\controller\life;

use app\admin\controller\BaseController;
use app\admin\server\life\GoodsOrderServer;
use app\admin\model\GoodsOrder as GoodsOrderModel;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use app\admin\model\LifeGoods;
use app\admin\model\User;
use support\Db;

class GoodsOrder extends BaseController
{

    /**
     * Notes:获取订单列表
     * @return \support\Response
     * User: ZQ
     * Date: 2022/10/13
     */
    public function getOrderList()
    {
        [$page, $limit] = $this->getPage();
        $keywords = $this->request->get('keywords');
        $order_type_model = $this->request->get('order_type_model',1);
        $result         = GoodsOrderServer::getOrderList($page, $limit,$keywords,$order_type_model);
        return json_success($result, '成功');
    }

    /**
     * Notes:订单详情
     * @return \support\Response
     * User: ZQ
     * Date: 2022/10/13
     */
    public function orderInfo()
    {
        $order_id = $this->request->get('order_id');
        $result         = GoodsOrderServer::orderInfo($order_id);
        if ($result){
            return json_success($result, '获取成功');
        }else{
            throw new \Exception('获取失败！');
        }

    }

    /**
     * Notes:发货
     * @return \support\Response
     * User: YCP
     * Date: 2023/5/12
     */
    public function orderDelivery()
    {
        $params = $this->request->post();
        $admin_id = $this->request->admin_id;
        $result         = GoodsOrderServer::orderDelivery($params,$admin_id);
        if ($result){
            return json_success($result, '获取成功');
        }else{
            throw new \Exception('获取失败！');
        }

    }

    /**
     * Notes:修改订单支付状态
     * @return \support\Response
     * User: YCP
     * Date: 2022/11/28
     */
    public function updatePayStatus()
    {
        $order_id = $this->request->post('order_id');
        $order_pay_status = $this->request->post('order_pay_status');
        if(!$order_id){
            throw new \Exception('订单ID不能为空');
        }
        $result       = GoodsOrderServer::updatePayStatus($order_id, $order_pay_status);
        return json_success($result, '修改成功');
    }

    /**
     * Notes:导出订单
     * @return \support\Response
     * User: YCP
     * Date: 2023/8/10
     */
    public function orderExport()
    {

        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        // 居中对齐
        $styleArray = [
            'alignment' => [
                'horizontal' => Alignment::HORIZONTAL_CENTER, //水平居中
                'vertical' => Alignment::VERTICAL_CENTER, //垂直居中
            ],
        ];

        $sheet->getDefaultColumnDimension()->setWidth(20);// 列宽
        //自动计算列宽
        $sheet->getColumnDimension('A')->setAutoSize(true);
        $sheet->getDefaultRowDimension()->setRowHeight(20);// 行高

        // 标题
        $tabletitle = '悦享家待发货订单表(备注：相同订单号请填写相同的快递单号)';
        $sheet->mergeCells('A1:K1');
        $sheet->getRowDimension('1')->setRowHeight(40);// 行高
        $sheet->getStyle('A1')->applyFromArray($styleArray);
        $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(16);
        $sheet->setCellValue('A1', $tabletitle);
        
        $sheet->getStyle('A2:K2')->getFont()->setBold(true)->setSize(12);
        $sheet->setCellValue('A2','订单号');
        $sheet->setCellValue('B2','下单时间');
        $sheet->setCellValue('C2','收货人');
        $sheet->setCellValue('D2','电话');
        $sheet->setCellValue('E2','地址');
        $sheet->setCellValue('F2','商品');
        $sheet->setCellValue('G2','规格');
        $sheet->setCellValue('H2','数量');
        $sheet->setCellValue('I2','备注'); 
        $sheet->setCellValue('J2','快递单号');
        $sheet->setCellValue('K2','快递公司');
        

        $data = GoodsOrderModel::select(['life_market_order.order_dno','life_market_order.order_address_nickname','life_market_order.order_address_mobile','life_market_order.order_address','life_market_order.order_remke','life_market_order.order_create_time','life_market_order_detail.detail_goods_name','life_market_order_detail.detail_goods_num','life_market_goods.goods_attr'])
            ->RightJoin('life_market_order_detail','detail_order_id','=','life_market_order.order_id')
            ->leftJoin('life_market_goods','goods_id','=','life_market_order_detail.detail_goods_id')
            ->where(['order_pay_status'=>1,'order_status'=>1])
            ->orderBy('order_create_time','DESC')
            ->get()->toArray();

        //return json_success($data, '修改成功');

        $sort = 0;
        foreach ($data as $v){
            $sheet->setCellValue('A' . ($sort + 3), $v['order_dno']);
            $sheet->setCellValue('B' . ($sort + 3), $v['order_create_time']);
            $sheet->setCellValue('C' . ($sort + 3), $v['order_address_nickname']);
            $sheet->setCellValue('D' . ($sort + 3), $v['order_address_mobile']);
            $sheet->setCellValue('E' . ($sort + 3), $v['order_address']);
            $sheet->setCellValue('F' . ($sort + 3), $v['detail_goods_name']);
            $sheet->setCellValue('G' . ($sort + 3), $v['goods_attr']);
            $sheet->setCellValue('H' . ($sort + 3), $v['detail_goods_num']);
            $sheet->setCellValue('I' . ($sort + 3), $v['order_remke']);
            $sort++;
        }
        // 工作簿标题
        $sheettitle = '悦享家待发货订单表';
        $sheet->setTitle($sheettitle);

        // 文件名
        $filename='悦享集市待发货订单_'.date('Y-m-dHis');

        $writer = new Xlsx($spreadsheet);
        $file_path = public_path().'/'.$filename.'.xlsx';
        // 保存文件到 public 下
        $writer->save($file_path);
        // 下载文件
        return response()->download($file_path, $filename.'.xlsx');

    }

    /**
     * Notes:导入发货订单
     * @return \support\Response
     * @throws \Exception
     * User: YCP
     * Date: 2023/8/11
     */
    public function orderImport()
    {
        $excel_address = $this->request->get('excel_address');//文件地址;
        $admin_id = $this->request->admin_id;
        require_once 'vendor/phpoffice/phpexcel/Classes/PHPExcel.php';
        require_once 'vendor/phpoffice/phpexcel/Classes/PHPExcel/IOFactory.php';
        $objPHPExcel = \PHPExcel_IOFactory::load($excel_address);
        // 逐行读取 sheet 内的内容（常用）
        foreach ($objPHPExcel->getworksheetiterator() as $sheet){   //循环sheet
            foreach ($sheet->getrowiterator() as $row){     //循环row
                if ($row->getrowindex() < 3){  // 默认从第二行开始
                    continue;
                }
                foreach ($row->getcelliterator() as $cell){     //循环cell
                    $data[] = $cell->getvalue();
                }
                if(!empty($data)){
                    
                    $order_dno = $data[0];
                    $order = GoodsOrderModel::where(['order_dno' => $order_dno])->first();
                    if($order['order_pay_status'] == 1 && $order['order_status'] == 1){

                        $params['order_express_no'] = $data[9];
                        $params['order_express_company'] = $data[10];
                        $params['order_status'] = 2;
                        $params['order_deliver_time'] = time();
                        $result = GoodsOrderModel::where(['order_dno' => $order_dno])->update($params);
                        if (!empty($result)){
                            $msg = '管理员：' . $admin_id . '在：' . date("Y-m-d H:i:s", time()) . '导入订单物流信息-编号: ' . $result;
                            plog('user-order-update', '悦享集市-导入物流信息', $msg);
                        }
                    }        
                    unset($data);
                }else{
                    throw new \Exception('读取失败');
                }
            }
        }

        return json_success('', '导入成功');
    }

    /**
     * Notes:数据统计
     * @return \support\Response
     * User: YCP
     * Date: 2023/8/21
     */
    public function dataStatistics()
    {
        //健康超市
        $data['market_goods_count'] = LifeGoods::where(['goods_is_del'=>0,'goods_shop_id'=>1])->whereNotIn('goods_category_id',[300])->count();//产品总数
        $data['market_goods_on_count'] = LifeGoods::where(['goods_is_del'=>0,'goods_status'=>1,'goods_shop_id'=>1])->whereNotIn('goods_category_id',[300])->count();//已上架产品数
        $data['market_goods_off_count'] = LifeGoods::where(['goods_is_del'=>0,'goods_status'=>2,'goods_shop_id'=>1])->whereNotIn('goods_category_id',[300])->count();//已上架产品数
        $data['market_goods_sell_count'] = GoodsOrderModel::RightJoin('life_market_order_detail','detail_order_id','=','life_market_order.order_id')
            ->where(['order_pay_status'=>1,'order_type_model'=>1])
            ->sum('life_market_order_detail.detail_goods_num');
        $data['market_order_count'] = GoodsOrderModel::where(['order_type_model'=>1])->count();
        $data['market_order_status_count'] = GoodsOrderModel::select(DB::raw('count(*) as count, order_status'))
                     ->where(['order_pay_status'=>1,'order_type_model'=>1])
                     ->groupBy('order_status')
                     ->get();
        $data['market_order_pay_status_count'] = GoodsOrderModel::select(DB::raw('count(*) as count, order_pay_status'))
                     ->where(['order_type_model'=>1])
                     //->where('order_pay_status','!=',1)
                     ->groupBy('order_pay_status')
                     ->get();

        //中医馆
        $data['zhongyi_goods_count'] = LifeGoods::where(['goods_is_del'=>0,'goods_shop_id'=>32])->count();//产品总数
        $data['zhongyi_goods_on_count'] = LifeGoods::where(['goods_is_del'=>0,'goods_status'=>1,'goods_shop_id'=>32])->count();//已上架产品数
        $data['zhongyi_goods_off_count'] = LifeGoods::where(['goods_is_del'=>0,'goods_status'=>2,'goods_shop_id'=>32])->count();//已上架产品数
        $data['zhongyi_order_count'] = GoodsOrderModel::where(['order_type_model'=>3])->count();
        $data['zhongyi_order_status_count'] = GoodsOrderModel::select(DB::raw('count(*) as count, order_status'))
                     ->where(['order_pay_status'=>1,'order_type_model'=>3])
                     ->groupBy('order_status')
                     ->get();
        $data['zhongyi_order_pay_status_count'] = GoodsOrderModel::select(DB::raw('count(*) as count, order_pay_status'))
                     ->where(['order_type_model'=>3])
                     //->where('order_pay_status','!=',1)
                     ->groupBy('order_pay_status')
                     ->get();

        //会员
        $data['user_type_count'] = User::select(DB::raw('count(*) as count, user_type'))
                     ->groupBy('user_type')
                     ->get();


        return json_success($data,'成功');
    }
}
