<?php
/**
 * 营养品管理
 * author:renpengju
 *
 */
namespace app\p\logic;
use app\model\Nutrition as modelNutrition;
use app\model\NutritionSet as modelNutritionSet;
use app\model\NutritionTime as modelNutritionTime;
use app\model\NutritionCategory as modelNutritionCategory;
use think\Db;
use think\Exception;
class Nutrition{

    protected $model;
    protected $articleCateModel;
    protected $modelNutritionTime;
    protected $modelNutritionCategory;
    public function __construct() {
        $this->model = new modelNutrition();
        $this->modelSet = new modelNutritionSet();
        $this->modelNutritionTime = new modelNutritionTime();
        $this->modelNutritionCategory = new modelNutritionCategory();
    }


    
    /**
     * 添加文营养品
     * @return array
     */
    public function add($params) {
        try{
            $params['uuid']  = guid();
            $set = $this->modelSet->where(['uuid'=>$params['set_uuid']])->find();
            if (!$set) {
                throw new Exception('营养品分类不存在');
            }
            if (!empty($params['nutrition_category_uuid'])){
                $category = $this->modelNutritionCategory->read($params['nutrition_category_uuid']);
                if (empty($category)){
                    throw new Exception('营养品展示分类不存在');
                }
            }
            $params['create_time'] = date('Y-m-d H:i:s');
            //查找供货商是否为”康比特“相关
            $is_exist = strpos($params['supplier'],'康比特');
            $params['is_own'] = $is_exist === false ? 0 : 1;
            $params = \app\common\service\NutritionPlainFloatWeight::forModel($params, $this->model);
            $res = $this->model->add(\app\common\service\NutritionFloat82Write::forModel($params, 'nutrition', $this->model));
            if (!$res) {
                throw new Exception('添加营养品失败');
            }
            $resSet = $this->updateSetNum($params['uuid']);
            if ($resSet['code'] == 1) {
                throw new Exception($resSet['message']);
            }
            $res_number = Db::name('nutrition_category')->where(['uuid'=>$params['nutrition_category_uuid']])->setInc('number');
            if (!$res_number){
                throw new Exception('添加营养品失败');
            }
        } catch (Exception $e) {
            return ['code' => 1, 'message' => $e->getMessage(), 'data' =>[]];
        }
        return ['code' => 0, 'message' => '添加营养品成功', 'data' =>[]];
    }

    /**
     *  获取营养品列表
     * @return array
     */
    public function lists($where, $page, $pageSize, $orderBy, $field) {
        $data['total'] = $this->model->inquiryCount($where);
        if(isset($where['name|synopsis'])){
            $where['a.name|synopsis'] = $where['name|synopsis'];
            unset($where['name|synopsis']);
        }
        if(isset($where['status'])){
            $where['a.status'] = $where['status'];
            unset($where['status']);
        }
        $where['a.is_del'] = 1;
        unset($where['is_del']);
        $nutrition = $this->model->inquiryNutrition($where, $page, $pageSize, $orderBy, $field);
//        $use_time_word = \think\Config::get("use_time");
        //将use_time的id转换为文字
//        $use_time_word_arr = array();
//        foreach ($use_time_word as $value){
//            $use_time_word_arr[$value['id']] = $value['item'];
//        }
//        foreach ($nutrition as &$value){
//            $use_time_id_arr = explode(',',$value['use_time']);
//            $use_time = array();
//            foreach ($use_time_id_arr as $use_time_id){
//                if(isset($use_time_word_arr['$use_time_id'])){
//                    $use_time[] = $use_time_word_arr['$use_time_id'];
//                }
//            }
//            $value['use_time'] = $use_time;
//        }
        if (!empty($nutrition)) {
            foreach ($nutrition as $key => $value) {
                if ($field === ['a.*','b.name as set_name']) {
                    $value = \app\common\service\NutritionPlainFloatWeight::physicalForModel($value, $this->model);
                }
                $nutrition[$key] = $this->normalizeDictionaryCreateTime($value);
                $nutrition[$key]['img_path'] = getImgFullPath($value['img_path']);
                $nutrition[$key]['source_img_path'] = getImgFullPath($value['source_img_path']);
                $nutrition[$key]['app_img'] = getImgFullPath($value['app_img']);
            }
        }
        $data['rows'] = $nutrition;
        $data['nutrition_sum'] = $this->model->inquiryCount(['is_del'=>1]);
        return ['code' => 0, 'message' => '获取成功', 'data' =>$data];
    }

