<?php
namespace app\mainapp\controller;

use think\facade\Session;
use app\mainapp\BaseController;
use app\common\model\MallCate as MallCateModel;
use app\common\model\MallGoods as MallGoodsModel;
use app\common\model\MallOrder as MallOrderModel;

use app\common\model\User as UserModel;
use app\common\model\UserAuths as UserAuthsModel;
use app\common\model\UserIntegral as UserIntegralModel;

use echowx\WxPay;

class Mall extends BaseController
{
	
	// 取消订单
	public function closeOrder()
	{
		$userid = input('userid/d', 0);
		$user = UserModel::findOrEmpty($userid);
		if ($user->isEmpty()) {
		    page_result(1, "用户信息不存在。");
		}
		$orderid = input('orderid/d', 0);
		$order = MallOrderModel::where(['userid'=>$userid])->findOrEmpty($orderid);
		if ($order->isEmpty()){
			page_result(1, "订单信息不存在");
		}
		if ($order->status==1){
			page_result(1, "订单信息已取消，请不要重复操作。");
		}elseif ($order->status!=2){
			page_result(1, "订单信息已支付，不能再做取消操作。");
		}
		$goods = MallGoodsModel::findOrEmpty($order->goodsid);
		if ($order->integral > 0){
			$uintegral = new UserIntegralModel; 
			$uintegral->save([
				'userid'		=> $userid,
				'title'			=> "订单取消返积分<".$order->title.">",
				'intvalue'		=> $order->integral,
				'intmoney'		=> 0.00,
				'onlycontent'	=> "",
				'remark'		=> "订单编号".$order->ordersn,
				'itype'			=> 7,
				'status'		=> 2,
				'createtime'	=> time(),
				'yeartime'		=> date("Y"),
				'monthtime'		=> date("Ym")
			]);
			$user->save(['integral' => $user->integral + $order->integral]);
		}
		$goods->dec('sales', $order->buynumber)->inc('stock', $order->buynumber)->update();
		$order->save(['status' => 1]);
		page_result(0, "", array());
	}
	
	// 删除订单
	public function deleteOrder()
	{
		$userid = input('userid/d', 0);
		$user = UserModel::findOrEmpty($userid);
		if ($user->isEmpty()) {
		    page_result(1, "用户信息不存在。");
		}
		$orderid = input('orderid/d', 0);
		$order = MallOrderModel::where(['userid'=>$userid])->findOrEmpty($orderid);
		if ($order->isEmpty()){
			page_result(1, "订单信息不存在");
		}
		if ($order->status!=1){
			page_result(1, "订单信息不在已取消状态，不能做删除操作。");
		}
		$order->delete();
		page_result(0, "", array());
	}
	
	// 修改订单地址
	public function setOrderAddress()
	{
		$userid = input('userid/d', 0);
		$user = UserModel::findOrEmpty($userid);
		if ($user->isEmpty()) {
		    page_result(1, "用户信息不存在。");
		}
		$orderid = input('orderid/d', 0);
		$order = MallOrderModel::with('mallGoods')->where(['userid'=>$userid])->findOrEmpty($orderid);
		if ($order->isEmpty()){
			page_result(1, "订单信息不存在"); 
		}
		if ($order->status!=2){
			page_result(1, "订单已取消或已支付，不能再修改收件信息。");
		}
		$order->save([
			'username'		=> input('username/s', ""),
			'usermobile'	=> input('usermobile/s', ""),
			'province'		=> input('province/s', ""),
			'city'			=> input('city/s', ""),
			'county'		=> input('county/s', ""),
			'detailinfo'	=> input('detailinfo/s', "")
		]);
		page_result(0, "", array(
			'order' => $order
		));
	}
	
	
	// 订单详情
	public function listOrder()
	{
		$ppage = input('ppage/d', 1);
		$psize = input('psize/d', 20);
		$map = array();
		$userid = input('userid/d', 0);
		$map[] = ['userid','=',$userid];
		$status = input('status/d', 0);
		if ($status!=0){
			$map[] = ['status', '=', $status];
		}
		$plist = MallOrderModel::with(['mallGoods'])->where($map)->order(['id'=>'desc'])->page($ppage)->limit($psize)->select();
		page_result(0, "", array(
			'plist' => $plist,
			'pstatus' => $psize > count($plist) ? 'noMore' : 'more'
			));
	}
	 
    
	
