<?php


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

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

    /**
    * @param status
    * @param username
    * @param nickname
    * @param mobile
    * @param stock_low
    * @param stock_up
     */
    public  function StockList(){
        $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']) :"";
        $where=[];
        if($status!==""){
            $where['status'] = $status;
        }
        $username =  isset($this->post['username'])&&$this->post['username']!=="" ? trim($this->post['username']) :"";
        if($username!=""){
            $where['username'] = ["like","%{$username}%"];
        }
        $nickname =  isset($this->post['nickname'])&&$this->post['nickname']!=="" ? trim($this->post['nickname']) :"";
        if($nickname!=""){
            $where['nickname'] = ["like","%{$nickname}%"];
        }
        $mobile =  isset($this->post['mobile'])&&$this->post['mobile']!=="" ? trim($this->post['mobile']) :"";
        if($mobile!=""){
            $where['mobile'] = ["like","%{$mobile}%"];
        }
        $stock_low =  isset($this->post['stock_low'])&&$this->post['stock_low']!=="" ? intval($this->post['stock_low'])
            :"";
        $wherestock="1=1";
        if($stock_low!=""){
           // $where['stock_balance'] = [">=",$stock_low];
            $wherestock .=" and stock_balance>={$stock_low}";
        }
        $stock_up =  isset($this->post['stock_up'])&&$this->post['stock_up']!=="" ? intval($this->post['stock_up']) :"";
        if($stock_up!=""){
           // $where['stock_balance'] = ["<=",$stock_up];
            $wherestock .=" and stock_balance<={$stock_up}";
        }
        $count= Db::name("stock_list")->where($where)->where($wherestock)->count();
        $total = ceil($count/$size);
        $page = $page>=$total? $total:$page;
        $list = Db::name("stock_list")->where($where)->where($wherestock)->page($page,$size)->field("id,username,status,nickname,mobile,stock_balance,stock_update")->order("stock_update desc")->select();
        return app_show(0,"获取成功",["list"=>$list,"count"=>$count]);
    }

    /**
     * @param id
     * @param stock
     * @param type
     */
    public function Save(){
        $id = isset($this->post['id'])&&$this->post['id']!=""? intval($this->post["id"]) :"";
        if($id==""){
            return error_show(1004,"参数id 不能为空");
        }
        $account = Db::name("account")->where(["is_del"=>0,"id"=>$id])->find();
        if(empty($account)){
            return error_show(1005,"账户信息不存在");
        }
        $stock = isset($this->post['stock'])&&$this->post['stock']!==""? $this->post["stock"] :"";
        if($stock==""){
            return error_show(1005,"参数stock 不能为空或0");
        }
        $type = isset($this->post['type'])&&$this->post['type']!=""?intval($this->post['type']) :"";
        if($type===""){
            return error_show(1005,"参数type 不能为空");
        }
        if(!in_array($type,[1,2])){
            return error_show(1005,"参数type 值无效");
        }
        $stockinfo = Db::name("account_stock")->where(["accountid"=>$id,"is_del"=>0])->find();
        Db::startTrans();
        try {
            $msg = $type==1?"增加库存":"减少库存";
            $log=[
                "accountid"=>$id,
                "run_stock"=>$stock,
                "type"=>$type,
                "after_stock"=>isset($stockinfo['stock_balance']) ? $stockinfo['stock_balance']+$stock:$stock,
                "before_stock"=>isset($stockinfo['stock_balance']) ? $stockinfo['stock_balance']:0,
                "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);
            if($stocklog){
             if($stockinfo){
                if($type==1){
                    $stockinfo['stock_total']+=$stock;
                    $stockinfo['stock_balance']+=$stock;
                }else{
                    if($stockinfo['stock_balance']<$stock){
                        Db::rollback();
                        return error_show(1005,"剩余库存不足");
                    }
                    $stockinfo['stock_total']-=$stock;
                    $stockinfo['stock_balance']-=$stock;
                }
                $stockinfo['updatetime']=date("Y-m-d H:i:s");
                $accstock = Db::name("account_stock")->update($stockinfo);
             }else{
                 if($type==1){
                   $data = [
                       "accountid"=>$id,
                       "stock_total"=>$stock,
                       "stock_balance"=>$stock,
                       "stock_used"=>0,
                       "stock_delivery"=>0,
                       "status"=>1,
                       "is_del"=>0,
                       "updatetime"=>date("Y-m-d H:i:s"),
                       "addtime"=>date("Y-m-d H:i:s")
                   ];
                     $accstock = Db::name("account_stock")->insert($data);
                 }else{
                     Db::rollback();
                     return error_show(1005,"账户剩余库存不足");
                 }
             }
             if($accstock){
                 write_log("账户{$account['username']}{$msg}:{$stock}",$this->userinfo,"stock","edit","0");
                 Db::commit();
                 return app_show(0,"{$msg}成功");
             }
            }
            Db::rollback();
            return error_show(1005,"{$msg}失败");
        }catch (\Exception $e){
            Db::rollback();
            return error_show(1004,$e->getMessage());
        }
    }

    /**
    * @param id
    * @param page
    * @param size
     */

    public function StockLog(){
        $id = isset($this->post['id'])&&$this->post['id']!=""? intval($this->post["id"]) :"";
        if($id==""){
            return error_show(1004,"参数id 不能为空");
        }
        $account = Db::name("account_list")->where(["is_del"=>0,"id"=>$id])->find();
        if(empty($account)){
            return error_show(1005,"账户信息不存在");
        }
        $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;
        $count = Db::name("stock_log")->where(["accountid"=>$id])->count();
        $total = ceil($count/$size);
        $page = $page>=$total? $total:$page;
        $list = Db::name("stock_log")->where(["accountid"=>$id])->page($page,$size)->order("addtime desc")->select();
        foreach ($list as $key=>$value){
            $list[$key]['username']=$account['username'];
            $list[$key]['nickname']=$account['nickname'];
        }
        return app_show(0,"获取成功",['list'=>$list,"count"=>$count]);
    }

}