<?php
namespace app\api\controller\v1;
use app\api\model\Ry;
use app\api\model\Ryjr as RyjrModel;
use app\api\model\Subject;
use app\api\model\Ry as RyModel;
use OpenApi\Annotations as OA;
use app\BaseController;
use thans\jwt\facade\JWTAuth;
use think\facade\Db;
use OSS\Core\OssException;
use OSS\OssClient;

use think\facade\Request as re;
use think\Request;
use think\facade\Cache;
use thans\jwt\JWT;
use rsa\Rsa;
use function Symfony\Component\VarDumper\Dumper\esc;

class Index extends BaseController
{
    use ResponseJson;
    protected $request;
    protected $middleware = [
        'jwt' => ['except' => ['login']],
//        'check' => ['except' => ['login']]

    ];

    public function __construct(Request $request)
    {
        $this->request = $request;
    }
//asasdfasdf123
    public function login()
    {
        $data = $this->request->post();

        $res = Db::name("ry")->field('rymc,qydm,rybh,groupname')->where([['rybh', '=', $data['login_name']], ['kl', '=', $data['pwd']],['groupname','<>','企业']])->findOrEmpty();

        $res2 = Db::name("jcdw")->field('qydm,name,groupname,id')->where([['login_name', '=', $data['login_name']], ['pwd', '=', $data['pwd']]])->findOrEmpty();
//        $res['qymc'] = Db::name("qyBasic")->field('qymc')->where('qydm','=',$res['qydm'])->find();

        if(isset($res['qydm'])){

            $res['token'] = JWTAuth::builder([
                'qydm' => $res['qydm'],
                'groupname' => $res['groupname'],
            ]);
            $res['re_ip'] = $this->request->ip();
            Cache::store('redis')->set($res['re_ip'],$res['token'],1 * 24 * 3600);
            $res['message'] = '登录成功';

            return $this->jsonSuccessData($res);
        } else if(isset($res2['qydm'])){
            $res2['token'] = JWTAuth::builder([
                'qydm' => $res2['qydm'],
                'unit_id' => $res2['id'],
                'groupname' => $res2['groupname'],
            ]);
            $res2['re_ip'] = $this->request->ip();
            Cache::store('redis')->set($res2['re_ip'],$res2['token'],1 * 24 * 3600);
            $res2['message'] = '登录成功';

            return $this->jsonSuccessData($res2);

        }else{
            return $this->jsonData(-1, "用户名或密码错误");
        }
    }

    /**
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 获取任务接口：param:  pageNum  pageSize
     */



    //渲染任务列表（监管单位）
    public function getTaskList(){
        $data = $this->request->post();
        $pageNum=$data['pageNum'];
        $pageSize=$data['pageSize'];
        $map1=[];
        $map2=[];
        $map3=[];
        $map4=[];
        if(isset($data['year'])){
            $map1=[
                ['year','=',$data['year']],
                ['task_class','=',$data['task_class']]
            ];
        }
        if(isset($data['ispublic'])){
            $map2=[
                ['ispublic','=',$data['ispublic']],
                ['task_class','=',$data['task_class']]
            ];
        }
        if(isset($data['task_name'])){
            $map4=[
                ['task_name','LIKE','%'.$data['task_name'].'%'],
                ['task_class','=',$data['task_class']]
            ];
        }
        if(isset($data['starttime'])&&isset($data['endtime'])){
            $map3=[
                ['starttime','>=',$data['starttime']],
                ['endtime','<=',$data['endtime']],
                ['task_class','=',$data['task_class']]
            ];
        }
        $sumMap=[];
        if (count($map1)!=0){
            $sumMap[]=$map1;
        }
        if (count($map2)!=0){
            $sumMap[]=$map2;
        }
        if (count($map3)!=0){
            $sumMap[]=$map3;
        }if (count($map4)!=0){
            $sumMap[]=$map4;
        }else{
            $sumMap[]=[
                ['task_class','=',$data['task_class']]
            ];

        }

        if (count($sumMap)!=0){
            $res['rows'] = Db::name("ccjc")->where($sumMap)->page($pageNum,$pageSize)->select();
            $res['total'] = Db::name("ccjc")->where($sumMap)->count();
        }else{
            $res['rows'] = Db::name("ccjc")->page($pageNum,$pageSize)->select();
            $res['total'] = Db::name("ccjc")->count();
        }

        return $this->jsonSuccessData($res);
    }

