<?php

namespace App\Http\Controllers;

use Carbon\Carbon;
use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use App\Models\AlarmOrder;
use Illuminate\Support\Facades\DB;
use App\Models\AlarmOrderSchedule;
use Illuminate\Support\Facades\Auth;

class AlarmOrderController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $where = [];
        $whereBetween = [0, date('Y-m-d H:i:s')];
        $limit = 20;
        if($request->input('limit') > 0) {
            $limit = $request->input('limit');
        }
        $offset = $limit * ($request->input('page') - 1);
        if($request->input('isuser') == 'user'){

            $where[] = ['u.id','=',Auth::id()];
            print_r(explode(',',$request->input('userstate')));
        }
        if($request->input('order_num')) {
            $where[] = ['alarm_order.order_num' , '=', $request->input('order_num')];
        }
        if($request->input('deviceNum')) {
            $where[] = ['r.devicenumber' , '=', $request->input('deviceNum')];
        }
        if($request->input('state') != 99) {
            $where[] = ['alarm_order.state' , '=', $request->input('state')];
        }
        if($request->input('user_id')) {
            $where[] = ['alarm_order.user_id' , '=', $request->input('user_id')];
        }
        if($request->input('timeRange') != "null") {
            $times = explode(',', $request->input('timeRange'));
            $whereBetween = [$times[0], $times[1]];
        }
        $orders = AlarmOrder::selectRaw('
            FROM_UNIXTIME(r.starttime) AS start_time,
            FROM_UNIXTIME(r.endtime) AS end_time,
            alarm_order.*,
            r.devicenumber, r.concentration, r.location, r.policestatus, r.shutoff_status,
            d.devicecoord, d.username,t.tname,
            u.name, u.phone_number,
            s.status_name
            ')
            ->leftjoin('reportpolice AS r', 'r.id', '=', 'alarm_order.reportpolice_id')
            ->leftjoin('device AS d', 'd.id', '=', 'alarm_order.device_id')
            ->leftjoin('users AS u', 'alarm_order.user_id', '=', 'u.id')
            ->leftjoin('status AS s', 's.id', '=', 'r.policestatus')
            ->leftjoin('device_type AS t', 'r.policestatus', '=', 't.tid')
            ->offset($offset)
            ->where($where)
            ->whereBetween('alarm_order.created_at',$whereBetween)
            ->limit($limit)
            ->orderByDesc('id')
            ->get()->toArray();
        $count = AlarmOrder::leftjoin('reportpolice AS r', 'r.id', '=', 'alarm_order.reportpolice_id')
            ->leftjoin('users AS u', 'alarm_order.user_id', '=', 'u.id')
            ->whereBetween('alarm_order.created_at',$whereBetween)
            ->where($where)
            ->count();
        $meta = [
            'count' => $count,
            'current_page' => $request->input('page'),
            'limit' => $limit
        ];
        return $this->jsonSuccessData(compact('orders', 'meta'));

    }

    public function userworklist(Request $request){
        $orders = AlarmOrder::selectRaw('
            FROM_UNIXTIME(r.starttime) AS start_time,
            FROM_UNIXTIME(r.endtime) AS end_time,
            alarm_order.*,
            r.devicenumber, r.concentration, r.location, r.policestatus, r.shutoff_status,
            d.devicecoord, d.username,t.tname,
            u.name, u.phone_number,
            s.status_name
            ')
            ->leftjoin('reportpolice AS r', 'r.id', '=', 'alarm_order.reportpolice_id')
            ->leftjoin('device AS d', 'd.id', '=', 'alarm_order.device_id')
            ->leftjoin('users AS u', 'alarm_order.user_id', '=', 'u.id')
            ->leftjoin('status AS s', 's.id', '=', 'r.policestatus')
            ->leftjoin('device_type AS t', 'r.policestatus', '=', 't.tid')
            ->whereIn('alarm_order.state',explode(',',$request->input('userstate')))
            ->where('u.id','=',Auth::id())
            ->orderByDesc('id')
            ->get()->toArray();
        return $this->jsonSuccessData($orders);
    }
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $reportpolice_id = $request->input('reportpolice_id');
        $orderNum = date('YmdHis') .
            substr($request->input('device_num'), -4).
            $request->input('policestatus').
            $request->input('shutoff_status');

        DB::beginTransaction();
        try {
            // 获取device_id
            $device = DB::table('device')
                ->select('id')
                ->where('devicenum', $request->input('device_num'))
                ->first();
            if(!$device) {
                return $this->jsonErrorData(500, '设备编号不存在！');
            }
            $order = new AlarmOrder();
            $insertId = $order->insertGetId([
                'order_num' => $orderNum,
                'device_id' => $device->id,
                'user_id' => $request->input('user_id'),
                'reportpolice_id' => $reportpolice_id,
                'created_at' => Carbon::now(),
            ]);

            // 进度表新增
            $orderSchedule = new AlarmOrderSchedule();
            $orderSchedule->alarm_order_id = $insertId;
            $orderSchedule->schedule = 1;
            $orderSchedule->created_at = Carbon::now();
            $orderSchedule->save();
            DB::commit();
        } catch (QueryException $exception) {
            DB::rollBack();
            return $this->jsonErrorData(500,'工单创建失败');
        }

        if($insertId) {
            return $this->jsonSuccessData('已生成工单！');
        }else{
            return $this->jsonErrorData(500, '工单创建失败');
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show(Request $request)
    {

        $order = AlarmOrder::leftjoin('reportpolice AS r', 'r.id', '=', 'alarm_order.reportpolice_id')
            ->leftjoin('device AS d', 'd.id', '=', 'alarm_order.device_id')
            ->leftjoin('users AS u', 'alarm_order.user_id', '=', 'u.id')
            ->leftjoin('status AS s', 's.id', '=', 'r.policestatus')
            ->leftjoin('device_type AS t', 'r.policestatus', '=', 't.tid')
            ->leftjoin('gas AS g', 'd.status', '=', 'g.id')
            ->leftjoin('danwei AS w', 'd.devicemonad', '=', 'w.id')
            ->where('alarm_order.id', '=', $request->input('id'))
            ->selectRaw('
            FROM_UNIXTIME(r.starttime) AS start_time,
            FROM_UNIXTIME(r.endtime) AS end_time,
            alarm_order.*,
            r.devicenumber, r.concentration, r.location, r.policestatus, r.shutoff_status,
            d.devicecoord, d.username,t.tname,d.deviceinfo,g.gas,w.danwei,
            u.name, u.phone_number,
            s.status_name
            ')
            ->first();
        // 工单进度
        $order['step'] = AlarmOrderSchedule::where('alarm_order_id', '=', $request->input('id'))->get();
        // 图片
        $order['images'] = DB::table('userimage')
            ->select('path')
            ->where('alarm_order_id', $request->input('id'))
            ->get()->toArray();
       return $this->jsonSuccessData($order);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {
        $data = $request->all();
        if(isset($data['schedule'])) {
            DB::beginTransaction();
            try {
                AlarmOrderSchedule::insert(array_merge(
                    json_decode($data['schedule'],true),
                    ['created_at' => Carbon::now(), 'alarm_order_id' => $data['id']]));
                unset($data['schedule']);
                $order = AlarmOrder::where('id', $data['id'])
                    ->update(array_merge($data, ['updated_at' => Carbon::now()]));
                DB::commit();
            } catch (QueryException $exception) {
                DB::rollBack();
                return $this->jsonErrorData(500, '工单更新失败！');
            }

        }else{
            $order = AlarmOrder::where('id', $data['id'])
                ->update(array_merge($data, ['updated_at' => Carbon::now()]));
        }
        if($order) {
            return $this->jsonSuccessData('工单更新成功');
        }else{
            return $this->jsonErrorData(500, '工单更新失败！');
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $state = AlarmOrder::destroy($id);
        if($state) {
            return $this->jsonSuccessData('删除成功');
        }else{
            return $this->jsonErrorData(500, '删除工单失败！');
        }
    }

    /**
     * 获取派单用户
     */
    public function getUserInfo()
    {
        if ($this->isadmin()) {
            $users = DB::table('users')
                ->select('users.id', 'users.name', 'users.username', 'users.phone_number', 'ur.name AS role_name', 'ap.area_name AS province', 'aa.area_name AS area', 'ac.area_name AS city')
                ->leftJoin('user_roles AS ur', 'ur.id', '=', 'users.user_role_id')
                ->leftJoin('areachina AS ap', 'ap.areaid', '=', 'users.provinceid')
                ->leftJoin('areachina AS aa', 'aa.areaid', '=', 'users.areaid')
                ->leftJoin('areachina AS ac', 'ac.areaid', '=', 'users.cityid')
                ->where('users.user_role_id', '!=', 0)
                ->get()->toArray();
            return $this->jsonSuccessData($users);
        } else {
            return $this->jsonErrorData(500, '没有权限, 请联系管理员！');
        }
    }

    //获取当前订单为第几步
    public function orderin(Request $request){
        $orderid = $request->input('id');
        $status = AlarmOrder::where('id','=',$orderid)->select('isorderone','id')->first();
        return $this->jsonSuccessData($status);
    }
}
