<?php
namespace app\command;
// +----------------------------------------------------------------------
// | [ WE CAN DO IT MORE SIMPLE  ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018-2020 rights reserved.
// +----------------------------------------------------------------------
// | Author: TABLE ME
// +----------------------------------------------------------------------
// | Date: 2020-09-08 16:19
// +----------------------------------------------------------------------
use app\model\api\SiteProduct;
use app\model\system\Product;
use library\lib\hupun;
use library\utils\Qiniu;
use library\utils\Region;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Db;

class OrderPush extends Command
{

    protected function configure()
    {
        // 指令配置
        $this->setName('Task')
            ->setDescription('推送定到ERP系统');
    }

    protected function execute(Input $input, Output $output)
    {

        $this->pushOrder();
        //$this->bindPro();
        $this->pushFind();
    }



    public function pushOrder(){
        $hupin = new hupun();
        $order = Db::name("order")->where(array('is_pay'=>1,'is_push'=>0))->select();
        foreach ($order as $v) {
            $orderInfo = Db::name("orderInfo")
                ->where('o_id',$v['id'])
                ->where('is_push',0)
                ->select();
            $sitePro = new SiteProduct();
            $region = new Region;
            $sitePro->setSass($v['sassid']);
            foreach ($orderInfo as $v2) {
                //获取产品信息
                $proData = $sitePro->getProItem($v['pro_id']);
                //获取地址
                $memberData = Db::name('member')->where('uid',$v2['uid'])->find();
                //获取仓库信息
                $warehouse = Db::name("warehouse")->where('id',$v2['warehouse_id'])->find();
                //推送数据
                $iisave['order_id'] = $v2['in_order_id'];
                $iisave['time'] = $v['time'];
                $iisave['payTime'] = $v['pay_time'];
                $iisave['storeID'] = $warehouse['code'];
                $iisave['pro_price'] =$v2['pro_price'];
                $iisave['exp_price'] = $v2['exp_price'];
                $iisave['ts_name'] = empty($memberData) ? '' : $memberData['mobile'];
                $iisave['name'] = $v2['name'];

                $rData = $region->getRegion($v2['address']);
                $iisave['province'] = $rData['province'];
                $iisave['city'] = $rData['city'];
                $iisave['area'] = $rData['area'];
                $iisave['address'] = $v2['address'];
                $iisave['mobile'] = $v2['mobile'];
                $iisave['in_order_id'] = $v2['in_order_id'];
                $iisave['mono'] = $v['mono'];
                //产品信息
                //$iisave['csno'] = $proData['csno'];
                $code = $this->getWlnCode($v2['pro_id'],$v2['warehouse_id'],$v2['exp_id'],$v2['platform_id']);
                $iisave['csno'] =$code;

                $iisave['pro_title'] = $proData['title'];
                $iisave['pro_price'] = $proData['price'];
                $iisave['pro_img'] = empty($proData['img']) ? '' : $proData['img'][0];
                $pusData = $hupin->tradesErp($iisave);
                //推送数据
                $pushSave = [];
                $pushSave['o_id'] = $v['id'];
                $pushSave['oi_id'] = $v2['id'];
                $pushSave['time'] = time();
                $pushSave['code'] = 'trades';//推送
                if($pusData['success']) {
                    $pushSave['status'] = 1;
                    $pushSave['text'] = $v2['in_order_id']."，联系人:".$v2['name']."，手机号码:".$v2['mobile']."，地址:"
                        .$v2['address'].'推送成功';
                    Db::name("orderInfo")->where('id',$v2['id'])->update(['is_push'=>1]);
                } else {
                    $pushSave['status'] = 0;
                    $pushSave['text'] = $v2['in_order_id']."，联系人:".$v2['name']."，手机号码:".$v2['mobile']."，地址:"
                        .$v2['address'].'推送失败:'
                        .$pusData['error_msg'];
                    var_dump($pushSave);
                    Db::name("orderInfo")->where('id',$v2['id'])->update(['is_push'=>-1]);
                }
                Db::name("orderPush")->insert($pushSave);
                echo "订单号:". $v2['in_order_id']."，联系人:".$v2['name']."，手机号码:".$v2['mobile']."，地址:".$v2['address'].PHP_EOL;
            }
            Db::name("order")->where('id',$v['id'])->update(['is_push'=>1]);
        }
    }