    /**
     * 读取营养品
     * @param type $uuid
     * @return type
     */
    public function info($uuid) {
        $nutrition = $this->model->read($uuid);
        if (is_array($nutrition)) {
            $nutrition = \app\common\service\NutritionFloat82Write::physicalForModel($nutrition, 'nutrition', $this->model);
            $nutrition = \app\common\service\NutritionPlainFloatWeight::physicalForModel($nutrition, $this->model);
            $nutrition = $this->normalizeDictionaryCreateTime($nutrition);
        }
        if($nutrition['employ'] == 0){
            $nutrition['employ'] = '';
        }
        $nutrition['nutrition_category_name'] = '';
        if (!empty($nutrition['nutrition_category_uuid'])){
            $category_name = $this->modelNutritionCategory->inquiryColumn(['uuid'=>$nutrition['nutrition_category_uuid']],'name');
            $nutrition['nutrition_category_name'] = implode(',',$category_name);
        }
        if(!$nutrition){
            return ['code' => 1, 'message' => '获取失败', 'data' =>''];
        }
        $nutrition['specifications'] = $nutrition['specifications'] ? $nutrition['specifications'] : '';
        $nutrition['img_path'] = getImgFullPath($nutrition['img_path']);
        $nutrition['app_img'] = getImgFullPath($nutrition['app_img']);
        return ['code' => 0, 'message' => '获取成功', 'data' =>$nutrition];
    }

    /**
     *  编辑
     * @return array
     */
    public function update($params) {
       try{
           $uuid = $params['uuid'];
           unset($params['uuid']);
           $nutrition = $this->model->read($uuid);
           if (!$nutrition) {
               throw  new Exception('参数未查询出数据');
           }
           //查找供货商是否为”康比特“相关
           $is_exist = strpos($params['supplier'],'康比特');
           $params['is_own'] = $is_exist === false ? 0 : 1;
           $params = \app\common\service\NutritionPlainFloatWeight::forModel($params, $this->model);
           $res = $this->model->modify($uuid, \app\common\service\NutritionFloat82Write::forModel($params, 'nutrition', $this->model));
           if ($res === false) {
               throw  new Exception('修改失败');
           }
           //营养品的分类更改
           if($nutrition['set_uuid'] != $params['set_uuid']){
               //更新原来旧分类的数据
               $resSet = $this->updateSetNum(null,$nutrition['set_uuid']);
               if ($resSet['code'] == 1) {
                   throw new Exception($resSet['message']);
               }
               //更新新分类的数据
               $resSet = $this->updateSetNum($uuid);
               if ($resSet['code'] == 1) {
                   throw new Exception($resSet['message']);
               }
           }
           if($nutrition['nutrition_category_uuid'] != $params['nutrition_category_uuid']){
               //更新原来旧分类的数据
               $resSet = $this->updateSetNum(null,null,$nutrition['nutrition_category_uuid']);
               if ($resSet['code'] == 1) {
                   throw new Exception($resSet['message']);
               }
               //更新新分类的数据
               $resSet = $this->updateSetNum($uuid);
               if ($resSet['code'] == 1) {
                   throw new Exception($resSet['message']);
               }
           }
       } catch (Exception $e) {
           return ['code' => 1, 'message' => $e->getMessage(), 'data' =>[]];
       }
       return ['code' => 0, 'message' => '修改成功', 'data' =>[]];
    }

    /**
     * 隐藏/显示
     * @return array
     */
    public function able($uuid, $status) {
        try{
            $article = $this->model->read($uuid);
            if(!$article) {
                throw new Exception("营养品不存在");
            }
            $ret = $this->model->modify($uuid, ['status'=>$status]);
            if (!$ret) {
                throw new Exception("状态修改失败");
            }
        }catch(Exception $e) {
            return ['code'=>1, 'message'=>$e->getMessage(), 'data'=>[]];
        }
        return ['code'=>0, 'message'=>'状态修改成功', 'data'=>[]];
    }

    /**
     *  删除
     * @return array
     */
    public function delete($uuid) {
       $del_arr = explode(',', $uuid);
       $data = $this->model->delMore($del_arr);
       if (!$data){
          return ['code' => 1, 'message' => '删除失败', 'data' =>[]];
       }
        $resSet = $this->updateSetNum($uuid);
        if ($resSet['code'] == 1) {
            throw new Exception($resSet['message']);
        }
       return ['code' => 0, 'message' => '删除成功', 'data' =>$data];
    }

