<?php

namespace app\index\controller;

use app\index\model\BoxActionModel;
use app\index\model\BoxModel;
use app\index\model\CabinetModel;
use app\index\model\MsgModel;
use app\index\model\OrderModel;
use think\facade\Log;

class Order extends Base
{
    const base_url = 'https://yxmall-adminportal.eavic.com/oms-web/box';

    public function CheckOrder(){
        $order_sn = input('param.order_sn');

        //商网接口
        $postData['orderCode'] = $order_sn;
        $postData = json_encode($postData);
        $result = http_post_json(self::base_url . '/check' , $postData);
        if($result == false){
            json_error(3000);
        }
        $result = json_decode($result,true);
        if(!empty($result) && $result['code'] == 0) {
            $existed = $result['data']['isEffective'] != 0;
            if($existed == true){
                $BoxModel = new BoxModel();
                $order = $BoxModel->where('order_sn',$order_sn)->find();
                if(!empty($order)){
                    $existed = false;
                }
            }
            json_success(['order_sn' => $order_sn,'existed' => $existed]);
        }
        else {
            json_return($result['code'],[],$result['message']);
        }
    }

    /**
     * 自提柜向服务器上报
     */
    public function RecordStore()
    {
        $order_sn = input('param.order_sn');
        $trunk = input('param.trunk');
        $cabinet_code = input('param.cabinet');

        $cabinet = CabinetModel::where('cabinet_code', $cabinet_code)->find();
        if (empty($cabinet)) {
            json_error(1008, '找不到柜子');
        }
        $cabinet_number = $cabinet['id'];

        $code = $this->createRandCode();
        $ret = $this->CreateOrder($order_sn, $trunk, $cabinet_number, $code);

        if ($ret['code'] != 1) {
            json_error(1006);
        }

        return $this->report($order_sn, $cabinet_number,$cabinet['alias'], $trunk, $code);
    }

    private function report($order_sn,$cabinet_number,$alias,$trunk, $code)
    {
        $url = self::base_url . '/deliver';

        $msg = "{$alias}柜门{$trunk}箱门，取件码{$code}";
        $postData['orderCode'] = $order_sn;
        $postData['boxMsg'] = $msg;
        $postData = json_encode($postData);
        Log::record("report msg:{$msg}");

        $max_times = 5;
        for ($i=0; $i < $max_times ; $i++) {
            $result = http_post_json($url, $postData);
            if($result != false) {
                break;
            }
            else {
                Log::record("repost Error:{$i} : {$result}");
            }
        }

        if ($result == false) {
            Log::record('RecordStore Error:' . $result);
            $msg = "商网连接错误,错误信息：{$result}";
            $this->CreateMsg($cabinet_number, $trunk, $msg, $order_sn, 4);
            json_error(3000);
        }
        else
        {
            Log::record("RecordStore Success result:{$result}");
            $result = json_decode($result,true);
            if($result['code'] != 0){
                $msg = "错误码：{$result['code']},错误信息：{$result['message']}";
                $this->CreateMsg($cabinet_number,$trunk,$msg,$order_sn,4);
                json_return($result['code'] , [] , $result['message']);
            }
            else {
                $this->box_action_record($cabinet_number , $trunk , 1 , $order_sn , $alias);
                $this->CreateMsg($cabinet_number,$trunk,$msg,$order_sn,1);
                json_success([]);
            }
        }
    }

    public function CheckFcode(){
        $code = input('param.code');
//        $cabinet_code = input('param.cabinet');

        $BoxModel = new BoxModel();
        $box = $BoxModel->CheckCode($code);
        if(empty($box)){
            json_error(2003);
        }

        //返回access
        $data['code'] = $code;
        $data['existed'] = true;
        $data['trunk'] = $box['box_number'];
        $cabinet = CabinetModel::where('id',$box['cabinet_number'])->find();
        $data['cabinet'] = $cabinet['cabinet_code'];

        json_success($data);
    }

