<?php
namespace app\common\model;

use app\hander\HelpHander;
use think\Db;
use think\Exception;
use think\Model;

class OfficeItems extends Model
{

    public function add($userId){
        $data = [
            'id' => input('id/d',0),
            'title' => input('title','','trim'),
            'spec' => input('spec','','trim'),
            'price' => input('price/f',0),
            'org_id' => input('orgId/d',0),
            'cate_id' => input('cateId/d',0),
            'unit_id' => input('unitId/d',0),
            'buy_time' => input('buyTime','','trim'),
            'nums' => input('nums/d',0),
            'last_nums' => input('lastNums/d',0),
            'remark' => input('remark','','trim')
        ];
        $logdata = json_encode($data);

        $result = validate('OfficeItems')->check($data,[],'');
        if(true !== $result){
            HelpHander::error(validate('OfficeItems')->getError());
        }

        Db::startTrans();
        try{
            $id = $data['id'];
            unset($data['id']);
            if($id > 0){
                $data['update_time'] = date('Y-m-d H:i:s');
                unset($data['nums']);
                unset($data['last_nums']);
                $ret = $this->allowField(true)->save($data,['id'=>$id]);
            }else{
                $data['create_time'] = date('Y-m-d H:i:s');
                $data['last_nums'] = $data['nums'];
                $ret = $this->allowField(true)->save($data);
            }
            if(!$ret){
                \exception('操作失败');
            }

            if($id <= 0){ // 添加一个初始入库单
                $res = Db::name('office_inreceipt')->insert([
                    'org_id' => $data['org_id'],
                    'user_id' => $userId,
                    'items_id' => $this->id,
                    'nums' => $data['nums'],
                    'remark' => '初始入库',
                    'create_time' => date('Y-m-d H:i:s')
                ]);
                if(!$res){
                    \exception('操作失败');
                }
            }

            if($id > 0){
                $content = '修改办公物品';
            }else{
                $content = '添加办公物品';
            }
            model('ActionLog')->add(13,$content,0,$logdata);

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


        return true;
    }

    public function info($id){
        $info = $this->where('id',$id)->find();
        if(!$info){
            HelpHander::error('数据不存在');
        }
        return $info->toArray();
    }

    public function lists($page,$size,$title,$cateId,$orgId,$type=0){ // type 0=全部 1=有库存
        $map[] = ['org_id','=',$orgId];
        $map[] = ['del','=',0];
        if($cateId > 0){
            $map[] = ['cate_id','=',$cateId];
        }
        if($title){
            $map[] = ['title','like','%'.$title.'%'];
        }
        if($type == 1){
            $map[] = ['last_nums','>',0];
            $map[] = ['enable','=',1];
        }

        $lists = $this
            ->where($map)
            ->page($page,$size)
            ->field('del,update_time',true)
            ->order('id desc')
            ->select();
        $lists = $lists?$lists->toArray():[];
        foreach ($lists as $k=>$v){
            $lists[$k]['cate_name'] = Db::name('office_cate')->where('id',$v['cate_id'])->value('title');
            $lists[$k]['unit_name'] = Db::name('office_unit')->where('id',$v['unit_id'])->value('title');
        }

        $total = $this->where($map)->count();
        $data = [
            'total' => $total,
            'list' => $lists
        ];
        return $data;
    }

    public function export($title,$cateId,$orgId,$type=0){ // type 0=全部 1=有库存
        $map[] = ['org_id','=',$orgId];
        $map[] = ['del','=',0];
        if($cateId > 0){
            $map[] = ['cate_id','=',$cateId];
        }
        if($title){
            $map[] = ['title','like','%'.$title.'%'];
        }
        if($type == 1){
            $map[] = ['last_nums','>',0];
            $map[] = ['enable','=',1];
        }

        $lists = $this
            ->where($map)
            ->field('del,update_time',true)
            ->order('id desc')
            ->select();
        $lists = $lists?$lists->toArray():[];
        foreach ($lists as $k=>$v){
            $lists[$k]['cate_name'] = Db::name('office_cate')->where('id',$v['cate_id'])->value('title');
            $lists[$k]['unit_name'] = Db::name('office_unit')->where('id',$v['unit_id'])->value('title');
            if($v['enable'] == 1){
                $lists[$k]['enable_text'] = '启用';
            }else{
                $lists[$k]['enable_text'] = '禁用';
            }
        }

        $columns = [
            ["title" => "名称","key" => "title"],
            ["title" => "规格","key" => "spec"],
            ["title" => "类型","key" => "cateName"],
            ["title" => "价格","key" => "price"],
            ["title" => "总数","key" => "nums"],
            ["title" => "剩余数量","key" => "lastNums"],
            ["title" => "单位","key" => "unitName"],
            ["title" => "购买日期","key" => "buyTime"],
            ["title" => "备注","key" => "remark"],
            ["title" => "状态","key" => "enableText"],
        ];

        $data = [
            'columns' => $columns,
            'list' => $lists
        ];
        return $data;
    }

    public function del($id){
        // 检查是否已被使用
        $info = Db::name('office_receive_items')
            ->where('items_id',$id)
            ->find();
        if($info){
            HelpHander::error('已被使用,无法删除');
        }

        $ret = $this->where('id',$id)->delete();
        if(!$ret){
            HelpHander::error('删除失败');
        }
        $logdata = json_encode(['id' => $id]);
        model('ActionLog')->add(13,'删除办公物品',0,$logdata);

        return true;
    }

    // 物品数量修改
    public function modifyNums($id,$nums,$reason,$type,$userId,$orgId){
        Db::startTrans();
        try{
            $info = Db::name('office_items')->where('id',$id)->where('del',0)->lock(true)->find();
            if(!$info){
                \exception('物品不存在');
            }

            if($type == 1 && $info['last_nums'] < $nums){ // 减少
                \exception('减少数量不能大于剩余数量');
            }

            if($type == 1){
                $nums = -$nums;
            }

            $before = $info['last_nums'];
            $after = $before + $nums;

            $ret = Db::name('office_items')->where('id',$id)->setField('last_nums',$after);
            if(!$ret){
                \exception('操作失败');
            }

            $res = Db::name('office_items_log')->insert([
                'org_id' => $orgId,
                'user_id' => $userId,
                'items_id' => $id,
                'before' => $before,
                'after' => $after,
                'nums' => $nums,
                'reason' => $reason,
                'create_time' => date('Y-m-d H:i:s')
            ]);
            if(!$res){
                \exception('操作失败');
            }

            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            HelpHander::error($e->getMessage());
        }

        return true;
    }

    // 物品数量修改
    public function modifyNumsReceive($id,$nums,$remark,$userId,$orgId){
        Db::startTrans();
        try{
            $info = Db::name('office_items')->where('id',$id)->where('del',0)->lock(true)->find();
            if(!$info){
                \exception('物品不存在');
            }

            $total = $info['nums'] + $nums;
            $after = $info['last_nums'] + $nums;

            $ret = Db::name('office_items')->where('id',$id)->update(['last_nums'=>$after,'nums'=>$total]);
            if(!$ret){
                \exception('操作失败');
            }

            $res = Db::name('office_inreceipt')->insert([
                'org_id' => $orgId,
                'user_id' => $userId,
                'items_id' => $id,
                'nums' => $nums,
                'remark' => $remark,
                'create_time' => date('Y-m-d H:i:s')
            ]);
            if(!$res){
                \exception('操作失败');
            }

            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            HelpHander::error($e->getMessage());
        }

        return true;
    }

    // 日志修改记录
    public function numsLog($page,$size,$title,$name,$orgId){
        $map[] = ['oil.org_id','=',$orgId];
        if($title){
            $map[] = ['oi.title','like','%'.$title.'%'];
        }
        if($name){
            $map[] = ['ui.name','like','%'.$name.'%'];
        }
        $lists = Db::name('office_items_log')
            ->alias('oil')
            ->join('user_info ui','ui.user_id = oil.user_id')
            ->join('office_items oi','oi.id = oil.items_id')
            ->field('oil.*,oi.title,ui.name')
            ->where($map)
            ->page($page,$size)
            ->order('oil.id desc')
            ->select();

        $total = Db::name('office_items_log')
            ->alias('oil')
            ->join('user_info ui','ui.user_id = oil.user_id')
            ->join('office_items oi','oi.id = oil.items_id')
            ->where($map)->count();
        $data = [
            'total' => $total,
            'list' => $lists?$lists:[]
        ];
        return $data;

    }

    public function inreceipt($page,$size,$id){
        $map[] = ['items_id','=',$id];
        $lists = Db::name('office_inreceipt')
            ->where($map)
            ->page($page,$size)
            ->order('id desc')
            ->select();
        foreach ($lists as $k=>$v){
            $lists[$k]['userName'] = Db::name('user_info')->where('user_id',$v['user_id'])->value('name');
        }

        $total = Db::name('office_inreceipt')
            ->where($map)->count();
        $data = [
            'total' => $total,
            'list' => $lists?$lists:[]
        ];
        return $data;
    }

    // 物品入库月统计
    public function numsTj($page,$size,$title,$month,$orgId){
        $map[] = ['a.org_id','=',$orgId];
        if($title){
            $map[] = ['b.title','like','%'.$title.'%'];
        }
        if($month){
            $map[] = ['a.create_time','like',$month.'%'];
        }else{
            $map[] = ['a.items_id','=',0];
        }
        $lists = Db::name('office_items_tj')
            ->alias('a')
            ->join('office_items b','b.id = a.items_id')
            ->field('sum(a.nums) as nums1,sum(a.nums2) as nums2,b.title')
            ->where($map)
            ->page($page,$size)
            ->order('a.create_time desc')
            ->group('a.items_id')
//            ->fetchSql(true)
            ->select();
//        halt($lists);

        $total = Db::name('office_items_tj')
            ->alias('a')
            ->join('office_items b','b.id = a.items_id')
            ->group('a.items_id')
            ->where($map)->count();
        $data = [
            'total' => $total,
            'list' => $lists?$lists:[]
        ];
        return $data;

    }

    public function tjexport($title,$month,$orgId){
        $map[] = ['a.org_id','=',$orgId];
        if($title){
            $map[] = ['b.title','like','%'.$title.'%'];
        }
        if($month){
            $map[] = ['a.create_time','like',$month.'%'];
        }else{
            $map[] = ['a.items_id','=',0];
        }
        $lists = Db::name('office_items_tj')
            ->alias('a')
            ->join('office_items b','b.id = a.items_id')
            ->field('sum(a.nums) as nums1,sum(a.nums2) as nums2,b.title')
            ->where($map)
            ->order('a.create_time desc')
            ->group('a.items_id')
            ->select();
        $lists = $lists?$lists:[];

        $columns = [
            ["title" => "名称","key" => "title"],
            ["title" => "入库数量","key" => "nums1"],
            ["title" => "修改数量","key" => "nums2"],
        ];

        $data = [
            'columns' => $columns,
            'list' => $lists
        ];
        return $data;

    }
}