    /**
     *  获取文章
     * $param key_name
     * @return array
     */
    public function listSet($where, $page, $pageSize, $orderBy, $field) {
//        $nutritionSet = $this->modelSet->inquiry($where, $page, $pageSize, $orderBy, $field);
        $nutritionSet = $this->modelSet->field($field)->where($where)->order($orderBy)->page($page, $pageSize)->select()->toArray();
        //使用时间汉字查询
        $use_time_arr = $this->modelNutritionTime->inquiryColumn([],['uuid','name']);
        foreach ($nutritionSet as &$value){
            $value = $this->normalizeDictionaryCreateTime($value);
            $flag = 1;
            $wheres['is_del'] = 1;
            $wheres['set_uuid'] = $value['uuid'];
            $is_exist = Db::name('nutrition')
                ->where($wheres)
                ->count();
            if($is_exist){
                $flag = 0;
            }
            $value['delete_able'] = $flag;
            $take_time = '';
            if($value['use_time']){
                foreach (explode(',',$value['use_time']) as $use_time_uuid){
                    if(isset($use_time_arr[$use_time_uuid])){
                        if($take_time){
                            $take_time = $take_time . ',' . $use_time_arr[$use_time_uuid];
                        }else{
                            $take_time = $use_time_arr[$use_time_uuid];
                        }
                    }
                }
            }
            $value['take_time'] = $take_time;
        }
        $data['rows'] = $nutritionSet;
        $data['total'] = $this->modelSet->alias("a")->where($where)->count();
        return ['code' => 0, 'message' => '获取成功', 'data' =>$data];
    }

    /**
     *  获取
     * @param type_id
     * $param key_name
     * @return array
     */
    public function listsALL($where,$orderBy, $field) {
//        $data= $this->modelSet->inquiryAll($where, $orderBy, $field);
        $data = $this->modelSet->inquiryAllCount($where, $orderBy, $field);
        return ['code' => 0, 'message' => '获取成功', 'data' =>$data];
    }

    /**
     *  获取文章
     * @param type_id
     * $param key_name
     * @return array
     */
    public function listsAllSet($where,$orderBy, $field) {
        $data = $this->modelSet->inquiryAll($where, $orderBy, $field);
        return $data;
    }

    /**
     *  获取
     * $param key_name
     * @return array
     */
    public function supplierList($where) {

        $data = $this->model->where($where)
            ->group('supplier')
            ->field(['supplier'])
            ->select();
        $res = array();
        $else = 0;
        foreach ($data as $k => $value) {
            if($value['supplier']){
                $where_supplier = $where;
                $where_supplier['supplier'] = $value['supplier'];
                $number = $this->model->where($where_supplier)->count();
                $res[] = ['name'=>$value['supplier'],'number'=>$number];
            }else{
                $else = 1;
            }
        }
        if($else){
            $where['supplier'] = ['exp',Db::raw('IS NULL OR supplier= " " ')];
            $number =  $this->model
                ->where($where)
                ->count();
            $res[] = ['name'=>'其他','number'=>$number];
        }
        return ['code' => 0, 'message' => '获取成功', 'data' =>$res];
    }

    /**
     *  添加营养品分类
     * @return array
     */
    public function addSet($params) {
        try{
            $params['uuid']  = guid();
            $title = $this->modelSet->where(['name'=>$params['name'],'is_del'=>1])->find();
            if ($title) {
                throw new Exception('营养品分类已存在');
            }
            $params['create_time'] = date('Y-m-d H:i:s');
            $res = $this->modelSet->add($params);
            if (!$res) {
                throw new Exception('添加营养品分类');
            }
        } catch (Exception $e) {
            return ['code' => 1, 'message' => $e->getMessage(), 'data' =>[]];
        }
        return ['code' => 0, 'message' => '添加营养品分类成功', 'data' =>[]];
    }

    /**
     * 读取文章
     * @param type $uuid
     * @return type
     */
    public function infoSet($uuid) {
        $article = $this->modelSet->read($uuid);
        if (is_array($article)) {
            $article = $this->normalizeDictionaryCreateTime($article);
        }
        return ['code' => 0, 'message' => '获取成功', 'data' =>$article];
    }

    /**
     *  编辑营养品分类
     * @return array
     */
    public function updateSet($params) {
        try{
            $uuid = $params['uuid'];
            unset($params['uuid']);
            $nutrition = $this->modelSet->read($uuid);
            if (!$nutrition) {
                throw  new Exception('不存在该分类');
            }
            $where['name'] = $params['name'];
            $where['uuid'] = ['neq',$uuid];
            $where['is_del'] = 1;
            $title = $this->modelSet->where($where)->find();
            if ($title) {
                throw new Exception('营养品分类已存在');
            }
            $res = $this->modelSet->modify($uuid, $params);
            if ($res === false) {
                throw  new Exception('修改失败');
            }
        } catch (Exception $e) {
            return ['code' => 1, 'message' => $e->getMessage(), 'data' =>[]];
        }
        return ['code' => 0, 'message' => '修改成功', 'data' =>[]];
    }