	// 订单支付
	public function payOrder()
	{
		$userid = input('userid/d', 0);
		$user = UserModel::findOrEmpty($userid);
		if ($user->isEmpty()) {
		    page_result(1, "用户信息不存在。");
		}
		$userauths = UserAuthsModel::where(['userid'=>$user->id,'identitytype'=>"weixin"])->findOrEmpty();
		if ($userauths->isEmpty()){
			page_result(1, "请先授权微信号登录。");
		}
		$orderid = input('orderid/d', 0);
		$order = MallOrderModel::with('mallGoods')->where(['userid'=>$userid])->findOrEmpty($orderid);
		if ($order->isEmpty()){
			page_result(1, "订单信息不存在。");
		}
		if ($order->username==""){
			page_result(1, "请选择收件信息。");
		}
		$remark = input('remark/s', "");
		if ($order->paymoney <= 0.00){  
			$order->save([
				'status'	=> 3,
				'remark'	=> $remark
			]);
			page_result(0, "", array('ostatus'=>3));
		}else{
			$order->save([
				'remark'	=> $remark
			]);
			$payData = [
			    'body'			=> $order->title,
			    'out_trade_no'	=> $order->ordersn,
			    'total_fee'		=> intval($order->paymoney * 100),
				'openid'		=> $userauths->identifier
			];
			$wxpay = new WxPay();
			$info = $wxpay->wxpay_unified_order($payData); 
			if ($info['status']==1){
				$payinfo = $wxpay->get_jsapi_param($info['data']['prepay_id']);
				page_result(0, "", array('ostatus'=>2, 'payinfo'=>$payinfo));
			}else{
				page_result(1, $info['data']);
			}
		}
	}
	
	
	// 订单详情
	public function getOrder()
	{
		$orderid = input('orderid/d', 0);
		$userid = input('userid/d', 0);
		$order = MallOrderModel::with('mallGoods')->where(['userid'=>$userid])->findOrEmpty($orderid);
		if ($order->isEmpty()){
			page_result(1, "订单信息不存在");
		}
		page_result(0, "", array(
			'order' => $order
			));
	}
	
	
	
	// 提交订单
	public function setOrder()
	{
		$goodsid = input('goodsid/d', 0);
		$userid = input('userid/d', 0);
		$buynumber = input('buynumber/d', 0);
		$goods = MallGoodsModel::findOrEmpty($goodsid);
		if ($goods->isEmpty()){
			page_result(1, "商品信息不存在。");
		}
		if ($buynumber<=0){
			page_result(1, "兑购数量不能小于1。");
		}
		$user = UserModel::findOrEmpty($userid);
		$payintegral = $buynumber * $goods->integral;
		if ($user->integral < $payintegral){
			page_result(1, "积分不足，不能兑购该商品。");
		}
		if ($payintegral>0){
			$uintegral = new UserIntegralModel;
			$uintegral->save([
				'userid'		=> $userid,
				'title'			=> "兑购<".$goods->title.">商品",
				'intvalue'		=> 0 - $payintegral,
				'intmoney'		=> 0.00,
				'onlycontent'	=> "",
				'remark'		=> "兑购".$buynumber."件，单件需".$goods->integral."积分",
				'itype'			=> 7,
				'status'		=> 2,
				'createtime'	=> time(),
				'yeartime'		=> date("Y"),
				'monthtime'		=> date("Ym")
			]);
			$user->save(['integral' => $user->integral - $payintegral]);
		}
		$order = new MallOrderModel;
		$order->save([
			'userid'		=> $userid,
			'ordersn'		=> "M".date("YmdHis").mt_rand(100000, 999999),
			'goodsid'		=> $goodsid,
			'title'			=> $goods->title,
			'tilpic'		=> $goods->tilpic,
			'gintegral'		=> $goods->integral,
			'gpaymoney'		=> $goods->paymoney,
			'buynumber'		=> $buynumber,
			'integral'		=> $payintegral,
			'paymoney'		=> $buynumber * $goods->paymoney,
			'payinfo'		=> array(),
			'status'		=> 2,
			'username'		=> "",
			'usermobile'	=> "",
			'province'		=> "",
			'city'			=> "",
			'county'		=> "",
			'detailinfo'	=> "",
			'remark'		=> "",
			'createtime'	=> time()
		]);
		$goods->inc('sales', $buynumber)->dec('stock', $buynumber)->update();
		page_result(0, "", array(
			'orderid' => $order->id
			));
	}
	
	
	// 详情
	public function getGoods()
	{
		$goodsid = input('goodsid/d', 0);
		$goods = MallGoodsModel::with('mallCate')->findOrEmpty($goodsid);
		if ($goods->isEmpty()){
			page_result(1, "商品信息不存在");
		}
		page_result(0, "", array(
			'goods' => $goods
			));
	}
	
    
    // 列表
    public function listGoods()
    {
        $ppage = input('ppage/d', 1);
        $psize = input('psize/d', 20);
        $map[] = ['status','=',2];
        $map[] = ['createtime','<=',time()];
        $cateid = input('cateid/d', 0);
        if ($cateid!=0) {
            $map[] = ['cateid', '=', $cateid];
        }
        $userid = input('userid/d', 0);
		$user = UserModel::findOrEmpty($userid);
        if (!$user->isEmpty()) {
            $map[] = ['integral', '<=', $user->integral];
        }
        $plist = MallGoodsModel::with('mallCate')->where($map)->order(['priority'=>'desc','id'=>'desc'])->page($ppage)->limit($psize)->select();
        page_result(0, "", array(
            'plist' => $plist,
            'pstatus' => $psize > count($plist) ? 'noMore' : 'more'
            ));
    }
    
    // 全部分类
    public function allCate()
    {
        $allcate = MallCateModel::where('status', 1)->order(['priority'=>'desc','id'=>'desc'])->select()->toArray();
        page_result(0, "", array(
			'allcate' => $allcate
			));
    }
}