    /**、
     * @return \think\response\Json
     * 添加任务
     */


    /***
     * todo 增加没写
     */
    //添加任务并关联牵头单位
    public function AddTask(){
        $data = $this->request->post();
        $resid=Db::name("ccjc")->strict(false)->insertGetId($data);
        for($i=0;$i<count($data['orgs']);$i++){
            $orgs[$i]['task_id']=$resid;
            $orgs[$i]['unit_id']=$data['orgs'][$i]['id'];
            $orgs[$i]['unit_name']=$data['orgs'][$i]['name'];
        }
        $res = Db::name('orgs')->strict(false)->insertAll($orgs);
        return $this->jsonSuccessData($res);
    }

    public function ossUpload(Request $request){
        $file = $request->file('file');
        if ($file == null) {                                    //判断文件是否为空
            return $this ->jsonResponse(-1,'未上传文件');
        }

        $data= $request -> param();


        // 阿里云主账号AccessKey,在OSS控制台主页常用入口处有快速通道可以快速查看你的AccessKey ID($accessKeyId)以及Access Key Secret($accessKeySecret )
        $accessKeyId = 'LTAI4G1xGunUnwkgq48jFWi9';
        $accessKeySecret = '17PK5dY7WnLJR1ejgsopTUBUOzS05S';
        //Endpoint(地域节点)查看位置在文章下方
        $endpoint = 'http://oss-cn-hangzhou.aliyuncs.com';
        //创建Bucket填写的名称
        $bucket = 'syjcimage';
        //设置保存的路径(前面不要加'/',否则会出错)
        $path = 'govFile/'.time(). '/';
        //下面这三项应该都知道
        $name = $_FILES['file']['name'];
        $tmp_name = $_FILES['file']['tmp_name'];
        $error = $_FILES['file']['error'];
        //过滤错误(临时测试时使用,代码写的比较简陋)
        if ($error) {
            switch ($error) {
                case 1 :
                    $error_message = '您上传的文件超过了PHP.INI配置文件中UPLOAD_MAX-FILESIZE的大小';
                    break;
                case 2 :
                    $error_message = '您上传的文件超过了PHP.INI配置文件中的post_max_size的大小';
                    break;
                case 3 :
                    $error_message = '文件只被部分上传';
                    break;
                case 4 :
                    $error_message = '文件不能为空';
                    break;
                default :
                    $error_message = '未知错误';
            }
            die($error_message);
        }
        //文件名生成
        $arr_name = explode('.', $name);
        //源文件的后缀
        $extension = end($arr_name);
        /**
         * 判断上传文件是否合法
         * 判断截取上传文件名是否为
         * jpeg，jpg，png其中之一
         */
        if (!in_array($extension, array("jpeg", "jpg", "png", "PNG", "JPG", "JPEG","pdf","PDF","XLS","xls","doc","DOC","docx","xlsx"))) {
            return $this->jsonData(-2, '上传文件不合法');

        }

//            try {
//                validate(['file' => ['fileSize:2*1024*1024']])->check(['file' => $file]);
//            } catch (ValidateException $e) {
//                $return['msg'] = $e->getMessage();
//
//            }
        //新的文件名
        $new_name = $name;
        //文件在OSS上的URL
        $url=$path.$new_name;
        //抛出异常

        try{
            //相比传统的操作,其实就多了两个步骤
            //第一步是根据上面的参数实例化一个对象
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
            //这一步相当于之前把临时文件移入到设置的地址那步,只是以前的是自己的服务器上,现在是OSS;
            $result =$ossClient->uploadFile($bucket,$url,$tmp_name);
            //返回的参数
            if (isset($result['info']['http_code']) AND $result['info']['http_code']==200) {
                $arr=[
                    'fileName' => $new_name,
                    'fileUrl'  => $result['info']['url']
                ];

                return $this->jsonSuccessData($arr);
            }else{
                return $this->jsonData(-1,'上传失败');
            }
        } catch(OssException $e) {
            $msg = $e->getMessage();
            return $this->jsonData(-1,$msg);
        }


    }

