<?php
/**
 *
 *User:Administrator
 *Date:2021/10/11
 */

namespace app\api\business;

use app\api\exception\ApiException;
use app\api\model\Ccjc;
use app\api\model\Pesticides;
use app\api\model\ProductClass;
use app\api\model\TestModel;
use app\api\model\TestPesticides;
use app\api\model\TestProduct;
use app\common\lib\Arr;
use app\common\lib\auth\JwtAuth;

class ModelBus
{
    private $uid;
    public function __construct()
    {
        $jwtAuth = JwtAuth::getInstance();
        $this->uid = $jwtAuth->getUid();
    }

    //获取当前用户的模型页列表
    public function selectModelList($data)
    {
        $pageNum = $data['pageNum'];
        $pageSize = $data['pageSize'];
        $type_id = $data['type_id'];//1.种植业 2.畜牧业 3.渔业 4.其他

        $where = [];
        if (!empty($type_id)) {
            array_push($where, ['type_id', '=', (int)$type_id]);
        }
        $result = (new TestModel())->getListByUserId($this->uid,$pageNum,$pageSize,$where)->toArray();
        $count = (new TestModel())->countListByUserId($this->uid, $where);
        return ['rows'=>$result, 'total' => $count,];
    }

    //获取模型信息
    public function getModelInfoByModelId($tmp_data)
    {
        $model_id = $tmp_data['id'];
        $model_info=(new TestModel())->getModelInfoByModelID($model_id);//获取模型信息
        $model_product=(new TestModel())->getProductInfo($model_id)->toArray();//检测对象
        $model_pesticides = (new TestModel())->getPesticidesInfo($model_id)->toArray();//检测项
        $data=[
            'name'=>$model_info,
            'product'=>$model_product,
            'pesticides'=>$model_pesticides
        ];
        return $data;
    }

    //获取模型信息
    public function getModelInfoByTaskId($data)
    {
        $task_id = $data['task_id'];

        $test_model_id['id'] = (new Ccjc())->getTaskInfoByTaskID($task_id)['test_model_id'];
        $model_info = $this->getModelInfoByModelId($test_model_id);
        return $model_info;

    }

    public function updateInfoByTaskID($data)
    {
        $task_id = $data['task_id'];
        $tmp_data = [
            'endtime_cydsb' => $data['endtime_cydsb'],
            'is_divide' => $data['is_divide'],
            'test_model_id' => $data['test_model_id'],
            'industry' => (new TestModel())->getModelInfoByModelID($data['test_model_id'])['type_id'],
        ];
        $result = (new Ccjc())->updateInfoByTaskID($task_id, $tmp_data);
        return $result;
    }



    //修改模型信息
    public function updateModelInfo($model_id,$model_info,$product='',$pesticides='')
    {

        //检测对象如果不为空则存在需要更新的信息，$product_update_Data
        $product_update_data = [];
        if ($product != '') {
            foreach ($product as $k => $value) {
                $product_update_data[$k] = [
                    'test_model_id' => $model_id,
                    'product_id' => $value['id'],
                    'product_name' => $value['name'],
                ];
            }
            //删除原有Product中model_id的内容
            (new TestProduct())->deleteProductInfoByTestModelID($model_id);
            //添加新的Product中model_id的内容
            (new TestProduct())->insertProductInfo($product_update_data);
        }

        //检测项目如果不为空则存在需要更新的信息，$product_update_Data
        $pesticides_update_data = [];
        if ($pesticides != '') {
            foreach ($pesticides as $k => $value) {
                $pesticides_update_data [$k]= [
                    'test_model_id' => $model_id,
                    'test_id' => $value['id'],
                    'test_name' => $value['name'],
                ];
            }
            //删除原有Pesticides中model_id的内容
            (new TestPesticides())->deletePesticidesInfoByTestModelID($model_id);
            //添加新的Pesticides中model_id的内容
            (new TestPesticides())->insertPesticidesInfo($pesticides_update_data);
        }

        //更新model_test表中的信息（model_name和type_id)
        (new TestModel())->updateModelInfoByModelID($model_id,$model_info);

        return true;
    }

    //新增模型
    public function createModelInfo($model_name,$type_id,$product_data,$pesticides_data)
    {
        $uid=$this->uid;
        $model_id = (new TestModel())->createModelInfo($model_name, $type_id, $uid);

        //格式化$product_data=》$product
        $product=[];
        //todo 需要重写foreach
        foreach ($product_data as $k=>$v){
            $j=[];
            $j['test_model_id']=$model_id;
            $j['product_id']=$v['id'];
            $j['product_name']=$v['name'];
            $product[]=$j;
        }
        //格式化$pesticides_data=》$pesticides
        $pesticides=[];
        foreach ($pesticides_data as $i=>$o){
            $p=[];
            $p['test_model_id']=$model_id;
            $p['test_name']=$o['name'];
            $p['test_id']=$o['id'];
            $pesticides[]=$p;
        }
        //todo 写到一个model里
        $update_test_product = (new TestProduct())->createProductInfo($product);
        if ($update_test_product == 0) {
            throw new ApiException(config('status.none_model_product'));
        }
        $update_test_pesticide =(new TestPesticides())->insertPesticidesInfo($pesticides);
        if ($update_test_pesticide == 0) {
            throw new ApiException(config('status.none_model_pesticides'));
        }
        return true;
    }

    //删除模型
    public function deleteModelInfo($data,$data_count)
    {
        for ($i = 0; $i < $data_count; $i++) {
            //从数据库获取当前模型的user_id        //验证模型创建者是否一致
            $user_id = (new TestModel())->getUserIdByModelID($data[$i]['id'])['user_id'];
            //查询模型绑定任务，如果绑定则禁止删除
            $ccjc_info = (new Ccjc())->getTaskInfoByModelId($data[$i]['id']);

            if ( !($ccjc_info==[])) {
                throw new ApiException(config('status.err_disable_delete'));
            }

            if ($user_id != $this->uid) {
                throw new ApiException(config('status.none_authority'));
            }
            //删除test_model信息
            (new TestModel())->deleteModelInfoByID($data[$i]['id']);
            //删除test_product信息
            (new TestProduct())->deleteProductInfoByTestModelID($data[$i]['id']);
            //删除test_pesticides信息
            (new TestPesticides())->deletePesticidesInfoByTestModelID($data[$i]['id']);
        }
        return true;
    }

    //获取检测项目列表
    public function selectPesticidesList($pageNum,$pageSize,$key_word)
    {
        $data = (new Pesticides())->selectPesticidesList($key_word, $pageNum, $pageSize)->toArray();
        $count = (new Pesticides())->countPesticidesList($key_word);
        $result = [
            'rows' => $data,
            'total' => $count,
        ];
        return $result;
    }

    //获取检测对象列表
    public function selectProductList($type_id)
    {

        //todo cache缓存优化数据
        $field='id,parent_id,product_code,name,alias';
        $tmp_result = (new ProductClass())->selectProductListByTypeID($type_id,$field)->toArray();//字段调用的field过滤

        //todo 树状化需要看一下，回调可以优化
        $result = (new Arr())->Arr_tree($tmp_result,'0'.$type_id);
        return $result;
    }

}