<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\admin\model\SaleOriginChange;use think\App;use think\facade\Cache;use think\facade\Validate;use think\Request;

class Origin extends Base
{
	protected $model=null;
	public $white=["*"];
    public function __construct(App $app) {
    	parent::__construct($app);
    	$this->model=new SaleOriginChange();
    }
    /** 成本修改列表
	* @return \think\response\Json|void
	* @throws \think\db\exception\DbException
	 */
    public function list(){
       $param =$this->request->only(['orderCode'=>'','companyNo'=>'',"size"=>15,"page"=>1],'post','trim');
       $where=[];
       $param["orderCode"]==""?: $where[]=["sale_origin_change.orderCode","like","%{$param["orderCode"]}%"];
       $param["companyNo"]==""?: $where[]=["orderInfo.supplierNo","=",$param["companyNo"]];
       $list = $this->model
       ->withJoin(["orderInfo"],"left")
       ->order("id","desc")
       ->where($where)
       ->paginate(["list_rows"=>$param["size"],"page"=>$param["page"]]);
       return app_show(0,"获取成功",["list"=>$list->items(),"count"=>$list->total()]);
    }
    /** 新建
	* @return \think\response\Json|void
	 */
    public function create(){
        $param =$this->request->only(["orderCode"=>"","change_fee"=>"","remark"=>""],"post","trim");
        $valid =Validate::rule(["orderCode|订单编号"=>"require|max:255","change_fee|成本修改金额"=>"require"]);
        if($valid->check($param)==false)return error_show(1004,$valid->getError());
        $orderInfo = \app\admin\model\Sale::where("orderCode",$param['orderCode'])->findOrEmpty();
        if($orderInfo->isEmpty())return error_show(1004,"订单数据未找到");
        $data=[
        	"orderCode"=>$orderInfo->orderCode,
        	"origin_price"=>bcadd(bcmul($orderInfo->origin_price,bcsub($orderInfo->good_num,$orderInfo->th_num),6),$orderInfo->post_fee,6),
        	"change_price"=>bcadd(bcmul($orderInfo->origin_price,bcsub($orderInfo->good_num,$orderInfo->th_num),6),bcadd($orderInfo->post_fee,$param['change_fee'],6),6),
        	"change_fee"=>$param['change_fee'],
        	"apply_id"=>$this->uid,
        	"apply_name"=>$this->uname,
        	"remark"=>$param["remark"]
        	];
        $orderInfo->post_fee = bcadd($orderInfo->post_fee,$param['change_fee'],6);
        $up = $orderInfo->save();
        if($up==false)return error_show(1004,'订单数据更新失败');
       
        $create =SaleOriginChange::create($data);
        return app_show(0,"成本修改成功");
    }
    /** 详情
	* @return \think\response\Json|void
	 */
    public function info(){
        $id =$this->request->post("id");
        $info =$this->model->with(["order_info"])->findOrEmpty($id);
        if($info->isEmpty())return error_show(1004,'数据未找到');
         return app_show(0,'数据查询成功',$info);
    }
}