    public function RecordFetch(){
        $trunk      = input('param.trunk');
        $cabinet_code    = input('param.cabinet');
        $cabinet = CabinetModel::where('cabinet_code',$cabinet_code)->find();
        $cabinet_number = $cabinet['id'];
        $BoxModel = new BoxModel();
        $Box = $BoxModel->getOneCabinetBox($cabinet_number , $trunk);
        if(empty($Box)){
            json_error(2004);
        }
        $ret = $BoxModel->editData(['cabinet_number' => $cabinet_number , 'box_number' => $trunk] ,
            ['order_sn' => '' , 'box_status' => 1, 'fetch_code' => '']);
        if($ret['code'] != 1){
            json_error(1006);
        }
        $OrderModel = new OrderModel();
        $OrderModel->editData(['order_sn' => $Box['order_sn']] , ['order_status' => 2 , 'out_time' => date("Y-m-d H:i:s")]);
        $order_sn = $Box['order_sn'];
        $postData['orderCode'] = $order_sn;
        $postData = json_encode($postData);
        $result = http_post_json(self::base_url . '/receive' , $postData);
        if($result == false){
            Log::record('RecordFetch Error:'.$result);
            json_error(3000);
        }
        Log::record('RecordFetch Success:');
        Log::record($result);
        $result = json_decode($result,true);
        if($result['code'] != 0){
            json_return($result['code'] , [] , $result['message']);
        }
        // 存消息
        $msg = "{$cabinet['alias']}柜门{$trunk}箱门";
        $this->CreateMsg($cabinet_number,$trunk,$msg,$order_sn,2);
        $this->box_action_record($cabinet_number , $trunk , 2 , $order_sn ,$cabinet['alias']);
        json_success([]);
    }

    public function ManualSave(){
        $order_sn   = input('param.order_sn');
        $box_number = input('param.box_number');
        $cabinet_number = input('param.cabinet_number');
        $BoxModel = new BoxModel();
        $box = $BoxModel->where(['cabinet_number' => $cabinet_number , 'box_number' => $box_number , 'order_sn' => $order_sn])->find();
        if(empty($box)){
            json_error(2004);
        }
        $cabinet = CabinetModel::where('id',$cabinet_number)->find();
        $ret = $BoxModel->editData(['cabinet_number' => $cabinet_number , 'box_number' => $box_number] ,
            ['order_sn' => '' , 'box_status' => 1, 'fetch_code' => '']);
        if($ret['code'] != 1){
            json_error(1006);
        }
        $OrderModel = new OrderModel();
        $OrderModel->editData(['order_sn' => $order_sn] , ['order_status' => 2 , 'out_time' => date("Y-m-d H:i:s")]);
        $postData['orderCode'] = $order_sn;
        $postData = json_encode($postData);
        $result = http_post_json(self::base_url . '/receive' , $postData);
        if($result == false){
            Log::record('ManualSave Error:'.$result);
            json_error(3000);
        }
        Log::record('ManualSave Success:');
        Log::record($result);

        $result = json_decode($result,true);
        if($result['code'] != 0){
            json_return($result['code'] , [] , $result['message']);
        }
        // 存消息
        $msg = "{$cabinet['alias']}柜门{$box_number}箱门";
        $this->CreateMsg($cabinet_number,$box_number,$msg,$order_sn,2);
        $this->box_action_record($cabinet_number , $box_number , 2 , $order_sn ,$cabinet['alias']);
        json_success([]);
    }

