<?php

namespace frontend\controllers;

use common\libs\MyLib;
use common\models\CarGiftT;
use common\models\CarT;
use common\models\GiftGroupT;
use common\models\OrderGiftT;
use common\models\OrderT;
use common\models\OrderUserT;
use common\models\UserT;
use Yii;
use yii\data\Pagination;
use yii\helpers\VarDumper;
use yii\web\Response;

class PrintController extends BaseController
{
    public $my = null;
    public function init()
    {
        parent::init();

        $cookie = Yii::$app->request->cookies;
        $user_id = MyLib::encrypt($cookie->get('aid'),'DECODE');

        if($user_id != 0)
        {
            $this->my = UserT::findOne(['id'=>$user_id]);
        } else {
            Yii::$app->response->redirect('/common/login')->send();
            exit;
        }
    }

    /**
     * 送单表打印-列表
     * @return string
     */
    public function actionSendMng()
    {
        $request = Yii::$app->request;
        $car_man = $request->get('car_man');
        $phone = $request->get('phone');
        $car_no = $request->get('car_no');
        $send_date = $request->get('send_date');
        $page = $request->get('page',1);
        if($page < 1) $page = 1;

        $query = OrderT::find()
            ->where('status_id=3')
            ->orderBy('submit_date DESC, id DESC');
        if($car_man != '') {
            $query = $query->andWhere('car_man="'.$car_man.'"');
        }
        if($phone != '') {
            $query = $query->andWhere('link_phone="'.$phone.'"');
        }
        if($car_no != '') {
            $query = $query->andWhere('car_no="'.$car_no.'"');
        }
        if($send_date != '') {
            $query = $query->andWhere('send_date="'.$send_date.'"');
        }
        $query = $query->orderBy('updated_at asc');
        $total = $query->count();

        $pagination = new Pagination(['totalCount' => $total,'pageSize'=>20]);
        $pagination->setPage($page-1);

        $query = $query->offset($pagination->offset)->limit($pagination->limit);
        $items = $query->all();

        $page_info = MyLib::getPageInfo($pagination);


        return $this->render('send-mng',[
            'items' => $items,
            'car_man' => $car_man,
            'phone' => $phone,
            'car_no' => $car_no,
            'send_date' => $send_date,
            'page' => $page,
            'page_info' => $page_info
        ]);
    }

    /**
     * 送单表打印-详情
     * @return string
     */
    public function actionSendMngEdit()
    {
        $request = Yii::$app->request;
        $id = $request->get('id',0);
        $back_params = $request->get('back_params');
        $order_info = OrderT::findOne(['id'=>$id]);

        if($order_info->lock_id == 0) {
            $tran = OrderT::getDb()->beginTransaction();
            try {
                $order_info->lock_id = $this->my->id;
                $order_info->save();

                $order_user_info = new OrderUserT();
                $order_user_info->user_id = $this->my->id;
                $order_user_info->order_id = $order_info->id;
                $order_user_info->type_id = $order_info->status_id;
                $order_user_info->status = 0;
                $order_user_info->save();

                $tran->commit();
            } catch (\Exception $e) {
                $tran->rollBack();
                throw $e;
            }
        } else {
            if($order_info->lock_id != $this->my->id) {
                echo '该记录已经被别人锁定,【<a href="/print/send-mng">返回</a>】';
                exit;
            }
        }
        $gift_items = CarGiftT::find()
            ->where('order_id='.$order_info->id)
            ->orderBy('strategy_id DESC')
            ->all();
        $gift_str = '';
        foreach($gift_items as $item) {
            if(!$item->gift) continue;
            $gift_str .= $item->gift->name.',';
        }
        //礼品
        $gift_group_items = GiftGroupT::find()->all();
        //获取礼品数据
        $sel_gifts = array();
        $tmp_items = OrderGiftT::find()
            ->where('order_id='.$order_info->id)
            ->all();
        foreach($tmp_items as $item) {
            $sel_gifts[$item->group_id] = $item;
        }

        return $this->render('send-mng-edit',[
            'order_info'=>$order_info,
            'back_params' => $back_params,
            'gift_group_items' => $gift_group_items,
            'sel_gifts' => $sel_gifts
        ]);
    }

    /**
     * 送单表打印-保存
     * @return array
     * @throws \Exception
     */
    public function actionSendMngSave()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '保存失败';