    /**
     * 获取订单信息
     */
    public function pushFind(){
        $true = true;
        $p = 1;
        while ($true) {
            $orderIds = Db::name("orderInfo")
                ->where('status', '>', 0)
                ->where('send_time', 0)
                ->page($p, 100)
                ->column('in_order_id');
            if(empty($orderIds)) {
                $true = false;
                continue;
            }
            if (count($orderIds) > 0) {
                $ids = join(',', $orderIds);
                $hupin = new hupun();
                $data  = $hupin->orderFind($ids);
                if (!empty($data['response'])) {
                    $response = json_decode($data['response'], true);
                    $statuses = $response['statuses'];
                    foreach ($statuses as $v) {

                        if (!empty($v['waybill'])) {
                            $oData = Db::name("orderInfo")->where('in_order_id', $v['tid'])->find();
                            echo $v['tid']. PHP_EOL;

                            if (!empty($oData)) {
                                Db::name("orderInfo")->where('in_order_id', $v['tid'])->update([
                                    'exp_number' => $v['waybill'],
                                    'send_time'  => time(),
                                    'status'     => 2
                                ]);
                                Db::name("order")->where('id', $oData['o_id'])->update(['status' => 2]);

                                $this->setPush($oData);
                            }
                        }
                    }
                }
            }
            $p++;
        }
    }


    /**
     * push 数据
     * @param $data
     */
    private function setPush($data) {
        $count = Db::name("weixin_push_user")->where('uid',$data['uid'])->count();
        if($count > 0) {
            $weixinPush = Db::name("weixin_order_push")
                ->where('uid', $data['uid'])
                ->where('status', 0)
                ->find();
            $post = [];
            if(!empty($weixinPush)) {
                $post = unserialize($weixinPush['data']);
            }
            $o_id = $data['o_id'];
            if(!empty($post[$o_id])) {
                $post[$o_id]['count'] += 1;
            } else {
                $post[$o_id] = ['count'=>1,'o_id'=>$o_id];
            }
            $save['uid'] = $data['uid'];
            $save['status'] = 0;
            $save['data'] = serialize($post);
            if(empty($weixinPush)) {
                $save['push_time'] = time();
                Db::name("weixin_order_push")->insert($save);
            } else {
                Db::name("weixin_order_push")->where('id',$weixinPush['id'])->update($save);
            }
        }
    }


    public function bindPro(){
        $data = Db::name("product")->where('csno','fslp00001')->select();
        foreach ($data as $v) {
            $hupin = new hupun();
            $hupin->addProduct([
                'code' => $v['csno'],
                'title' => $v['title'],
                'price' => $v['price'],
                'quantity' => $v['count'],
                'csno'      => $v['csno'],
                'url' => 'http://www.lipinwawa.com/goods/detail/'.$v['id'].'.html',
                'img' => $v['img'],
                'status' =>1,
                'time' => $v['add_time']
            ]);
        }

    }


    /**
     * 其他信息
     * @param $proId
     * @param $warehouseId
     * @param $expId
     * @param $platformId
     */
    private function getWlnCode($proId,$warehouseId,$expId,$platformId){
        $code = Db::name("wln_pro")
            ->where('pro_id',$proId)
            ->where('warehouse_id',$warehouseId)
            ->where('express_id',$expId)
            ->where('platform_id',$platformId)
            ->value('code');
        if(!empty($code)) return $code;

        $code = Db::name("wln_pro")
            ->where('pro_id',$proId)
            ->where('warehouse_id',$warehouseId)
            ->where('express_id',$expId)
            ->where('is_defulat',1)
            ->value('code');
        return $code;
    }



}
