<?php
namespace app\common\model;
use think\Exception;
use think\Db;
class QualityPlan extends Base {

    public function updates($userId){
        $post = request()->post();
        $post['org_id'] = cur_org_id();
        $post['user_id'] = $userId;

        $validate = new \app\common\validate\QualityPlan();
        $result = $validate->check($post,[]);
        if(true !== $result){
            $this->error = $validate->getError();
            return false;
        }

        Db::startTrans();
        try{
            $curDate = date('Y-m-d H:i:s');
            $data = [
                "title" => $post['title'],
                "start_time" => $post['start_time'],
                "end_time" => $post['end_time'],
                "content" => $post['content'],
                "status" => 0,
                "org_id" => $post['org_id'],
                "user_id" => $post['user_id'],
                "create_time" => $curDate,
            ];
            if($post['start_time'] == date('Y-m-d')){
                $data['status'] = 1; // 进行中
            }
            $planId = Db::name('quality_plan')->insertGetId($data);
            if(!$planId){
                \exception('操作失败');
            }

            $content = json_decode($post['content'],true);
            $tasks = $content['tasks']['list']; // 任务数组
            $addrForms = $content['addrForms'];
            $nforms = [];
            foreach ($addrForms as $k=>$v){
                $forms = [];
                foreach ($v['forms'] as $fk=>$fv){
                    $forms[] = $fv['id'];
                }
                $busids = [];
                foreach ($v['buss'] as $fk=>$fv){
                    $busids[] = $fv['id'];
                }
                $groupId = Db::name('quality_group')->insertGetId([
                    'title' => $v['title'],
                    'org_id' => $post['org_id'],
                    'forms' => $forms?implode(',',$forms):'',
                    'busids' => $busids?implode(',',$busids):'',
                    'type' => $v['type'],
                    'enable' => 1,
                    'del' => 0,
                    'create_time' => getTime()
                ]);
                if(!$groupId){
                    \exception('操作失败');
                }
                $nforms[] = [
                    'quality_group_id' => $groupId
                ];
            }
            foreach ($tasks as $k=>$v){
                foreach ($v['list'] as $kk=>$vv){
                    if($content['dateType']==4 || $content['dateType']==5){//按月,循环周
                        list($a,$b) = explode('~',$vv['day']);
                        $stime = $a.' '.$v['time']['stime'];
                        $etime = $b.' '.$v['time']['etime'];
                    }else{
                        $stime = $vv['day'].' '.$v['time']['stime'];
                        $etime = $vv['day'].' '.$v['time']['etime'];
                        if($v['time']['stype'] == 1){ // 次日
                            $nextday = date('Y-m-d',strtotime($vv['day']) + $v['time']['sday']*24*60*60);
                            $etime = $nextday.' '.$v['time']['etime'];
                        }
                    }

                    $d = [
                        'org_id' => $post['org_id'],
                        'title' => $post['title'],
                        'start_time' => $stime,
                        'end_time' => $etime,
                        'status' => 0,
                        'create_time' => $curDate,
                        'update_time' => $curDate,
                        'plan_id' => $planId,
                        'create_yyyy' => date('Y',strtotime($stime)),
                        'create_yyyymm' => date('Ym',strtotime($stime)),
                        'create_yyyymmdd' => date('Ymd',strtotime($stime)),
                    ];
                    $taskId = Db::name('quality_task')->insertGetId($d);
                    if(!$taskId){
                        \exception('操作失败');
                    }

                    foreach ($nforms as $key=>$val){
                        $nforms[$key]['quality_task_id'] = $taskId;
                    }
                    $fromRet = Db::name('quality_task_addr')->insertAll($nforms);
                    if($fromRet != count($nforms)){
                        \exception('操作失败');
                    }

                    $uds = [];
                    foreach ($vv['userIds'] as $key=>$val){
                        $uds[] = [
                            'quality_task_id' => $taskId,
                            'user_id' => $val
                        ];
                    }
                    $userRet = Db::name('quality_task_user')->insertAll($uds);
                    if($userRet != count($uds)){
                        \exception('操作失败');
                    }
                }
            }

            Db::commit();
            return true;
        }catch (\Exception $e){
            // 回滚事务
            $this->error = $e->getMessage();
            Db::rollback();
            return false;
        }

    }