        if($request->isPost) {
            $order_id = $request->post('order_id',0);
            $status_id = $request->post('status_id',0);

            $tran = OrderT::getDb()->beginTransaction();
            try {
                $order_info = OrderT::findOne(['id'=>$order_id]);
                if(empty($order_info)) {
                    $result['msg'] = '保单错误!';
                    return $result;
                }

                $old_status_id = $order_info->status_id;
                $order_info->status_id = $status_id;
                if($status_id > $old_status_id) {
                    $order_info->lock_id = 0;
                    $this->addLog($order_info->car_id,'送单表打印完毕,进入配送调度',1);

                    //处理操作人员状态
                    $order_user_info = OrderUserT::findOne(['order_id'=>$order_info->id,'user_id'=>$this->my->id,'type_id'=>$old_status_id,'status'=>0]);
                    if($order_user_info) {
                        $order_user_info->status = 1; //操作结束
                        $order_user_info->save();
                    }
                }
                $order_info->save();

                $tran->commit();

            } catch(\Exception $e) {
                $tran->rollBack();
                throw $e;
            }

            $result['success'] = true;
            $result['msg'] = '保存成功';
        }
        return $result;
    }

    public function actionOpSendPrint()
    {
        $request = Yii::$app->request;
        $params = $request->post();

        return $this->renderPartial('op-send-print',[
            'params'=>$params
        ]);
    }
    private function curldebang($parm)
    {
        header("Content-type: text/html; charset=utf-8");
        $uri = "http://gwapi.deppon.com/dop-interface-async/dop-standard-ewborder/ewbNewSaveOrder.action";

        list($t1, $t2) = explode(' ', microtime());

        $timestamp = (float)sprintf('%.0f',(floatval($t1) + floatval($t2)) * 1000);

        $appkey = 'd4f7d7473ba3a22bc06bf939135a84f5';

        $bianma = 'EWBCHBJQCFWYXGS';

        $sign = 'LKUE12345678';

        $parmas = [
            'backSignBill' => 0,
            'cargoName' => "保单和礼品",

            //'logisticID' => $sign.time(),//订单ID
            // 'logisticID' => 'QDGHFMMYYXGS1512985995',//订单ID

            'customerCode' => '400996024',
            'customerID' => $bianma,
            "deliveryType"=> 0,
            "logisticCompanyID"=>"DEPPON",
            'orderSource' => $bianma,
            'logisticID' => $sign.time(),
            'serviceType' => 2, //1、零担在线订单 2、快递在线订单
            'payType' => '2',
            'gmtCommit' => date('Y-m-d H:i:s'),

            'sender' => [
                'name' => $parm['sender_name'],
                'phone' => '01083298300',
                'mobile' => '01083298300',
                'province' => '北京',
                'city' => '北京市',
                'county' => '丰台区',
                'address' => '五里店西59号',
            ],
            'receiver' => [
                'name' => $parm['insurer_name'],
                'phone' => $parm['link_tel'],
                'province' => $parm['receiver_province'],
                'city' => $parm['receiver_city'],
                'county' => $parm['receiver_county'],
                'address' => $parm['receiver_address'],
            ],
            'totalNumber' => 1,
            'totalWeight' => 30,
            'transportType' => 'PACKAGE',//PACKAGE: 标准快递; RCP :360特惠件;   这两个,3KG以内是标准快递,超过3KG是360特惠。
            'vistReceive' => 'Y',

        ];
        $senderinfo=$parmas['sender'];
        $parmas = json_encode($parmas);

        $digest = base64_encode(md5($parmas . $appkey . $timestamp));

        $data = array (
            'companyCode'=> $bianma,
            'params'=> $parmas,
            'digest'=> $digest,
            'timestamp'=> $timestamp
        );

        $ch = curl_init();//初始化curl
        curl_setopt($ch,CURLOPT_URL,$uri);//访问地址
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);//是否自动输出内容
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data );
        $result = curl_exec($ch);
        curl_close($ch);
        $result=json_decode($result,true);
        $returnda['returnResult']=$result;
        $returnda['senderdata']=$senderinfo;
        return $returnda;

    }
    public function actionOpEmsPrint()
    {
        $request = Yii::$app->request;
        $params = $request->get();

        return $this->renderPartial('op-ems-print',[
            'params'=>$params
        ]);
    }
    public function actionOpEmsPrint1()
    {
        $request = Yii::$app->request;
        $params = $request->get();
        $returnData=$this->curldebang($params);
//        var_dump($params);
//        dd($returnData);
//        var_dump($returnData['result']);
        if(!$returnData['returnResult']['result']){
            echo '请求德邦快递接口失败';
            return false;
        }
//        dd($returnData['returnResult']['mailNo']);
        if($returnData['returnResult']['mailNo']){
           $order_info= OrderT::findOne(['id'=>$request->get('order_id')]);
            $order_info->mail_no=$returnData['returnResult']['mailNo'];
            $order_info->save();

        }
//        die;
        return $this->renderPartial('op-ems-print1',[
            'params'=>$params,
            'mailNo'=>$returnData['returnResult']['mailNo'],
            'bigNo'=>$returnData['returnResult']['sortingParam']['bigPen'],
            'sender'=>$returnData['senderdata'],
            'time'=>date('Y/m/d H:i:s'),
        ]);
    }
    public function actionOpEmsPrint2()
    {
        $request = Yii::$app->request;
        $params = $request->get();
        $returnData=$this->curldebang($params);
//        var_dump($params);
//        dd($returnData);
//        var_dump($returnData['result']);
        if(!$returnData['returnResult']['result']){
            echo '请求德邦快递接口失败';
            return false;
        }
//        dd($returnData['senderdata']);

//        die;
        return $this->renderPartial('op-ems-print2',[
            'params'=>$params,
            'mailNo'=>$returnData['returnResult']['mailNo'],
            'bigNo'=>$returnData['returnResult']['sortingParam']['bigPen'],
            'sender'=>$returnData['senderdata'],
            'time'=>date('Y/m/d H:i:s'),
        ]);
    }
}