<?php
/**
 *  订单管理
 *  @author  system
 *  @version    1.0
 *  @date 2018-07-03 16:51:03
 *
 */
namespace App\Http\Controllers\Admin\Album;
use App\Http\Controllers\Admin\Controller;
use App\Models\AlbumManufacturerModel;
use App\Models\AlbumOrderModel;
use App\Models\AlbumPartsModel;
use App\Models\AlbumProgressModel;
use App\Models\AlbumUserModel;
use App\Models\FurnitureFormidModel;
use App\Services\Base\Attachment;
use EasyWeChat\Factory;
use EasyWeChat\Payment\Order;
use Image;
use Illuminate\Http\Request;
use App\Repositories\Base\Criteria\OrderBy;
use App\Repositories\Album\Criteria\MultiWhere;
use App\Repositories\Album\OrderRepository;
use Illuminate\Support\Facades\DB;

class OrderController extends Controller
{
    private $repository;

    public function __construct(OrderRepository $repository) {
        if(!$this->repository) $this->repository = $repository;
        parent::__construct();
    }

    function index(Request $request) {
        $search['keyword'] = $request->input('keyword');
        $search['status'] = $request->input('status');
        $search['expected'] = $request->input('expected');
        $search['storeid'] = $this->getStoreId();

        $order = array();
        if(isset($request['sort_field']) && $request['sort_field'] && isset($request['sort_field_by'])) {
            $order[$request['sort_field']] = $request['sort_field_by'];
        }else{
            $order['id']='DESC';
        }

        $list = $this->repository->searchOrder($search,$order);

        return view('admin.album.order.index',compact('list'));
    }


    function check(Request $request) {
        $data = $this->repository->find(request('id'));
        $img = explode(',',$data['picture']);
        $parts = AlbumPartsModel::where('store_id', $this->getStoreId())->where('order_id', request('id'))
            ->get(['name', 'count']);

        return view('admin.album.order.check',compact('data','img','parts'));
    }


    /**
     * 添加
     *
     */
    public function create(Request $request)
    {
        if($request->method() == 'POST') {
            return $this->_createSave();
        }
        return view('admin.album.order.edit');
    }

    /**
     * 保存修改
     */
    private function _createSave(){
        $data = (array) request('data');

        $data['store_id'] = $this->getStoreId();

        $array_pic = request('picture');

        if ($array_pic && isset($array_pic['url'])) {
            $data['picture'] = '';
            foreach ($array_pic['url'] as $item) {
                $data['picture'] .= $item . ',';
            }
            if ($data['picture']) $data['picture'] = rtrim($data['picture'], ',');
        } else {
            $data['picture'] = '';
        }
        $data['status'] = 0;
        $data['sno'] = date('YmdHmis');

        $res = $this->repository->create($data);
        if($res) {
            $this->getQrcode($this->getStoreId(),$res->id);
            $url[] = array('url'=>U( 'Album/Order/index'),'title'=>'返回列表');
            $url[] = array('url'=>U( 'Album/Order/create'),'title'=>'继续添加');
            $this->showMessage('添加成功',$url);
        }else{
            $url[] = array('url'=>U( 'Album/Order/index'),'title'=>'返回列表');
            return $this->showWarning('添加失败',$url);
        }
    }

    /**
     *
     * 修改
     *
     *
     */
    public function update(Request $request) {
        if($request->method() == 'POST') {
            return $this->_updateSave();
        }
        $data = $this->repository->find($request->get('id'));
        $data['picture'] = explode(',',$data['picture']);

        return view('admin.album.order.edit',compact('data'));
    }

    /**
     * 保存修改
     */

    private function _updateSave() {
        $data = (array) request('data');
        $array_pic = request('picture');

        if ($array_pic && isset($array_pic['url'])) {
            $data['picture'] = '';
            foreach ($array_pic['url'] as $item) {
                $data['picture'] .= $item . ',';
            }
            if ($data['picture']) $data['picture'] = rtrim($data['picture'], ',');
        } else {
            $data['picture'] = '';
        }
        $old = $this->repository->find(request('id'))->picture;

        $ok = $this->repository->update(request('id'),$data);
        if($ok) {
            //操作成功，删除原来的图片
            if ($old) {
                $pics = explode(',', $old);
                foreach ($pics as $pic) {
                    if (!in_array($pic, $array_pic['url'])) {
                        $md5 = $this->getarea($pic);
                        $attache = new Attachment();
                        $attache->deleteAttachment($md5);
                    }
                }
            }

            return $this->showMessage('操作成功',urldecode(request('_referer')));
        }else{
            $url[] = array('url'=>U( 'Album/Order/index'),'title'=>'返回列表');
            return $this->showWarning('操作失败',$url);
        }
    }

