<?php
namespace app\common\model;

use think\Db;
use think\Exception;

class MateApplyUse extends Base
{
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    public $table = 'mate_apply_use';
    protected $validateName = 'MateApplyUse';

    public function updates($userId){
        $data = request()->post();
        $data['org_id'] = cur_org_id();
        $result = validate($this->validateName)->check($data,[],'');
        if(true !== $result){
            $this->error = validate($this->validateName)->getError();
            return false;
        }
        $curTime = date('Y-m-d H:i:s');
        Db::startTrans();
        try{
            $applyId = Db::name('mate_apply')->insertGetId([
                'org_id' => $data['org_id'],
                'create_time' => $curTime,
                'user_id' => $userId,
                'sn' => get_unique_id(),
                'remark' => $data['remark'],
                'name' => $data['name'],
                'phone' => $data['phone'],
                'type' => $data['type']
            ]);
            if(!$applyId){
                \exception('操作失败');
            }
            $arr = [];
            foreach ($data['goods'] as $k=>$v){
                // 重新计算平均价
                $info = Db::name('mate_goods')->where('id',$k)->find();
                if($data['type'] == 1){
                    $price =  ($info['price'] *$info['nums'] + $v['price']*$v['nums']) / ($info['nums']+$v['nums']);
                    $ret = Db::name('mate_goods')->where('id',$k)->update([
                        'price' => round($price,2),
                        'nums' => $info['nums']+$v['nums'],
                        'update_time' => $curTime
                    ]);
                    if(!$ret){
                        \exception('操作失败');
                    }
                }else{
                    $ret = Db::name('mate_goods')->where('id',$k)->update([
                        'nums' => $info['nums'] - $v['nums'],
                        'update_time' => $curTime
                    ]);
                    if(!$ret){
                        \exception('操作失败');
                    }
                }
                $arr[] = [
                    'apply_id' => $applyId,
                    'goods_id' => $k,
                    'nums' => $v['nums'],
                    'price' => $data['type'] == 1?$v['price']:$info['price']
                ];
            }

            $ret = Db::name('mate_apply_goods')->insertAll($arr);
            if($ret != count($arr)){
                \exception('操作失败');
            }

            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            $this->error = $e->getMessage();
            return false;
        }

        return true;
    }

    public function saveData($data){
        $data['create_time'] = date('Y-m-d H:i:s');
        $data['user_id'] = is_login();
        $data['sn'] = get_unique_id();

        $ret = $this->allowField(true)->save($data);
        if(!$ret){
            $this->error = '操作失败';
            return false;
        }
        return $this->getLastInsID();
    }


    public function info($id){
        $info = $this
            ->where('id',$id)
            ->find()
            ->toArray();
        if(!$info){
            return false;
        }
        $info['userName'] = Db::name('user')
            ->where('id',$info['user_id'])
            ->value('real_name');
        $info['goods'] = Db::name('mate_apply_use_goods')
            ->alias('a')
            ->join('mate_goods c','c.id=a.goods_id')
            ->where('a.apply_id',$info['id'])
            ->field('a.*,c.title,c.unit,c.brand,c.spec')
            ->select();
        return $info;
    }



}