    /**
     * @return \think\response\Json
     * 删除任务  param:id
     */

    //删除任务
    public function delTask(){
        $data = $this->request->post();
        halt($data);
        $delarr = $data['delarr'];
            for($i=0;$i<count($delarr);$i++){
                $res=Db::name("ccjc")->where('id',$delarr[$i])->delete();

            }
        return $this->jsonSuccessData($res);
    }

    /**
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * 发布和废止   param: id  ispublic
     * 0:未发布 1：发布  2：废止
     */

    //更新任务发布状态
    public function isPublicTask(){
        $data = $this->request->post();
        $pubarr = $data['pubarr'];
            for($i=0;$i<count($pubarr);$i++) {
                $res = Db::name("ccjc")->where(['id'=>$pubarr[$i]['id']])->update(["ispublic" => $pubarr[$i]["ispublic"]]);
            }
        return $this->jsonSuccessData($res);

    }
    /**
     * 获取检测单位列表   param:pageNum    pageSize
     */

    //获取检测单位列表
    public function getTestList(){
        $data = $this->request->post();
        $pageNum=$data['pageNum'];
        $pageSize=$data['pageSize'];

        $res['rows'] = Db::name("jcdw")->page($pageNum,$pageSize)->select();
        $res['total'] = Db::name("jcdw")->count();
        return $this->jsonSuccessData($res);
    }

    /**
     * 获取检测单位所属任务接口：param:  pageNum  pageSize
     */


    获取牵头单位所属任务
    public function getTaskListTest(){
        $data = $this->request->post();
        $unit_id=$this->request->user['unit_id']->getValue();
        $pageNum=$data['pageNum'];
        $pageSize=$data['pageSize'];
        $map1=[];
        $map2=[];
        $map3=[];
        $map4=[];

        if(isset($data['year'])){
            $map1=[
                ['t_ccjc.year','=',$data['year']]
            ];
        }
        if(isset($data['ispublic'])){
            $map2=[
                ['t_ccjc.ispublic','=',$data['ispublic']]
            ];
        }
        if(isset($data['task_name'])){
            $map4=[
                ['t_ccjc.task_name','LIKE','%'.$data['task_name'].'%']
            ];
        }
        if(isset($data['starttime'])&&isset($data['endtime'])){
            $map3=[
                ['t_ccjc.starttime','>=',$data['starttime']],
                ['t_ccjc.endtime','<=',$data['endtime']]
            ];
        }
        $sumMap=[];
        if (count($map1)!=0){
            $sumMap[]=$map1;
        }
        if (count($map2)!=0){
            $sumMap[]=$map2;
        }
        if (count($map3)!=0){
            $sumMap[]=$map3;
        }if (count($map4)!=0){
            $sumMap[]=$map4;
        }
        $sumMap[]=['t_orgs.unit_id','=',$unit_id];
        $sumMap[]=['t_ccjc.task_class','=',$data['task_class']];
        $sumMap[]=['t_ccjc.ispublic','<>',0];

//        $sumMap[]=['t_ccjc.ispublic','<>',0];
        if ($map4||$map1||$map2||$map3){
            $res['rows'] =
                Db::name("orgs")
                    ->Join('t_ccjc','t_orgs.task_id=t_ccjc.id')
                    ->where($sumMap)
                    ->page($pageNum,$pageSize)
                    ->select();
            $res['total'] = Db::name("orgs")
                ->Join('t_ccjc','t_orgs.task_id=t_ccjc.id')
                ->where($sumMap)
                ->count();
        }else{
            $res['rows'] = Db::name("orgs")
                ->Join('t_ccjc','t_orgs.task_id=t_ccjc.id')
                ->where($sumMap)
                ->page($pageNum,$pageSize)
                ->select();
            $res['total'] = Db::name("orgs")->Join('t_ccjc','t_orgs.task_id=t_ccjc.id')->where($sumMap)->count();
        }

        return $this->jsonSuccessData($res);
    }

