<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\adminapi\logic\land;


use app\common\logic\BaseLogic;
use app\common\model\land\LandPlant;
use app\common\model\action\Action;
use app\common\model\land\Land;
use app\common\model\plant\Plant;
use think\facade\Db;


/**
 * LandPlant逻辑
 * Class LandPlantLogic
 * @package app\adminapi\logic\land
 */
class LandPlantLogic extends BaseLogic
{

    /**
     * @notes 添加
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2023/11/23 11:32
     */
    public static function add(array $params): bool
    {
        $userId = Db::name('land')->where('id', $params['land_id'])->value('user_id');
        Db::startTrans();
        try {
            LandPlant::create([
                'user_id' => $userId,
                'land_id' => $params['land_id'],
                'kind' => $params['kind'],
                'breed' => $params['breed'],
                'area' => $params['area'],
                'user' => $params['user'],
                'remark' => $params['remark'],
                'status' => $params['status'],
                'qr_code' => $params['qr_code'],
                'plant_date' => strtotime($params['plant_date']),
            ]);

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * @notes 编辑
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2023/11/23 11:32
     */
    public static function edit(array $params): bool
    {
        $landPlant = LandPlant::findOrEmpty($params['id'])->toArray();
        $land = Land::findOrEmpty($landPlant['land_id'])->toArray();
        $userId =  $land['user_id'];
        $newArea = $land['residual_area'] + ($landPlant['area'] - $params['area']); 
        Db::startTrans();
        try {
            LandPlant::where('id', $params['id'])->update([
                'user_id' => $userId,
                'land_id' => $params['land_id'],
                'kind' => $params['kind'],
                'breed' => $params['breed'],
                'area' => $params['area'],
                'user' => $params['user'],
                'remark' => $params['remark'],
                'status' => $params['status'],
                'qr_code' => $params['qr_code'],
                'plant_date' => strtotime($params['plant_date']),
            ]);
            Land::where('id', $landPlant['land_id'])->update(['residual_area'=>$newArea]);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * @notes 删除
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2023/11/23 11:32
     */
    public static function delete(array $params): bool
    {
        $landPlant = LandPlant::findOrEmpty($params['id'])->toArray();    
        Land::where('id', $landPlant['land_id'])->inc('residual_area', $landPlant['area'])->update();
        Db::name('land_plant_action')->where('plant_id', $params['id'])->delete();
        return LandPlant::destroy($params['id']);
    }


    /**
     * @notes 获取详情
     * @param $params
     * @return array
     * @author likeadmin
     * @date 2023/11/23 11:32
     */
    public static function detail($params): array
    {
        return LandPlant::findOrEmpty($params['id'])->toArray();
    }

    public static function suyuan($params): array|bool
    {
		if(empty($params['id'])){
            self::setError('参数错误');
            return false;
		}
		$plantInfo = Plant::where('id',$params['id'])->findOrEmpty();
		if($plantInfo->isEmpty()){
            self::setError('种植信息错误');
            return false;
		}
		if($plantInfo['status'] != 2){
            self::setError('种植信息状态错误');
            return false;
		}
		$landInfo = Land::where('id',$plantInfo['land_id'])->findOrEmpty();
		if($landInfo->isEmpty()){
            self::setError('土地信息错误');
            return false;
		}
		$plantInfo['pic'] = json_decode($plantInfo['pic'],true);
        $plantInfo['group_day'] = floor(($plantInfo['harvest_date'] - $plantInfo['plant_date']) / 86400);
		$plantInfo['plant_date'] = date('Y-m-d',$plantInfo['plant_date']);
        $plantInfo['harvest_date'] = date('Y-m-d',$plantInfo['harvest_date']);
		$plantInfo['land_name'] = $landInfo['title'];
		$plantInfo['land_area'] = $landInfo['total_area'];
		$plantInfo['land_address'] = $landInfo['province_name'].$landInfo['city_name'].$landInfo['county_name'].$landInfo['town_name'].$landInfo['village_name'].$landInfo['group_name'];
		//获取操作
		$action = Action::field('type,type_text,detail,create_time')->where('plant_id',$params['id'])->select()->each(function($item){
			$item['detail'] = json_decode($item['detail'],true);
			return $item;
		})->toArray();
		$plantInfo['actions'] = $action;
		return $plantInfo->toArray();
    }
}