<?php

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

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

    public function addSave() {
        $data = request()->post();
        $data['forms'] = !empty($data['forms'])?implode(',',$data['forms']):'';
        $data['addrs'] = !empty($data['addrs'])?implode(',',$data['addrs']):'';
        $data['org_id'] = cur_org_id();
        $result = validate($this->validateName)->check($data, [], 'add');
        if (true !== $result) {
            $this->error = validate($this->validateName)->getError();
            return false;
        }

        $user = $data['user'];
        unset($data['user']);
        $this->startTrans();
        try {
            $forms = explode(',',$data['forms']);
            $addrs = explode(',',$data['addrs']);
            unset($data['forms']);
            unset($data['addrs']);

            foreach ($forms as $k=>$v){
                //foreach ($addrs as $kk=>$vv){
                    $rdata = [
                        'org_id' => $data['org_id'],
                        'form_id' => $v,
                        'address_id' => implode(',',$addrs),
                        'plan_id' => $data['plan_id'],
                        'start' => $data['start'],
                        'end' => $data['end'],
                        'remark' => $data['remark'],
                        'create_time' => getTime()
                    ];
                    $rid = Db::name('f_clean_plan_record')->insertGetId($rdata);
                    if(!$rid){
                        \exception('任务保存失败');
                    }

                    //添加任务人员
                    $users = explode(',', $user);
                    $nArr = [];
                    foreach ($users as $v) {
                        if($v){
                            $nArr[] = [
                                'record_id' => $rid,
                                'user_id' => $v
                            ];
                        }
                    }
                    if($nArr){
                        $res = Db::name('f_clean_plan_user')->insertAll($nArr);
                        if (!$res) {
                            \exception('保存失败');
                        }
                    }
              //  }
            }

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

    public function editSave() {
        $data = request()->post();
        $data['org_id'] = cur_org_id();
        $data['address_id'] = !empty($data['address_id'])?implode(',',$data['address_id']):'';

        $result = validate($this->validateName)->check($data, [], 'edit');
        if (true !== $result) {
            $this->error = validate($this->validateName)->getError();
            return false;
        }
        $user = $data['user'];
        unset($data['user']);
        $this->startTrans();
        try {
            $data['update_time'] = getTime();
            $res = Db::name('f_clean_plan_record')->where('id',$data['id'])->update($data);
            if(!$res){
                \exception('操作失败');
            }

            Db::name('f_clean_plan_user')->where('record_id',$data['id'])->delete();

            //添加任务人员
            $users = explode(',', $user);
            $nArr = [];
            foreach ($users as $v) {
                if($v){
                    $nArr[] = [
                        'record_id' => $data['id'],
                        'user_id' => $v
                    ];
                }
            }
            if($nArr){
                $res = Db::name('f_clean_plan_user')->insertAll($nArr);
                if (!$res) {
                    \exception('保存失败');
                }
            }

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

    public function get_list_by_time($orgId,$start,$end){

        $map[] = ['org_id','=',$orgId];
        $map[] = ['del','=',0];
        $map[] = ['start','<=',$end];
        $map[] = ['end','>=',$start];

        $list = $this->field('id,form_id,address_id,start,end,enable')
            ->where($map)
            ->select();
        $list = $list?$list->toArray():[];
        foreach ($list as $k=>$v){
            $list[$k]['ftitle'] = Db::name('f_clean_type')->where('id',$v['form_id'])->value('title');
            $list[$k]['atitle'] = Db::name('address')->where('id',$v['address_id'])->value('title');
        }
        return $list?$list:array();
    }

    public function detail($id,$orgId){
        $info = Db::name('f_clean_plan_record')->where('org_id',$orgId)->where('id',$id)->where('del',0)->find();
        if(!$info){
            $this->error = '记录不存在';
            return false;
        }
        $users = Db::name('f_clean_plan_user')
            ->alias('a')
            ->join('user b','a.user_id = b.id')
            ->where('a.record_id',$info['id'])
            ->column('b.real_name');
        $info['users'] = $users?implode(',',$users):'';
        $address = Db::name('address')
            ->where('id','in',explode(',',$info['address_id']))->select();
        $info['address'] = $address?implode(',',array_column($address,'title')):'';
        $forms = Db::name('f_clean_type')->where('id',$info['form_id'])->find();
        $info['form'] = $forms?$forms['title']:'';
        $info['finish_user'] = '';
        if($info['finish_user_id'] > 0){
            $info['finish_user'] = Db::name('user')->where('id',$info['finish_user_id'])->value('real_name');
        }

        $info['imgs'] = $info['imgs']?$info['imgs']:'';
        return $info;
    }

    public function lists($page,$size,$status,$day,$userId,$orgId) {
        $map[] = ['b.del','=',0];
        $map[] = ['b.enable','=',$status];
        $map[] = ['b.start','<=',$day];
        $map[] = ['b.end','>=',$day];
        $map[] = ['b.org_id','=',$orgId];
        $map[] = ['a.user_id','=',$userId];

        $lists = Db::name('f_clean_plan_user')
            ->alias('a')
            ->join('f_clean_plan_record b','a.record_id = b.id')
            ->where($map)
            ->order('b.id desc')
            ->field('b.id,b.address_id,b.form_id,b.enable,b.start,b.end')
            ->page($page, $size)
            ->select();
        $lists = $lists?$lists:[];
        foreach ($lists as $k=>$v){
            $users = Db::name('f_clean_plan_user')
                ->alias('a')
                ->join('user b','a.user_id = b.id')
                ->where('a.record_id',$v['id'])
                ->column('b.real_name');
            $lists[$k]['users'] = $users?implode(',',$users):'';
            $address = Db::name('address')
                ->where('id','in',explode(',',$v['address_id']))
                ->select();
            $lists[$k]['address'] = $address?implode(',',array_column($address,'title')):'';
            $forms = Db::name('f_clean_type')->where('id',$v['form_id'])->find();
            $lists[$k]['form'] = $forms?$forms['title']:'';
        }

        return $lists;
    }

    public function finish($id,$content,$imgs,$userId,$orgId){
        $info = Db::name('f_clean_plan_record')->where('org_id',$orgId)->where('id',$id)->where('del',0)->find();
        if(!$info){
            $this->error = '记录不存在';
            return false;
        }
        if($info['enable'] == 1){
            $this->error = '已完成,勿重复操作';
            return false;
        }
        $users = Db::name('f_clean_plan_user')
            ->alias('a')
            ->join('user b','a.user_id = b.id')
            ->where('a.record_id',$info['id'])
            ->where('a.user_id',$userId)
            ->column('b.id');
        if(!$users){
            $this->error = '无权限操作';
            return false;
        }
        $ret = Db::name('f_clean_plan_record')->where('id',$id)->update([
            'enable' => 1,
            'finish_user_id' => $userId,
            'finish_time' => getTime(),
            'content' => $content,
            'imgs' => $imgs
        ]);
        if(!$ret){
            $this->error = '操作失败';
            return false;
        }
        return true;
    }
}