<?php

namespace app\common\model;
use app\hander\HelpHander;
use think\Db;
use think\Exception;

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

    public function updates() {
        $data = request()->post();
        if (!isset($data['type']) || empty($data['type'])) {
            $this->error = '请选择任务项';
            return false;
        }
        if (!isset($data['user']) || empty($data['user'])) {
            $this->error = '请选择人员';
            return false;
        }
        $data['type_id'] = (new CleanForm())->check_form_type(explode(',', $data['type']));
        if ($data['type_id'] <= 0) {
            $this->error = '请选择请选择同一分类下的任务项';
            return false;
        }
        if ($data['start_time'] >= $data['end_time']) {
            $this->error = '开始时间要小于结束时间';
            return false;
        }
        $data['org_id'] = cur_org_id();
        $result = validate($this->validateName)->check($data, [], '');
        if (true !== $result) {
            $this->error = validate($this->validateName)->getError();
            return false;
        }
        $id = $data['id'];
        unset($data['id']);
        $clean_task_form = $data['type'];
        $user = $data['user'];
        unset($data['type'], $data['user']);
        $this->startTrans();
        try {
            if ($id > 0) {
                $data['update_time'] = date('Y-m-d H:i:s');
                $ret = $this->allowField(true)->save($data, ['id' => $id]);
                $res = Db::name('clean_task_form')
                    ->where('task_id', $id)->delete();
                if (!$res) {
                    throw new Exception('重置任务内容失败');
                }
                $res = Db::name('clean_task_user')
                    ->where('task_id', $id)->delete();
                if (!$res) {
                    throw new Exception('重置任务人员失败');
                }
            }
            else {
                $data['create_time'] = date('Y-m-d H:i:s');
                $ret = $this->allowField(true)->save($data);
                $id = $this->getLastInsID();
            }
            if (!$ret) {
                throw new Exception('任务保存失败');
            }
            //添加任务内容
            $clean_task_form = explode(',', $clean_task_form);
            $nArr = [];
            foreach ($clean_task_form as $v) {
                $nArr[] = [
                    'task_id' => $id,
                    'form_id' => $v
                ];
            }
            $res = Db::name('clean_task_form')
                ->insertAll($nArr);
            if (!$res) {
                throw new Exception('保存任务内容失败');
            }
            //添加任务人员
            $user = explode(',', $user);
            $nArr = [];
            foreach ($user as $v) {
                $nArr[] = [
                    'task_id' => $id,
                    'user_id' => $v
                ];
            }
            $res = Db::name('clean_task_user')
                ->insertAll($nArr);
            if (!$res) {
                throw new Exception('保存任务人员失败');
            }
            $this->commit();
            return true;
        } catch (Exception $e) {
            $this->rollback();
            $this->error = $e->getMessage();
            return false;
        }
    }
    public function lists($page, $size, $status, $userId, $orgId, $type) {
        $ret = [];
        if ($type == 1) {
            $ret = $this
                ->field('id as task_id,start_time,title,end_time,status,timeout,type_id')
                ->where([
                    'org_id' => $orgId,
                    'del' => 0,
                    'status' => $status,
                ])
                ->order('id desc')
                ->page($page, $size)
                ->select();
            $ret = $ret ? $ret->toArray() : [];
        }
        else {
            $ret = $this->alias('a')
                ->join('clean_task_user b', 'a.id=b.task_id')
                ->field('a.id as task_id,a.start_time,a.title,a.end_time,a.status,a.timeout,a.type_id')
                ->where([
                    'a.org_id' => $orgId,
                    'a.del' => 0,
                    'a.status' => $status,
                    'b.user_id' => $userId,
                ])
                ->order('a.id desc')
                ->page($page, $size)
                ->select();
            $ret = $ret ? $ret->toArray() : [];
        }
        foreach ($ret as $k => $v) {
            $ret[$k]['type_name'] = Db::name('clean_type')
                ->where('id', $v['type_id'])
                ->where('org_id', $orgId)
                ->value('title');
            $user = Db::name('clean_task_user')
                ->alias('tu')
                ->join('user u', 'u.id = tu.user_id')
                ->where('tu.task_id', $v['task_id'])
                ->column('u.real_name');
            $implode = empty($user) ? [] : implode('/', $user);
            $ret[$k]['staff'] = $implode;
        }
        return $ret ? $ret : [];
    }

    public function taskCount($status, $userId, $orgId) {
        $isDispatch = check_is_dispatch($userId);
        if ($isDispatch) {
            $ret = $this
                ->field('id as task_id,start_time,title,end_time,status,timeout,type_id')
                ->where([
                    'org_id' => $orgId,
                    'del' => 0,
                    'status' => $status,
                ])
                ->count();
        }
        else {
            $ret = $this->alias('a')
                ->join('clean_task_user b', 'a.id=b.task_id')
                ->field('a.id as task_id,a.start_time,a.title,a.end_time,a.status,a.timeout,a.type_id')
                ->where([
                    'a.org_id' => $orgId,
                    'a.del' => 0,
                    'a.status' => $status,
                    'b.user_id' => $userId,
                ])
                ->count();
        }

        return $ret ? $ret : 0;
    }

    public function detail($id) {
        $ret = $this->alias('ct')
            ->field('ct.id,ct.start_time,ct.type_id,ct.end_time,ct.title,t.title as type_name,ct.check_content as report_text')
            ->join('clean_type t', 't.id=ct.type_id', 'left')
            ->where('ct.id', $id)
            ->find();
        $ret = $ret ? $ret->toArray() : [];
        $userName = Db::name('clean_task_user')
            ->alias('tu')
            ->join('user u', 'u.id = tu.user_id')
            ->where('tu.task_id', $id)
            ->column('u.real_name');
        $implode = empty($userName) ? [] : implode('/', $userName);
        $ret['name'] = $implode;
        $formList = Db::name('clean_task_form')
            ->alias('ctf')
            ->join('clean_form cf', 'cf.id = ctf.form_id')
            ->field('cf.id,cf.title as name')
            ->where('task_id', $ret['id'])
            ->select();
        $formList = $formList ? $formList : [];
        foreach ($formList as $k => $v) {
            $record = Db::name('clean_record')
                ->where('task_id', $id)
                ->where('form_id', $v['id'])->find();
            $formList[$k]['status'] = $record ? 1 : 0;
        }
        $ret['form_list'] = $formList;
        return $ret;
    }
    public function addSave($content, $formId, $taskId, $orgId, $formJson, $userId, $consItems) {
        // 检查该任务是已保存
        $res = Db::name('clean_record')
            ->where('task_id', $taskId)
            ->where('form_id', $formId)
            ->find();
        if ($res) {
            HelpHander::error('已上传记录');
        }
        $task = $this->where('id', $taskId)->find();
        $countrecord = Db::name('clean_record')
            ->where('task_id', $taskId)->count();
        $this->startTrans();
        try {
            $data = [
                'org_id' => $orgId,
                'user_id' => $userId,
                'form_id' => $formId,
                'content' => $content,
                'check_json' => $formJson,
                'create_time' => date('Y-m-d H:i:s'),
                'task_id' => $taskId,
            ];

            $ret = Db::name('clean_record')->insertGetId($data);
            $record_id = $ret;
            if (!$ret) {
                \exception('保存失败');
            }
            $countaddr = Db::name('clean_task_form')
                ->where('task_id', $taskId)
                ->count();
            if ($countaddr == $countrecord + 1) {
                $status = 2;
            }
            else {
                $status = 1;
            }
            if ($task['status'] != $status) {
                $ret = $this->where('id', $taskId)->update(['status' => $status]);
                if (!$ret) {
                    \exception('操作失败');
                }
            }
            if ($consItems) { // 耗材
                $consItems = json_decode($consItems, true);
                $mate = [
                    'todo_id' => $record_id,
                    'order_id' => $record_id,
                    'org_id' => $orgId,
                    'user_id' => $userId,
                    'type' => 1,
                    'create_time' => getTime()
                ];
                $todo_mate_id = Db::name('todo_mate')
                    ->insertGetId($mate);
                if (!$todo_mate_id) {
                    \exception('使用物品记录失败');
                }
                $items = [];
                $a = [];
                foreach ($consItems as $k => $v) {
                    $itemInfo = Db::name('mate_goods')
                        ->where('id', $v['itemsId'])
                        ->find();
//                    $pInfo = Db::name('mate_goods')
//                        ->where('id', $itemInfo['pid'])
//                        ->find();
                    if ($itemInfo['nums'] < $v['total']) {
                        \exception($itemInfo['title'] . ' 库存不足');
                    }
                    $items[] = [
                        'todo_mate_id' => $todo_mate_id,
                        'items_id' => $v['itemsId'],
                        'total' => $v['total'],
                        'create_time' => getTime(),
                        'user_id' => $userId,
                        'money' => $itemInfo['price'],
                        'total_money' => $itemInfo['price'] * $v['total'],
                    ];

                    //clean_record_items
                    $a[] = [
                        'org_id'=>$orgId,
                        'record_id'=>$record_id,
                        'items_id'=>$v['itemsId'],
                        'code'=>'',
                        'money'=>$itemInfo['price'],
                        'total'=>$v['total'],
                    ];

                    $res = Db::name('mate_goods')
                        ->where('id', $v['itemsId'])
                        ->setDec('nums', $v['total']);
                    if (!$res) {
                        \exception($itemInfo['title'] . ' 数量修改失败');
                    }
                }
                $res = Db::name('todo_mate_item')
                    ->insertAll($items);
                if (!$res) {
                    \exception('物品使用记录失败');
                }
                $res = Db::name('clean_record_items')
                    ->insertAll($a);
                if (!$res) {
                    \exception('专项保洁使用记录失败');
                }
            }
            $this->commit();
            return true;
        } catch (Exception $e) {
            $this->rollback();
            $this->error = $e->getMessage();
            return false;
        }
    }

    //定时处理超时任务
    public function timer_action(){
        $curTime = date('Y-m-d');
        $map[] = ['del','=',0];
        $map[] = ['status','in',[0,1]];
        $map[] = ['end_time','<',$curTime];
        $this->where($map)
            ->update(['timeout'=>1]);
    }

    public function taskCount2($status, $userId, $orgId) {
//        $isDispatch = check_is_dispatch($userId);
//        if ($isDispatch) {
//            $ret = Db::name('clean_plan_record')
//                ->where('enable',0)
//                ->where('del',0)
//                ->where('org_id',$orgId)
//                ->count();
//        }
//        else {
//            $ret = Db::name('clean_plan_record')
//                ->alias('clr')
//                ->join('clean_plan_user cpu','cpu.record_id = clr.id')
//                ->where('clr.enable',0)
//                ->where('clr.del',0)
//                ->where('clr.org_id',$orgId)
//                ->where('cpu.user_id',$userId)
//                ->count();
//        }


        $ret = Db::name('clean_plan_record')
            ->alias('clr')
            ->join('clean_plan_user cpu','cpu.record_id = clr.id')
            ->where('clr.enable',0)
            ->where('clr.del',0)
            ->where('clr.org_id',$orgId)
            ->where('cpu.user_id',$userId)
            ->count();

        return $ret ? $ret : 0;
    }

}