<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use think\Exception;

class Order extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = Db::name('order');
    }

    /**
     * 列表
     * @return void
     */
    public function getList(){
        try {
            $status = input('status',0);//状态:1=待支付,2=待处理,3=已完成,4=已取消

            $o = 'order';
            $st = 'servicetype';
            $field = $o.'.id,orderno,server_time,server_info,server_images,status,user_mobile,'.$o.'.user_car_number,'.
                $o.'.createtime,cancel_time,cancel_reason,pay_fee,appen_fee,finish_time,'.$st.'.title as `service_title`,paytype';
            $where[$o.'.user_id'] = $this->auth->id;
            $where[$o.'.company_id'] = $this->auth->company_id;
            if (!empty($status)) {
                $where[$o.'.status'] = $status;
            }
            $result = $this->model->alias($o)->field($field)
                ->join($st,$st.'.id = '.$o.'.servicetype_id','LEFT')
                ->where($where)->order($o.'.createtime desc')->autopage()->select();
            if (!empty($result)) {
                $statusArr  = [2=>'待处理',3=>'已完成',4=>'已取消'];
                $paytypeArr = [1=>'线下',2=>'余额',3=>'微信'];
                $timeArr = ['createtime','cancel_time','finish_time','server_time'];
                foreach ($result as $key => &$value) {
                    foreach ($timeArr as $k => $v) {
                        $value[$v] = !empty($value[$v]) ? date('Y年m月d日 H:i:s', $value[$v]) : '';
                    }
                    $value['total_amounts'] = bcadd($value['pay_fee'],$value['appen_fee'],2);
                    $value['status_text'] = isset($statusArr[$value['status']]) ? $statusArr[$value['status']] : '';
                    $value['paytype_text'] = isset($paytypeArr[$value['paytype']]) ? $paytypeArr[$value['paytype']] : '';
                }
                $result = list_domain_image($result,['server_images']);
            }

            $this->success('获取成功', $result);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 套餐列表
     * @return void
     */
    public function getPackageList(){
        try {
            $status = input('status',0);//状态:1=待使用,2=已核销

            $o = 'order';
            $st= 'servicetype';
            $p = 'package';

            $field = $o.'.id,server_info,'.$o.'.servicetype_id,'.$st.'.title as `service_title`,'.$p.'.title as `package_title`,'.
            $p.'.images as `package_images`,hexiao_time';

            $where[$o.'.user_id'] = $this->auth->id;
            $where[$o.'.company_id'] = $this->auth->company_id;
            $where[$o.'.ordertype'] = 3;//类型:1=预约下单,2=在线下单,3=套餐订单
            $where[$o.'.status'] = ['in',[1,2,3]];//状态:2=待处理,3=已完成,4=已取消
            if (!empty($status)) {
                if ($status == 1) {
                    $where[$o.'.hexiao_time'] = 0;
                }
                if ($status == 2) {
                    $where[$o.'.hexiao_time'] = ['gt',0];
                }
            }
            $result = $this->model->alias($o)->field($field)
                ->join($st,$st.'.id = '.$o.'.servicetype_id','LEFT')
                ->join($p,$p.'.id = '.$o.'.package_id','LEFT')
                ->where($where)->order($o.'.createtime desc')->autopage()->select();
            if (!empty($result)) {
                foreach ($result as $key => &$value) {
                    $value['is_check'] = !empty($value['hexiao_time']) ? 1 : 0;
                }
                $result = list_domain_image($result,['package_images']);
            }

            $this->success('获取成功', $result);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 详情
     * @return void
     */
    public function getInfo(){
        try {
            $id = input('id',0);
            $payOrderId = input('pay_order_id',0);
            if (!empty($payOrderId)) {
                $orderWhere['pay_order_id'] = $payOrderId;
                $order = Db::name('order')->field('id')->where($orderWhere)->find();
                $id = isset($order['id']) ? $order['id'] : 0;
            }
            $o = 'order';
            $st = 'servicetype';
            $where[$o.'.user_id'] = $this->auth->id;
            $where[$o.'.id'] = $id;
            $field = $o.'.id,orderno,server_time,server_info,server_images,status,user_mobile,'.$o.'.user_car_number,'.
                $o.'.createtime,cancel_time,cancel_reason,pay_fee,appen_fee,finish_time,'.$st.'.title as `service_title`,paytype';
            $result = $this->model->alias($o)->field($field)
                ->join($st,$st.'.id = '.$o.'.servicetype_id','LEFT')
                ->where($where)->find();
            if (!empty($result)) {
                $statusArr  = [2=>'待处理',3=>'已完成',4=>'已取消'];
                $paytypeArr = [1=>'线下',2=>'余额',3=>'微信'];
                $timeArr = ['createtime','cancel_time','finish_time','server_time'];
                foreach ($timeArr as $k => $v) {
                    $result[$v] = !empty($result[$v]) ? date('Y年m月d日 H:i:s', $result[$v]) : '';
                }
                $result['total_amounts'] = bcadd($result['pay_fee'],$result['appen_fee'],2);
                $result['status_text'] = isset($statusArr[$result['status']]) ? $statusArr[$result['status']] : '';
                $result['paytype_text'] = isset($paytypeArr[$result['paytype']]) ? $paytypeArr[$result['paytype']] : '';
                $orderAppenWhere['order_id'] = $id;
                $orderAppen = Db::name('order_appen')->where($orderAppenWhere)->select();
                $appenList = [];
                if (!empty($orderAppen)) {
                    foreach ($orderAppen as $key => $value) {
                        $appenList[] = [
                            'name' => $value['name'],
                            'price' => $value['price'],
                        ];
                    }
                }
                $result['appen_list'] = $appenList;
                $result = info_domain_image($result,['server_images']);
            }

            $this->success('获取成功', $result);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 核销码
     * @return void
     */
    public function writeOff()
    {
        try {
            $id = $this->request->param('id',0);
            $payOrderId = input('pay_order_id',0);
            if (!empty($payOrderId)) {
                $orderWhere['pay_order_id'] = $payOrderId;
                $order = Db::name('order')->field('id')->where($orderWhere)->find();
                $id = isset($order['id']) ? $order['id'] : 0;
            }
            $companyId = $this->auth->company_id;
            $userId = $this->auth->id;
            $where['id'] = $id;
            $where['company_id'] = $companyId;
            $where['user_id'] = $userId;
            $where['status'] = 2;
            $modelData = $this->model->where($where)->find();
            if (empty($modelData)) {
                throw new Exception('未找到相关信息');
            }

            $text = 'hexiaoorder_'.$id;
            $logo = '';
            $filRoute = '/uploads/temp/';
            $saveDir = ROOT_PATH.'public'.DS.'uploads'.DS.'temp'.DS;
            $fileStr = md5('order_'.$id);
            $localpng = $saveDir.$fileStr.'.png';
            //验证存在直接返回
            $userCouponsUrl = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].$filRoute.$fileStr.'.png';
            if (!file_exists($localpng)) {
                build_qrcode($text, $logo, $saveDir,$fileStr);
            }
            $result = [
                'url' => $userCouponsUrl,
            ];
            $this->success('获取成功',$result);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }
    
    /**
     * 保养列表
     * @return void
     */
    public function upkeepList()
    {
        try {
            $serviceTypeId = input('servicetype_id',0);
            $carId = input('car_id',0);
            $carNumber = input('car_number','');
            $o = 'order';
            $st = 'servicetype';
            if (!empty($serviceTypeId)) {
                $where[$o.'.servicetype_id'] = $serviceTypeId;
            }
            if (!empty($carNumber)) {
                $where[$o.'.user_car_number'] = $carNumber;
            } else {
                if (!empty($carId)) {
                    $where[$o.'.user_car_id'] = $carId;
                }
            }
            $where[$o.'.user_id'] = $this->auth->id;
            $where[$o.'.status'] = ['in',[2,3]];//状态:2=待处理,3=已完成,4=已取消
            $where[$st.'.is_upkeep'] = 1;//是否保养:1=是,0=否
            $field = $o.'.id,servicetype_id,server_info,finish_time,next_date,next_carlicheng,pay_fee,appen_fee,'.$st.'.title as `service_title`';
            $result = $this->model->alias($o)->field($field)
                ->join($st,$st.'.id = '.$o.'.servicetype_id','LEFT')
                ->where($where)->order($o.'.finish_time desc')->autopage()->select();
            if (!empty($result)) {
                $timeArr = ['finish_time'];
                foreach ($result as $key => &$value) {
                    foreach ($timeArr as $k => $v) {
                        $value[$v] = !empty($value[$v]) ? date('Y-m-d', $value[$v]) : '';
                    }
                    $value['total_amounts'] = bcadd($value['pay_fee'],$value['appen_fee'],2);
                }
            }
            
            $this->success('获取成功',$result);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }
}