<?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;

class AlarmOrderController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        if($this->isadmin()) {
            $limit = 20;
            $offset = $limit * ($request->input('page') - 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,
            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', '=', 'alarm_order.reportpolice_id')
                ->offset($offset)
                ->limit($limit)
                ->get()->toArray();
            return $this->jsonSuccessData($orders);
        }else{
            return $this->jsonErrorData(500, '没有权限，请联系管理员');
        }


    }

    /**
     * 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 {
            $order = new AlarmOrder();
            $insertId = $order->insertGetId([
                'order_num' => $orderNum,
                'device_id' => $request->input('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('工单创建失败');
        }

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

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $order = AlarmOrder::select('*')
            ->join('reportpolice AS r', 'r.id', '=', 'alarm_order.reportpolice_id')
            ->where('alarm_order.id', '=', $id)
            ->get();
        $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, $id)
    {
        $data = $request->all();

        if(isset($data['schedule'])) {
            DB::beginTransaction();
            try {
                AlarmOrderSchedule::insert(array_merge(
                    $data['schedule'],
                    ['created_at' => Carbon::now(), 'alarm_order_id' => $id]));
                unset($data['schedule']);
                $order = AlarmOrder::where('id', $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', $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, '删除工单失败！');
        }
    }
}