    public function getTaskcd(){
        $data = $this->request->post();
        $pageNum=$data['pageNum'];
        $pageSize=$data['pageSize'];
        $map1=[];
        $map2=[];
        $map3=[];
        $map4=[];
        if(isset($data['year'])){
            $map1=[
                ['year','=',$data['year']],
                ['task_class','=',$data['task_class']]
            ];
        }
        if(isset($data['ispublic'])){
            $map2=[
                ['ispublic','=',$data['ispublic']],
                ['task_class','=',$data['task_class']]
            ];
        }
        if(isset($data['task_name'])){
            $map4=[
                ['task_name','LIKE','%'.$data['task_name'].'%'],
                ['task_class','=',$data['task_class']]
            ];
        }
        if(isset($data['starttime'])&&isset($data['endtime'])){
            $map3=[
                ['starttime','>=',$data['starttime']],
                ['endtime','<=',$data['endtime']],
                ['task_class','=',$data['task_class']]
            ];
        }
        $sumMap=[];
        if (count($map1)!=0){
            $sumMap[]=$map1;
        }
        if (count($map2)!=0){
            $sumMap[]=$map2;
        }
        if (count($map3)!=0){
            $sumMap[]=$map3;
        }if (count($map4)!=0){
            $sumMap[]=$map4;
        }else{
            $sumMap[]=[
                ['task_class','=',$data['task_class']],
            ];

        }
        $unit_id=$this->request->user['unit_id']->getValue();
        $sumMap[]=['t_undertake.bear_id','=',$unit_id];
        $sumMap[]=['t_ccjc.ispublic','<>',0];
        $sumMap[]=['t_ccjc.ispublic','<>',1];

        if (count($sumMap)!=0){
            $res['rows'] = Db::name("undertake")
                ->Join('t_ccjc','t_undertake.task_id=t_ccjc.id')
                ->where($sumMap)
                ->select();
//            $res['rows'] = Db::name("ccjc")->where($sumMap)->page($pageNum,$pageSize)->select();
            $res['total'] = Db::name("undertake")
                ->Join('t_ccjc','t_undertake.task_id=t_ccjc.id')
                ->where($sumMap)
                ->count();
//            $res['total'] = Db::name("ccjc")->where($sumMap)->count();
        }else{
            $res['rows'] = Db::name("undertake")
                ->Join('t_ccjc','t_undertake.task_id=t_ccjc.id')
                ->where($sumMap)
                ->page($pageNum,$pageSize)
                ->select();
            $res['total'] = Db::name("undertake")
                ->Join('t_ccjc','t_undertake.task_id=t_ccjc.id')
                ->where($sumMap)
                ->count();

        }

        return $this->jsonSuccessData($res);
    }

    /**
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */



    //1.在任务里添加承担单位    2.绑定关系undertake
    public function AddUnderTask(){
        $data=$this->request->post();
        $data['userid']=$this->request->user['unit_id']->getValue();

        $bear_name = Db::name('jcdw')->field('name')->where('id',$data['bear_id'])->find();
//        dump($bear_name);die;
        $report_name = Db::name('jcdw')->field('name')->where('id',$data['report_id'])->find();
        $check_name = Db::name('jcdw')->field('name')->where('id',$data['check_id'])->find();
        $map =[
            'bear_name' => $bear_name['name'],
            'report_name' => $report_name['name'],
            'sample_number' => $data['sample_number'],
            'address' => $data['address'],
            'uploadtime' => $data['uploadtime'],
            'task_id'=> $data['task_id'],
            'unit_id'=> $data['userid'],
            'bear_id'=> $data['bear_id'],
            'report_id' => $data['report_id'],
            'check_id' => $data['check_id'],
            'check_name' => $check_name['name']
        ];

        $res = Db::name('undertake')->strict(false)->insert($map);

        return $this->jsonSuccessData($res);
    }

    //牵头单位发布任务
    public function qtRelease(){
        $data=$this->request->post();
        $res = Db::name('ccjc')->where('id',$data['task_id'])->update(['ispublic' => 5]);

        return $this->jsonSuccessData($res);
    }


    //渲染所属牵头单位下承担单位的信息
    public function getUnderTask(){
        $data=$this->request->post();
        $data['userid']=$this->request->user['unit_id']->getValue();
        $map = [['task_id','=',$data['task_id']],['unit_id','=',$data['userid']]];
        $res['rows'] = Db::name('undertake')->where($map)->select();
        $res['total'] = Db::name('undertake')->where($map)->count();

        return $this->jsonSuccessData($res);
    }


