<?php


namespace app\Home\controller;
use think\Db;

class Order extends Base
{
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * @param status 0/1/2
     * @param page
     * @param size
     */
    public function list(){
        $page = isset($this->post['page'])&&$this->post['page']!="" ? intval($this->post['page']):1;
        $size = isset($this->post['size'])&&$this->post['size']!="" ? intval($this->post['size']):10;
        $status = isset($this->post['status'])&&$this->post['status']!="" ? intval($this->post['status']):0;
        $where=["a.is_del"=>0,"a.accountid"=>$this->userinfo['id']];
        if($status!=0 && in_array($status,[1,2])){
            $where['a.status']=$status;
        }
        $count =Db::name("order a")->where($where)->count();
        $total = ceil($count/$size);
        $page = $page>$total?$total:$page;
        $list = Db::name("order a")->where($where)->page($page,$size)
            ->join("fc_order_post b","a.`order_sn` = `b`.`order_sn`","left")
            ->join("fc_addr c","`b`.`addrid` = `c`.`id`","left")
            ->join("fc_account e","a.`accountid` = `e`.`id`","left")
            ->join("fc_rela_account f","a.`accountid` = `f`.`accountid`","left")
            ->join("fc_account_info g","`f`.`account_info` = `g`.`id`","left")
            ->join("fc_good gd","a.good_id = gd.id","left")
            ->field("a.id AS id,
	a.`order_sn` AS `order_sn`,
	a.`accountid` AS `accountid`,
	a.`order_num` AS `order_num`,
	a.`status` AS `status`,
	a.`is_del` AS `is_del`,
	a.`delivery_time` AS `delivery_time`,
	a.`order_time` AS `order_time`,
	`b`.`addrid` AS `addrid`,
	`b`.`order_num` AS `border_num`,
	`b`.`post_code` AS `post_code`,
	`b`.`post_name` AS `post_name`,
	`b`.`status` AS `bstatus`,
	`c`.`addr` AS `addr`,
	`c`.`provice` AS `provice`,
	`c`.`city` AS `city`,
	`c`.`provice_name` AS `provice_name`,
	`c`.`city_name` AS `city_name`,
	`c`.`area` AS `area`,
	`c`.`area_name` AS `area_name`,
	`c`.`contector` AS `contector`,
	`c`.`mobile` AS `contector_mobile`,
	`e`.`username` AS `username`,
	`g`.`nickname` AS `nickname`,
	`g`.`mobile` AS `mobile`,
	a.`unit_weight` AS `unit_weight`,
	a.`unit` AS `unit`,
	  gd.good_name as 'good_name',
    gd.good_desc as 'good_desc',
     gd.id as 'good_id',
    gd.good_url as 'good_url'")->select();

        return app_show(0,"获取成功",["list"=>$list,"count"=>$count]);
    }

    /**
     * @param id 订单id
     */

    public function info(){
        $id = isset($this->post['id'])&&$this->post['id']!="" ? intval($this->post['id']):"";
        if($id==""){
            return error_show(1004,"参数id 不能为空");
        }

        $order = Db::name("order")->alias('a')->where(["a.is_del"=>0,"a.accountid"=>$this->userinfo['id'],"a.id"=>$id])

            ->join("fc_order_post b","a.order_sn =b.order_sn","left")
            ->join("fc_addr c","b.addrid= c.id","left")
            ->join("fc_account e","a.accountid= e.id","left")
            ->join("fc_rela_account f","a.accountid = f.accountid","left")
            ->join("fc_account_info g","f.account_info = g.id","left")
            ->join("fc_good gd","a.good_id = gd.id","left")
            ->field("`a`.`id` AS `id`,
                        `a`.`order_sn` AS `order_sn`,
                        `a`.`accountid` AS `accountid`,
                        `a`.`order_num` AS `order_num`,
                        `a`.`status` AS `status`,
                        `a`.`is_del` AS `is_del`,
                        `a`.`delivery_time` AS `delivery_time`,
                        `a`.`order_time` AS `order_time`,
                        `b`.`addrid` AS `addrid`,
                        `b`.`order_num` AS `border_num`,
                        `b`.`post_code` AS `post_code`,
                        `b`.`post_name` AS `post_name`,
                        `b`.`status` AS `bstatus`,
                        `c`.`addr` AS `addr`,
                        `c`.`provice` AS `provice`,
                        `c`.`city` AS `city`,
                        `c`.`provice_name` AS `provice_name`,
                        `c`.`city_name` AS `city_name`,
                        `c`.`area` AS `area`,
                        `c`.`area_name` AS `area_name`,
                        `c`.`contector` AS `contector`,
                        `c`.`mobile` AS `contector_mobile`,
                        `e`.`username` AS `username`,
                        `g`.`nickname` AS `nickname`,
                        `g`.`mobile` AS `mobile`,
                        `a`.`unit_weight` AS `unit_weight`,
                        `a`.`unit` AS `unit`,
                          gd.good_name as 'good_name',
                          gd.id as 'good_id',
                          gd.good_desc as 'good_desc',
                          gd.good_url as 'good_url'
                        ")
            ->find();
        if(empty($order)){
            return error_show(1005,"未找到订单数据");
        }
        return app_show(0,"获取成功",$order);
    }

    /**
     * @param  num
     * @param  addrid
     */
    public function ist(){
      $ist = Db::name('good')->where(["is_del" => 0,"status"=>1,"type"=>$this->userinfo['type']])->field("id,good_name,good_desc,good_url,unit as name, unit_weight as weight,limit_num")->select();
      return app_show(0,"获取成功",["list"=>$ist]);
    }

    public function add(){
        $num = isset($this->post['num'])&&$this->post['num']!="" ? intval($this->post['num']):"";
        if($num==""){
            return error_show(1004,"参数num 不能为空或0");
        }
        $id = isset($this->post['unit_id'])&&$this->post['unit_id']!=""? intval($this->post['unit_id']): "";
        if($id==""){
            return error_show(1004,"unit_id不能为空");
        }
        $kg= Db::name('good')->where(["is_del" => 0,"id"=>$id,"status"=>1,"type"=>$this->userinfo['type']])->field("id,good_name,good_desc,good_url,unit as name, unit_weight as weight,limit_num")->find();
       // var_dump(Db::name('unit')->where(["is_del" => 0,"id"=>$id,"status"=>1])->getLastSql());
        if($kg==false){
            return error_show(1004,"商品未找到");
        }
        $count=$num*$kg['weight'];
        if($count==""){
            return error_show(1004,"购买数量不能为空");
        }
        if($kg['limit_num']>0){
            $zl = Db::name('order_log')->where(["unit_id"=>$id,"accountid"=>$this->userinfo['id']])->sum('num');

            if($zl+$num>$kg['limit_num']){
                $jf = $kg['limit_num']>=$zl ?$kg['limit_num']-$zl :0;
                return error_show(1004,"购买数量超过限额,可购数量{$jf}{$kg['name']}");
            }

        }

        $addrid = isset($this->post['addrid'])&&$this->post['addrid']!="" ? intval($this->post['addrid']):"";
        if($addrid==""){
            return error_show(1004,"参数addrid 不能为空");
        }
        $stock = Db::name("account_stock")->where(['is_del'=>0,"accountid"=>$this->userinfo['id']])->find();
        if(empty($stock) || $stock['stock_balance']<$count){
            return error_show(1004,"库存数量不足");
        }
        $addr =Db::name("rela_addr")->alias('a')->join("addr b","a.addrid=b.id","left")->where(["a.accountid"=>$this->userinfo['id'],
            "b.is_del"=>0,"b.id"=>$addrid])->field("b.id,b.provice,b.provice_name,b.city,b.city_name,b.area,b.area_name,b.addr,b.contector,b.mobile,b.addtime")->find();
        if(empty($addr)){
            return error_show(1004,"地址数据未找到");
        }
        Db::startTrans();
        try{
            $ordersn =makeNo("FC");
            $data=[
                "order_sn"=>$ordersn,
                "accountid"=>$this->userinfo['id'],
                "order_num"=>$num,
                "unit"=>$kg['name'],
                "unit_weight"=>$kg['weight'],
                "good_id"=>$kg['id'],
                "is_del"=>0,
                "status"=>1,
                "addtime"=>date("Y-m-d H:i:s"),
                "updatetime"=>date("Y-m-d H:i:s"),
                "order_time"=>date("Y-m-d H:i:s"),
            ];
            $ordercreate= Db::name("order")->insert($data,false,true);
            if($ordercreate>0){
                $post =[
                    "order_sn"=>$ordersn,
                    "addrid"=>$addrid,
                    "order_num"=>$num,
                    'post_code'=>"",
                    'post_name'=>"",
                    "status"=>1,
                    "is_del"=>0,
                    "addtime"=>date("Y-m-d H:i:s"),
                    "updatetime"=>date("Y-m-d H:i:s")
                ];
                $orderpost=Db::name("order_post")->insert($post);
                if($orderpost){
                   $updatestock= Db::name("account_stock")->where($stock)->update
                    (['stock_balance'=>$stock['stock_balance']-$count,
                        "stock_delivery"=>$stock['stock_delivery']+$count,"updatetime"=>date("Y-m-d H:i:s")]);
                   if($updatestock){
                       $log=[
                           "accountid"=>$this->userinfo['id'],
                           "run_stock"=>$count,
                           "type"=>3,
                           "after_stock"=>$stock['stock_balance']-$count,
                           "before_stock"=>$stock['stock_balance'],
                           "action_uid"=>$this->userinfo['id'],
                           "action_name"=>$this->userinfo['nickname'],
                           "addtime"=>date("Y-m-d H:i:s"),

                       ];
                       $stocklog =Db::name("stock_log")->insert($log);
                       $log=[
                           "accountid"=>$this->userinfo['id'],
                           "addtime"=>date("Y-m-d H:i:s"),
                            "unit"=>$kg['name'],
                           "unit_weight"=>$kg['weight'],
                           "num"=>$num,
                           "total_weight"=>$num*$kg['weight'],
                           "unit_id"=>$kg['id']
                       ];
                       $st =Db::name("order_log")->insert($log);
                       if($stocklog && $st){
                           Db::commit();
                           return app_show(0,"下单成功",['orderid'=>$ordercreate]);
                       }
                   }
                }
            }
            Db::rollback();
            return error_show(1006,"下单失败");
        }catch (\Exception $e){
            Db::rollback();
            return error_show(1005,$e->getMessage());
        }
    }

    public function Stock(){
        $stock = Db::name("account_stock")->where(["accountid"=>$this->userinfo['id'],'is_del'=>0])->find();
        $data=[];
        $data['stock'] = isset($stock['stock_balance']) ? $stock['stock_balance']:0;
        $unit = Db::name('good')->where(['is_del'=>0,'status'=>1,"type"=>$this->userinfo['type']])->field("id,good_name,unit as name,unit_weight as weight,limit_num")
            ->select();
        $limit=[];
        foreach ($unit as $value){
            $zl =0;
            $num = intval($data['stock']/$value['weight']);
            if($value['limit_num']>0){
                $zl = Db::name('order_log')->where(["unit_id"=>$value['id'],"accountid"=>$this->userinfo['id']])->sum('num');
                $value['limit_num']>$zl?$value['limit_num'] -= $zl:$value['limit_num']=0;
                $value['limit_num'] = $value['limit_num']>$num  ? $num : $value['limit_num'];
            }else{
                $value['limit_num'] = $num ;
            }
            $limit[]=$value;
        }
        $data['limit']=$limit;
        return app_show(0,"获取成功",$data);
    }
}