    public function OrderList(){
        $param = input('param.');

        $limit = isset($param['pageSize']) ? $param['pageSize'] : 10;
        $param['pageNumber'] = isset($param['pageNumber']) ? $param['pageNumber'] : 1;
        $offset = ($param['pageNumber'] - 1) * $limit;
        $where = $TimeWhere = [];
        if(!empty($param['order_sn'])){
            $where['sc_order.order_sn'] = $param['order_sn'];
        }
        if(!empty($param['start_time']) && !empty($param['end_time'])){
            if($param['start_time'] > $param['end_time'] || strtotime($param['end_time']) > time()){
                json_error(1007,'日期有误');
            }
            $start_time = $param['start_time'];
            
            
            $end_time = $param['end_time'];
            $TimeWhere[] = ['enter_time','between',"$start_time,$end_time"];
        }
        $OrderModel = new OrderModel();
        $selectResult = $OrderModel->getOrdersByWhere($where,$offset, $limit,$TimeWhere);
        $order_status = ['1' => '已存入' , '2' => '已取走'];
        $CabinetModel = new CabinetModel();
        // 拼装参数
        foreach($selectResult as $key=>$vo){
            $selectResult[$key]['order_status'] = $order_status[$vo['order_status']];
            $selectResult[$key]['enter_time'] = date("m-d H:i",strtotime($vo['enter_time']));
            if($vo['out_time'] == null){
                $selectResult[$key]['out_time'] = '';
            }else{
                $selectResult[$key]['out_time'] = date("m-d H:i",strtotime($vo['out_time']));
            }
            $cabinet = $CabinetModel->find($vo['cabinet_number']);
            $selectResult[$key]['alias'] = $cabinet['alias'];
        }
        $return['total'] = $OrderModel->getAllCounts($where,$TimeWhere);  //总数量
        $return['rows'] = $selectResult;
        json_success($return);
    }

    public function SendMsg(){
        $order_sn   = input('param.order_sn');
        $box_number = input('param.box_number');
        $cabinet_number = input('param.cabinet_number');

        $box = BoxModel::where(['cabinet_number' => $cabinet_number , 'box_number' => $box_number , 'order_sn' => $order_sn])->find();
        if(empty($box)){
            json_error(2002);
        }
        $cabinet = CabinetModel::find($cabinet_number);
        $alias = $cabinet['alias'];
        $code = $box['fetch_code'];

        return $this->report($order_sn,$cabinet_number,$alias,$box_number,$code);
    }

    private function hasBox($cabinet_number , $box_number)
    {
        $BoxModel = new BoxModel();
        return $BoxModel->getOneCabinetBox($cabinet_number , $box_number);
    }

    private function CreateMsg($cabinet_number , $box_number , $msg , $order_sn , $type){
        $MsgModel = new MsgModel();
        $params['cabinet_number']       = $cabinet_number;
        $params['box_number']           = $box_number;
        $params['order_sn']             = $order_sn;
        $params['msg']                  = $msg;
        $params['type']                 = $type;
        $params['datetime']             = date("Y-m-d H:i:s");
        $MsgModel->save($params);
    }
    /**
     * 生成订单并绑定箱子
    */
    private function CreateOrder($order_sn , $box_number , $cabinet, $code)
    {
        $data['order_sn'] = $order_sn;
        $data['cabinet_number'] = $cabinet;
        $data['box_number'] = $box_number;
        $data['code'] = $code;
        $data['enter_time'] = date("Y-m-d H:i:s");

        $OrderModel = new OrderModel();
        return $OrderModel->CreateOrder($data);
    }

    /**
     * 记录箱子开启/关闭
     */
    private function box_action_record($cabinet_number , $box_number , $type , $order_sn , $cabinet_alias){
        $BoxActionModel = new BoxActionModel();
        $params['cabinet_number']       = $cabinet_number;
        $params['box_number']           = $box_number;
        $params['order_sn']             = $order_sn;
        $params['cabinet_alias']        = $cabinet_alias;
        $params['type']                 = $type;
        $params['datetime']             = date("Y-m-d H:i:s");
        $BoxActionModel->save($params);
    }

    /**
     * 生成校验码
    */
    private function createRandCode()
    {
        while (true)
        {
            $code = rand(100000,999999);
            $BoxModel = new BoxModel();
            $box = $BoxModel->where('fetch_code',$code)->find();
            if(empty($box)){
                return $code;
            }
        }
    }
}