    //获取模型列表
    public function  getModelList(){
        $data = $this->request->post();
        $data['userid']=$this->request->user['unit_id']->getValue();
        $pageNum=$data['pageNum'];
        $pageSize=$data['pageSize'];
        if($data['type_id']!=''){
            $res['rows'] = Db::name('test_model')
                ->field('t_test_model.id,t_test_model.name,t_test_model.type_id,t_test_model.creattime,t_test_model.updatetime')
                ->where([['t_test_model.userid','=',$data['userid']],['t_test_model.type_id','=',$data['type_id']]])
                ->leftJoin('t_test_product','t_test_model.id=t_test_product.test_model_id')
                ->leftjoin('t_test_pesticides','t_test_model.id=t_test_pesticides.test_model_id')
                ->distinct(true)
                ->page($pageNum,$pageSize)
                ->select();
            $res['total'] = count(Db::name('test_model')->field('t_test_model.id,t_test_model.name,t_test_model.type_id')->where([['t_test_model.userid','=',$data['userid']],['t_test_model.type_id','=',$data['type_id']]])->leftJoin('t_test_product','t_test_model.id=t_test_product.test_model_id')->leftjoin('t_test_pesticides','t_test_model.id=t_test_pesticides.test_model_id')->distinct(true)->select());

        }else {
            $res['rows'] = Db::name('test_model')
                ->field('t_test_model.id,t_test_model.name,t_test_model.type_id,t_test_model.creattime,t_test_model.updatetime')
                ->where('t_test_model.userid', $data['userid'])
                ->leftJoin('t_test_product', 't_test_model.id=t_test_product.test_model_id')
                ->leftjoin('t_test_pesticides', 't_test_model.id=t_test_pesticides.test_model_id')
                ->distinct(true)->page($pageNum, $pageSize)
                ->select();
            $res['total'] = count(Db::name('test_model')->field('t_test_model.id,t_test_model.name,t_test_model.type_id')->where('t_test_model.userid', $data['userid'])->leftJoin('t_test_product', 't_test_model.id=t_test_product.test_model_id')->leftjoin('t_test_pesticides', 't_test_model.id=t_test_pesticides.test_model_id')->distinct(true)->select());
        }
        return $this->jsonSuccessData($res);
    }

    //查看模型详情
    public function  getModeldetail(){
        $data = $this->request->post();

            $res['name'] = Db::name('test_model')->where([
                ['id','=',$data['id']]
            ])->field('id,name,type_id')
                ->find();

        $res['pesticides'] = Db::name('test_pesticides')->where([
            ['test_model_id','=',$data['id']]
        ])->field('test_name as name,test_id as id')
            ->select();

        $res['product'] = Db::name('test_product')->where([
            ['test_model_id','=',$data['id']]
        ])->field('product_name as name,product_id as id')
            ->select();

        return $this->jsonSuccessData($res);
    }


    /**
     *
     */
    public function test()
    {
        $data = $this->request->post();
        $map = [['type_id','=',$data['type_id']],['parent_id','=','0'.$data['type_id']]];

        $res=Db::name('product_class')->field('id,parent_id,product_code,name,alias')->where($map)->select()->toArray();

        for ($i=0;$i<count($res);$i++){
            $res[$i]['children']=Db::name('product_class')->field('id,parent_id,product_code,name,alias')->distinct(true)->where('parent_id','=',$res[$i]['product_code'])->select()->toArray();
            for($j=0;$j<count($res[$i]['children']);$j++){
                $res[$i]['children'][$j]['children']=Db::name('product_class')->field('id,parent_id,product_code,name,alias')->distinct(true)->where('parent_id','=',$res[$i]['children'][$j]['product_code'])->select()->toArray();

            }
        }
        return $this->jsonSuccessData($res);
    }
    function tree($res,$parent_id){
        $arr=[];
        foreach ($res as $k=> $v){

            if($v['parent_id']==$parent_id){
                    unset($res[$k]);
                    $v['children']=$this->tree($res, $v['product_code']);
                    $arr[]=$v;
            }
        }

        return $arr;
    }
    public function getProductList(){
        $data = $this->request->post();
        $map = [['type_id','=',$data['type_id']]];

        $res=Db::name('product_class')->field('id,parent_id,product_code,name,alias')->where($map)->select()->toArray();

        $arr_res = $this->tree($res,'0'.$data['type_id']);
        return $this->jsonSuccessData($arr_res);
    }
    public function getPesticidesList(){
        $data = $this->request->post();
        $pageNum=$data['pageNum'];
        $pageSize=$data['pageSize'];
        if(isset($data['keyword'])){
            $res['rows'] = Db::name("pesticides")->where('name','like','%'.$data['keyword'].'%')->page($pageNum,$pageSize)->select();
            $res['total'] = Db::name("pesticides")->where('name','like','%'.$data['keyword'].'%')->count();

        }else{
            $res['rows'] = Db::name("pesticides")->page($pageNum,$pageSize)->select();
            $res['total'] = Db::name("pesticides")->count();

        }
        return $this->jsonSuccessData($res);

    }