    /**
     * 隐藏/显示
     * @return array
     */
    public function ableSet($uuid, $status) {
        try{
            $nutrition = $this->modelSet->read($uuid);
            if(!$nutrition) {
                throw new Exception("分类不存在");
            }
//            $where['is_del'] = 1;
//            $where['set_uuid'] = $uuid;
//            $is_exist = Db::name('nutrition')
//                ->where($where)
//                ->count();
//            if($is_exist){
//                throw new Exception("此分类已被应用，不能改变状态");
//            }
            if (ltrim((string)config('database.type'), '\\') === \app\cores\database\Dm::class
                && in_array($status, [0, 1, '0', '1'], true)) {
                $ret = $this->modelSet->modifyByWhere(
                    ['uuid' => $uuid, 'status' => ['<>', $status]],
                    ['status' => $status]
                );
            } else {
                $ret = $this->modelSet->modify($uuid, ['status'=>$status]);
            }
            if (!$ret) {
                throw new Exception("修改失败");
            }
        }catch(Exception $e) {
            return ['code'=>1, 'message'=>$e->getMessage(), 'data'=>[]];
        }
        return ['code'=>0, 'message'=>'修改成功', 'data'=>[]];
    }

    /**
     *  删除
     * @return array
     */
    public function deleteSet($uuid) {
        try{
            $del_arr = explode(',', $uuid);
            //判断分类下有无关联营养品
            foreach ($del_arr as $key => $set_uuid){
                $is_used = $this->model->inquiryCount(['set_uuid'=>$set_uuid,'is_del'=>1]);
                if($is_used){
                    $set_name = $this->modelSet->inquiryColumn(['uuid'=>$set_uuid],['name']);
                    $set_name = isset($set_name[0]) ? $set_name[0] : $set_name;
                    throw new Exception($set_name . "分类下包含营养品，不能删除");
                }
            }
            $data = $this->modelSet->delMore($del_arr);
            if (!$data){
                return ['code' => 1, 'message' => '删除失败', 'data' =>[]];
            }
        }catch(Exception $e) {
            return ['code'=>1, 'message'=>$e->getMessage(), 'data'=>[]];
        }
        return ['code'=>0, 'message'=>'删除成功', 'data'=>[]];
    }

    /**
     *  编辑营养品分类
     * @return array
     */
    public function updateSetNum($uuid_str=null,$set_uuid_str=null,$category_uuid_str=null) {
        try{
            DB::startTrans();
            if($uuid_str){
                $where['uuid'] = ['in',$uuid_str];
                $get_set_uuid = $this->model->inquiryAll($where,[],'set_uuid,nutrition_category_uuid');
                if(!is_array($get_set_uuid)){
                    throw new Exception("此营养品不属于任何分类");
                }
                $set_uuids = array_column($get_set_uuid,'set_uuid');
                $category_uuids = array_column($get_set_uuid,'nutrition_category_uuid');
                $set_uuid_str = implode(',',$set_uuids);
                $category_uuid_str = implode(',',$category_uuids);
            }
            if($set_uuid_str){
                $set_uuid_arr = explode(',',$set_uuid_str);
                foreach ($set_uuid_arr as $set_uuid){
                    $nutritionNum = $this->model->inquiryCount(['set_uuid'=>$set_uuid,'is_del'=>1]);
                    $data['number'] = $nutritionNum;
                    $setRes = $this->modelSet->modifyByWhere(['uuid'=>$set_uuid],$data);
                    if($setRes === false){
                        throw new Exception("分类涉及营养品数更新失败");
                    }
                }
            }
            if(!empty($category_uuid_str)){
                $category_uuid_arr = explode(',',$category_uuid_str);
                foreach ($category_uuid_arr as $category_uuid){
                    $nutritionNum = $this->model->inquiryCount(['nutrition_category_uuid'=>$category_uuid,'is_del'=>1]);
                    $data['number'] = $nutritionNum;
                    $setRes = $this->modelNutritionCategory->modifyByWhere(['uuid'=>$category_uuid],$data);
                    if($setRes === false){
                        throw new Exception("展示分类涉及营养品数更新失败");
                    }
                }
            }
            DB::commit();
        } catch (Exception $e) {
            DB::rollback();
            return  $res = ['code'=>1, 'message'=>$e->getMessage(), 'data'=>[]];
        }
        return $res = ['code'=>0, 'message'=>'', 'data'=> ''];
    }

    private function normalizeDictionaryCreateTime(array $row): array
    {
        if (ltrim((string)config('database.type'), '\\') !== \app\cores\database\Dm::class) {
            return $row;
        }
        $value = $row['create_time'] ?? null;
        if (is_string($value)
            && preg_match('/^((\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2}))\.0{1,6}$/D', $value, $match)
            && (int)$match[2] >= 1000 && checkdate((int)$match[3], (int)$match[4], (int)$match[2])
            && (int)$match[5] <= 23 && (int)$match[6] <= 59 && (int)$match[7] <= 59) {
            $row['create_time'] = $match[1];
        }
        return $row;
    }


}
