<?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=['a.is_del'=>0,'d.is_del'=>0];
        if($status!==""){
            $where['a.status'] = $status;
        }
        $username =  isset($this->post['username'])&&$this->post['username']!=="" ? trim($this->post['username']) :"";
        if($username!=""){
            $where['a.username'] = ["like","%{$username}%"];
        }
        $nickname =  isset($this->post['nickname'])&&$this->post['nickname']!=="" ? trim($this->post['nickname']) :"";
        if($nickname!=""){
            $where['v.nickname'] = ["like","%{$nickname}%"];
        }
        $mobile =  isset($this->post['mobile'])&&$this->post['mobile']!=="" ? trim($this->post['mobile']) :"";
        if($mobile!=""){
            $where['v.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("account")->alias('a')
            ->join("fc_rela_account b","a.id = b.accountid","left")
            ->join("fc_account_info v","b.account_info = v.id","left")
            ->join("fc_account_stock d","a.id = d.accountid","left")
            ->where($where)->count();
        $total = ceil($count/$size);
        $page = $page>=$total? $total:$page;
        $list = Db::name("account")->alias('a')->where($where)->page($page,$size)
            ->join("fc_rela_account b","a.id = b.accountid","left")
            ->join("fc_account_info v","b.account_info = v.id","left")
            ->join("fc_account_stock d","a.id = d.accountid","left")
            ->field("`a`.`id` AS `id`,
                        `a`.`username` AS `username`,
                        `a`.`status` AS `status`,
                        `a`.`starttime` AS `starttime`,
                        `a`.`expiretime` AS `expiretime`,
                        `a`.`activetime` AS `activetime`,
                        `a`.`addtime` AS `addtime`,
                        `v`.`nickname` AS `nickname`,
                        `v`.`avatar` AS `avatar`,
                        `v`.`mobile` AS `mobile`,
                        `v`.`remark` AS `remark`,
                        ifnull( `d`.`stock_total`, 0 ) AS `stock_total`,
                        ifnull( `d`.`stock_used`, 0 ) AS `stock_used`,
                        ifnull( `d`.`stock_balance`, 0 ) AS `stock_balance`,
                        ifnull( `d`.`stock_delivery`, 0 ) AS `stock_delivery`,
                        ifnull( `d`.`updatetime`, '' ) AS `stock_update` ")
            ->order("d.updatetime 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")->alias('a')->where(["a.is_del"=>0,"a.id"=>$id])
            ->join("fc_rela_account b", "a.id = b.accountid", "left")
            ->join("fc_account_info c", "b.account_info= c.id", "left")
            ->field("`a`.`id` AS `id`,
	                      `a`.`username` AS `username`,
	                      `a`.`password` AS `password`,
	                      `a`.`salt` AS `salt`,
	                      `a`.`status` AS `status`,
                          `a`.`is_del` AS `is_del`,
                          `a`.`starttime` AS `starttime`,
                          `a`.`expiretime` AS `expiretime`,
                          `a`.`activetime` AS `activetime`,
                          `a`.`addtime` AS `addtime`,
                           `c`.`nickname` AS `nickname`,
                           `c`.`avatar` AS `avatar`,
                           `c`.`mobile` AS `mobile`,
                           `c`.`remark` AS `remark`,
                           `c`.`sex` AS `sex`")
            ->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]);
    }

}