    /**
     *
     * 农药残留表格
     */
//    新增模型
    public function saveModel(){
        $data=$this->request->post();
        $data['userid']=$this->request->user['unit_id']->getValue();
        $res['model']=Db::name('test_model')->strict(false)->insertGetId($data);
        $product=[];
        foreach ($data['product'] as $k=>$v){
            $j=[];
            $j['test_model_id']=$res['model'];
            $j['product_id']=$v['id'];
            $j['product_name']=$v['name'];
            $product[]=$j;
        }
        $pesticides=[];
        foreach ($data['pesticides'] as $i=>$o){
            $p=[];
            $p['test_model_id']=$res['model'];
            $p['test_name']=$o['name'];
            $p['test_id']=$o['id'];
            $pesticides[]=$p;

        }
        $res['product']=Db::name('test_product')->strict(false)->insertAll($product);
        $res['pesticides']=Db::name('test_pesticides')->strict(false)->insertAll($pesticides);
        return $this->jsonSuccessData($res);

    }

    //修改模型
    public function DoEditModelInfo(){
        $data = $this->request->post();
        $condition = ['id'=>$data['id']];
        Db::name('test_model')
            ->where($condition)
            ->data(['name' => $data['name'],'type_id' =>$data['type_id']])
            ->update();


        $res['id']=$data['id'];
        $res['type_id']=$data['type_id'];
        Db::name('test_product')
            ->where("test_model_id",$data['id'])
        ->delete();

        Db::name('test_pesticides')
            ->where("test_model_id",$data['id'])
            ->delete();

        $product=[];
        foreach ($data['product'] as $k=>$v){
            $j=[];
            $j['test_model_id']=$res['id'];
            $j['product_id']=$v['id'];
            $j['product_name']=$v['name'];
            $product[]=$j;
        }

        $pesticides=[];
        foreach ($data['pesticides'] as $i=>$o){
            $p=[];
            $p['test_model_id']=$res['id'];
            $p['test_name']=$o['name'];
            $p['test_id']=$o['id'];
            $pesticides[]=$p;

        }
        $res['product']=Db::name('test_product')->strict(false)->insertAll($product);
        $res['pesticides']=Db::name('test_pesticides')->strict(false)->insertAll($pesticides);
        return $this->jsonSuccessData($res);

    }

//    删除模型
    public function delModel(){
        $data = $this->request->post();
        $delarr = $data['delarr'];

        $id = '';
        for($j = 0; $j<count($delarr) ; $j++){
            if ($j == 0){
                $id = $delarr[$j]['id'];
            }else{
                $id = $delarr[$j]['id'].",".$id;
            }
        }

        $map=[];
        $map=[['test_model_id','in',$id]];

        $map1 = [['id','in',$id]];

        $result1 = Db::name("test_product")->where($map)->delete();

        $result2 = Db::name("test_pesticides")->where($map)->delete();

        $result3 = Db::name("test_model")->where($map1)->delete();


        if($result1 && $result2 && $result3){
            return $this->jsonData(0,"信息删除成功");
        }else{
            return $this->jsonData(-1,"信息删除失败");
        }
        return $this->jsonSuccessData($id);
    }