    public function view(Request $request) {
        $data = $this->repository->find(request('id'));
        $img = explode(',',$data['picture']);
        $this->getQrcode($this->getStoreId(),request('id'));
        return view('admin.album.order.view',compact('data','img'));
    }

    public function picture(Request $request) {
        $data = $this->repository->find(request('id'));
        $img = explode(',',$data['picture']);
        return view('admin.album.order.picture',compact('img'));
    }

    public function addecomment(Request $request){
        $data = $this->repository->find(request('id'));
        $data->expected_comment = $request->get('expected_comment');
        $ok = $data->save();
        if($ok) {
            return $this->showMessage('操作成功');
        }else{
            return $this->showWarning('操作失败');
        }
    }


    /**
     *
     * 状态改变
     *
     */
    public function status(Request $request) {
        $data = [
            'status'=>request('status'),
            'price' =>request('price'),
            'verifier_id' =>$this->_user->id,
            'expected_time' =>request('expected_time'),
        ];
        $ok = $this->repository->update(request('id'),$data);
        if($ok) {
            foreach (request('name') as $k =>$v){
                $parts[$k]['name'] = $v;
                $parts[$k]['count'] = request('count')[$k];
                $parts[$k]['order_id'] = request('id');
                $parts[$k]['store_id'] = $this->getStoreId();
                if($parts[$k]['name']){
                    AlbumPartsModel::create($parts[$k]);
                }
            }
            $data = [
                'status' =>request('status'),
                'order_id' =>request('id'),
                'store_id' =>$this->getStoreId(),
                'description' => '订单已审核，修理费为'.request('price').'订单下发到生产部，等待制作'
            ];
            AlbumProgressModel::create($data);
            $storeid =$this->getStoreId();
            $setting = AlbumManufacturerModel::where('store_id', $storeid)->first();
            $config = [
                'app_id' => $setting->service_app_id,
                'secret' => $setting->service_app_secret,
                // 下面为可选项
                // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
                'response_type' => 'array',
            ];
            $app = Factory::miniProgram($config);

            $users = AlbumUserModel::where('store_id',1)->where('role',1)->get();
//            foreach ($users as $user){
//                $formid = FurnitureFormidModel::where('store_id',$storeid)->where(DB::raw("DATEDIFF(NOW(),created_at)"), '<', 7)->where('openid',$user->wechat_open_id)->where('status',0)->orderBy('created_at','asc')->first();
//                $app->template_message->send([
//                    'touser' => $user->wechat_open_id,
//                    'template_id' => '',
//                    'page' => 'index',
//                    'form_id' => $formid->formid,
//                    'data' => [
//                        'keyword1' => 'VALUE',
//                        'keyword2' => 'VALUE2',
//                        // ...
//                    ],
//                ]);
//            }

            return $this->showMessage('操作成功');
        }else{
            return $this->showWarning('操作失败');
        }
    }

    /**
     * 删除
     */
    public function destroy(Request $request) {
        $bool = $this->repository->destroy($request->get('id'));
        if($bool) {
            return  $this->showMessage('操作成功');
        }else{
            return  $this->showWarning("操作失败");
        }
    }

    public function getPic(Request $request){
        $order = AlbumOrderModel::find(request('id'));
        $img = $order->picture;
        $img = explode(',',$img);
        return json_encode($img);
    }

    public function getQrcode($store_id, $id)
    {
        $this->wechat_app = AlbumManufacturerModel::where('store_id', $store_id)->first();
        $config = [
            'app_id' => $this->wechat_app->service_app_id,
            'secret' => $this->wechat_app->service_app_secret,

            // 下面为可选项
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',
        ];
        $app = Factory::miniProgram($config);
        $response = $app->app_code->getQrCode('pages/search/search?order_id=' . $id,300);
        $path = public_path() . '/download';
        $qrcode = $response->save($path, $id);

        if ($qrcode) {
            $qrcode = env('APP_URL') . '/download/' . $id . '.jpg';
            $order = AlbumOrderModel::find($id);
            $order->qrcode = $qrcode;
            $order->save();
            return true;
        } else {
            return false;
        }
    }

    public function getarea($str)
    {
        $start = strripos($str, '/');
        $first = substr($str, $start + 1);
        $end = strripos($first, '.');
        $last = substr($first, 0, $end);
        return $last;
    }
}