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

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

    public function CheckOrder(){
        $order_sn = input('param.order_sn');
        //todo 检查订单是否存在。
        //1,如果订单已经存在，并且在传入的柜子和箱子中，返回正确，做一下操作记录。
        //2,如果订单已经存在，但不在传入的柜子和箱子中，返回错误。
        //3,其余返回正确。

        //商网接口
        $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;
            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();

        $cabinet_number = $cabinet['id'];
        $checkNumber = $this->hasBox($cabinet_number , $trunk);
        if($checkNumber == false){
            json_error(2004);
        }
        $code = $this->createRandCode();
        $ret  = $this->CreateOrder($order_sn , $trunk , $cabinet_number,$code);

        if($ret['code'] != 1) {
            json_error(1006);
        }
        else {
            $alias = $cabinet['alias'];
            $this->box_action_record($cabinet_number , $trunk , 1 , $order_sn , $alias);

            $msg = "{$alias}柜门{$trunk}箱门，密码信息{$code}";
            $postData['orderCode'] = $order_sn;
            $postData['boxMsg'] = $msg;
            $postData = json_encode($postData);
            $result = http_post_json(self::base_url . '/deliver' , $postData);
            if($result == false){
                json_error(3000);
            }
            $result = json_decode($result,true);
            if($result['code'] != 0){
                json_return($result['code'] , [] , $result['message']);
            }

            $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){
            json_error(3000);
        }
        $result = json_decode($result,true);
        if($result['code'] != 0){
            json_return($result['code'] , [] , $result['message']);
        }
        //todo 存消息
        $msg = "{$cabinet['alias']}柜门{$trunk}箱门";
        $this->CreateMsg($cabinet_number,$trunk,$msg,$order_sn,2);
        $this->box_action_record($cabinet_number , $trunk , 2 , $cabinet ,$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;

        $OrderModel = new OrderModel();
        $selectResult = $OrderModel->getOrdersByWhere($offset, $limit);
        $order_status = ['1' => '已存入' , '2' => '已取走'];
        // 拼装参数
        foreach($selectResult as $key=>$vo){
            $selectResult[$key]['order_status'] = $order_status[$vo['order_status']];
            if($vo['out_time'] == null){
                $selectResult[$key]['out_time'] = '';
            }
        }
        $return['total'] = $OrderModel->getAllCounts();  //总数量
        $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(2004);
        }
        $cabinet = CabinetModel::find($cabinet_number);
        $alias = $cabinet['alias'];
        $code = $box['fetch_code'];
        $msg = "{$alias}柜门{$box_number}箱门，密码信息{$code}";
        $postData['orderCode'] = $order_sn;
        $postData['boxMsg'] = $msg;
        $postData = json_encode($postData);
        $result = http_post_json(self::base_url . '/deliver' , $postData);
        if($result == false){
            json_error(3000);
        }
        $result = json_decode($result,true);
        if($result['code'] != 0){
            json_return($result['code'] , [] , $result['message']);
        }
        $this->CreateMsg($cabinet_number,$box_number,$msg,$order_sn,3);
        json_success($result['data']);
    }

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

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