    public function bindModel(){
        $data = $this->request->post();
        $res = Db::name('ccjc')->where('id',$data['id'])->update(['is_divide'=>$data['is_divide'],'test_model_id'=>$data['test_model_id'],'endtime_cydsb'=>$data['endtime_cydsb']]);
        return $this->jsonSuccessData($res);
    }
    public function getTestObj(){
        $data=$this->request->post();
        $model = Db::name('ccjc')->where('id',$data['id'])->field('test_model_id')->find();
        $res = Db::name('test_model')->where('t_test_model.id',$model['test_model_id'])->join('t_test_product','t_test_model.id=t_test_product.test_model_id')->field('t_test_product.product_id,t_test_product.product_name')->select();
        return $this->jsonSuccessData($res);
    }
    public function saveSample(){
        $data=$this->request->post();
        $data['units_id']=Db::name('units_test')->strict(false)->insertGetId($data['units']);
        $data['product_unit']=Db::name('production')->strict(false)->insertGetId($data['production']);
        $data['sample_unit']=$this->request->user['unit_id']->getValue();
        $res=Db::name('cyd')->strict(false)->insert($data);
        return $this->jsonSuccessData($res);

    }
    public function getSampleList(){
        $data = $this->request->post();
        $pageNum=$data['pageNum'];
        $pageSize=$data['pageSize'];
        $data['sample_unit']=$this->request->user['unit_id']->getValue();
        $map=[['t_cyd.sample_unit','=',$data['sample_unit']],['t_cyd.task_id','=',$data['task_id']]];

        $res['rows'] = Db::name('cyd')->where($map)->field('t_cyd.id,t_cyd.sample_name,t_cyd.sample_id,t_cyd.sample_date,t_production.production_name,t_cyd.place,t_cyd.status,t_units_test.units_name,t_cyd.sample_unit_name,t_cyd.test_result,t_cyd.test_status,t_cyd.jc_value_id')->leftJoin('t_production','t_cyd.product_unit=t_production.id')->leftJoin('t_units_test','t_cyd.units_id=t_units_test.id')->page($pageNum,$pageSize)->select();
        $res['total'] = Db::name('cyd')->where($map)->leftJoin('t_production','t_cyd.product_unit=t_production.id')->leftJoin('t_units_test','t_cyd.units_id=t_units_test.id')->count();
        return $this->jsonSuccessData($res);
    }
    public function getSampleId(){
        $data=$this->request->post();
        $task = Db::name('ccjc')->where('id',$data['id'])->field('task_class')->find();
        $count = Db::name('cyd')->whereDay('createtime','today')->count();
        if($task['task_class']=="例行监测"){
                $id['id'] = 'LXJC'.date('Y').date('m').date('d').date('H').date('m').str_pad(($count+1),4,0,STR_PAD_LEFT);
        }else{
            $id['id'] = 'ZXJC'.date('Y').date('m').date('d').date('H').date('m').str_pad(($count+1),4,0,STR_PAD_LEFT);

        }
        return $this->jsonSuccessData($id);
    }
    public function setSampleStatus(){
        $data = $this->request->post();
        foreach ($data as $k =>$v) {
            $res = Db::name('cyd')->where('sample_id', $v['sample_id'])->update(['status' => 1]);
        }
        return $this->jsonSuccessData($res);
    }
    public function getTaskDetail(){
        $data=$this->request->post();
        $data['userid']=$this->request->user['unit_id']->getValue();
        $res = Db::name('ccjc')->where('id',$data['task_id'])->find();
        $res['releaserInfo'] = Db::name('jgry')->where('rymc',$res['releaser'])->field('groupname,rymc')->find();
        $res['product']=Db::name('test_model')->field('t_test_product.product_name,t_test_model.type_id')
            ->leftJoin('t_test_product','t_test_model.id=t_test_product.test_model_id')
            ->where('t_test_model.id',$res['test_model_id'])->select();
        $res['pesticides']=Db::name('test_model')->field('t_test_pesticides.test_name,t_test_model.type_id')
            ->leftJoin('t_test_pesticides','t_test_model.id=t_test_pesticides.test_model_id')
            ->where('t_test_model.id',$res['test_model_id'])->select();

        $res['name']=Db::name('undertake')->where([['task_id','=',$data['task_id']],['unit_id','=',$data['userid']]])->select();



        return $this->jsonSuccessData($res);
    }
    public function delSample(){
        $data = $this->request->post();
        foreach ($data as $k =>$v){
            $unit = Db::name('cyd')->where('sample_id',$v['sample_id'])->find();
            $res1=Db::name('units_test')->where('id',$unit['units_id'])->delete();
            $res2=Db::name('production')->where('id',$unit['product_unit'])->delete();
            $res = Db::name('cyd')->where('sample_id',$v['sample_id'])->delete();

        }

        return $this->jsonSuccessData($res);
    }
    public function getSampleDetail(){
        $data=$this->request->post();
        $map=[['t_cyd.sample_id','=',$data['sample_id']]];
        $res = Db::name('cyd')->where($map)->Join('t_production','t_cyd.product_unit=t_production.id')->leftJoin('t_units_test','t_cyd.units_id=t_units_test.id')->find();
        return $this->jsonSuccessData($res);
    }
    public function getTestPesticides(){
        $data=$this->request->post();
        $sample = Db::name('cyd')->where('sample_id',$data['sample_id'])->field('task_id')->find();
        $model = Db::name('ccjc')->where('id',$sample['task_id'])->field('test_model_id')->find();
        $test_model = Db::name('test_pesticides')->where('test_model_id',$model['test_model_id'])->field('test_name,test_id,test_model_id')->select();
        return $this->jsonSuccessData($test_model);
    }
    public function saveSamplePesticides(){
        $data=$this->request->post();
        $id = '';
        $test_result=1;
        $islog = Db::name('sample_pesticides')->where('sample_id',$data['sample_id'])->select();
        if (count($islog)!=0){
            return $this->jsonResponse(-1,'不要重复提交检测信息',$islog);
        }
        foreach ($data['pesticides'] as $k=>$v){
            $v['sample_id']=$data['sample_id'];
            $idv=Db::name('sample_pesticides')->insertGetId($v);
            $id.=$idv.',';
            if ($v['test_result']=='不合格'){
                $test_result=0;
            }
        }
        $res=Db::name('cyd')->where('sample_id',$data['sample_id'])->update(['jc_value_id'=>$id,'test_result'=>$test_result]);
        return $this->jsonSuccessData($res);
    }
    public function editSamplePesticides(){
        $data=$this->request->post();

        foreach ($data as $k=>$v){

            $id=Db::name('sample_pesticides')->where('id',$v['id'])->update($v);

        }
        return $this->jsonSuccessData($id);
    }
    public function getTestValue(){
        $data=$this->request->post();
        $res['result_detail']=Db::name('sample_pesticides')->where('sample_id',$data['sample_id'])->select();
        $res['result']=Db::name('cyd')->where('sample_id',$data['sample_id'])->find();
        return $this->jsonSuccessData($res);
    }
    public function saveTestFile(){
        $data=$this->request->post();
        $data['unit_id']=$this->request->user['unit_id']->getValue();
        $task = Db::name('cyd')->where('sample_id')->find();
        $data['task_id']=$task['task_id'];
        $res = Db::name('jcbg')->strict(false)->insertGetId($data);
        return $this->jsonSuccessData($res);

    }
    public function getUnitsFileList(){
        $data = $this->request->post();
        $pageNum=$data['pageNum'];
        $pageSize=$data['pageSize'];
        $data['unit_id']=$this->request->user['unit_id']->getValue();
        $res['rows'] = Db::name('jcbg')->where('unit_id',$data['unit_id'])->page($pageNum,$pageSize)->select();
        $res['total'] = Db::name('jcbg')->where('unit_id',$data['unit_id'])->count();
        return $this->jsonSuccessData($res);
    }
    public function getGovFileList(){
        $data = $this->request->post();
        $pageNum=$data['pageNum'];
        $pageSize=$data['pageSize'];
//        $data['unit_id']=$this->request->user['unit_id']->getValue();
        $res['rows'] = Db::name('jcbg')->field('t_jcbg.file_name,t_jcbg.file_url,t_ccjc.task_name,t_ccjc.year,t_cyd.sample_name,t_cyd.test_result')->join('t_ccjc','t_jcbg.task_id=t_ccjc.id')->join('t_cyd','t_jcbg.sample_id=t_cyd.id')->page($pageNum,$pageSize)->select();
        $res['total'] = Db::name('jcbg')->count();
        return $this->jsonSuccessData($res);
    }


}