    public function updatesOld($userId){
        $post = request()->post();
        $post['org_id'] = cur_org_id();
        $post['user_id'] = $userId;

        $validate = new \app\common\validate\QualityPlan();
        $result = $validate->check($post,[]);
        if(true !== $result){
            $this->error = $validate->getError();
            return false;
        }

        Db::startTrans();
        try{
            $curDate = date('Y-m-d H:i:s');
            $data = [
                "title" => $post['title'],
                "start_time" => $post['start_time'],
                "end_time" => $post['end_time'],
                "content" => $post['content'],
                "status" => 0,
                "org_id" => $post['org_id'],
                "user_id" => $post['user_id'],
                "create_time" => $curDate,
            ];
            if($post['start_time'] == date('Y-m-d')){
                $data['status'] = 1; // 进行中
            }
            $planId = Db::name('quality_plan')->insertGetId($data);
            if(!$planId){
                \exception('操作失败');
            }

            $content = json_decode($post['content'],true);
            $tasks = $content['tasks']['list']; // 任务数组
            $addrForms = $content['addrForms'];
            $addrForms = list_sort_by($addrForms,'sorts','asc'); // 排序
            $nforms = [];
            foreach ($addrForms as $k=>$v){
                $nforms[] = [
                    'quality_group_id' => $v['addrId'],
                    'sorts' => (int)$v['sorts']
                ];
            }
            foreach ($tasks as $k=>$v){
                foreach ($v['list'] as $kk=>$vv){
                    $stime = $vv['day'].' '.$v['time']['stime'];
                    $etime = $vv['day'].' '.$v['time']['etime'];
                    if($v['time']['stype'] == 1){ // 次日
                        $nextday = date('Y-m-d',strtotime($vv['day']) + $v['time']['sday']*24*60*60);
                        $etime = $nextday.' '.$v['time']['etime'];
                    }
                    $d = [
                        'org_id' => $post['org_id'],
                        'title' => $post['title'],
                        'start_time' => $stime,
                        'end_time' => $etime,
                        'status' => 0,
                        'create_time' => $curDate,
                        'update_time' => $curDate,
                        'plan_id' => $planId,
                        'create_yyyy' => date('Y',strtotime($stime)),
                        'create_yyyymm' => date('Ym',strtotime($stime)),
                        'create_yyyymmdd' => date('Ymd',strtotime($stime)),
                    ];
                    $taskId = Db::name('quality_task')->insertGetId($d);
                    if(!$taskId){
                        \exception('操作失败');
                    }

                    foreach ($nforms as $key=>$val){
                        $nforms[$key]['quality_task_id'] = $taskId;
                    }
                    $fromRet = Db::name('quality_task_addr')->insertAll($nforms);
                    if($fromRet != count($nforms)){
                        \exception('操作失败');
                    }

                    $uds = [];
                    foreach ($vv['userIds'] as $key=>$val){
                        $uds[] = [
                            'quality_task_id' => $taskId,
                            'user_id' => $val
                        ];
                    }
                    $userRet = Db::name('quality_task_user')->insertAll($uds);
                    if($userRet != count($uds)){
                        \exception('操作失败');
                    }
                }
            }

            Db::commit();
            return true;
        }catch (\Exception $e){
            // 回滚事务
            $this->error = $e->getMessage();
            Db::rollback();
            return false;
        }

    }

    // 获取组织某一类型巡更计划
    public function getListByMode($orgId){
        $lists = Db::name('quality_plan')
            ->where('del',0)
            ->where('org_id',$orgId)
            ->field('id,title,start_time,end_time,status')
            ->order('id desc')
            ->select();
        return $lists?$lists:[];
    }

}