<?php

namespace app\controller;

use app\model\Enterprise as EnterpriseModel;
use think\facade\Filesystem;
use think\Request;

class Enterprise
{
    public function index(Request $request)
    {
        $params = $request->param();
        $page = $params['page'] ?? 1;
        $pageSize = $params['pageSize'] ?? 10;
        
        $where = [];
        if(!empty($params['credit_code']) && isset($params['credit_code'])){
            $where[] = ['credit_code','like','%'.$params['credit_code'].'%'];
        }
        if(!empty($params['name']) && isset($params['name'])){
            $where[] = ['name','like','%'.$params['name'].'%'];
        }

        $query = EnterpriseModel::where($where)->order('id desc');
      

        $list = $query->paginate([
            'list_rows' => $pageSize,
            'page' => $page,
            'query' =>$params
        ]);
        
        return json($list);
    }

    
    public function read($id)
    {
        $result = EnterpriseModel::find($id);
        if(!$result){
            return json(['code' => 1, 'msg' => '数据不存在']);
        }
        
         return json(['msg'=>'','code'=>0,'data'=>$result]);
    }

    public function update(Request $request)
    {
        $params = $request->param();
        
        $info = EnterpriseModel::find($params['id']);
        if(!$info){
            return json(['code' => 1, 'msg' => '数据不存在']);
        }
        unset($params['create_time']);
        $result = $info->save($params);
        
        if($result){
            return json(['msg'=>'更新成功','code'=>0,'data'=>[]]);
        }else{
             return json(['msg'=>'更新失败,请检查~','code'=>1,'data'=>[]]);
        }
    }
    
     public function save(Request $request)
    {
        $params = $request->param();
        
        $result = EnterpriseModel::create([
            'name'=>$params['name'],
            'credit_code'=>$params['credit_code'],
            'username'=>$params['username'],
            'phone'=>$params['phone'],
            'discount'=>$params['discount'],
            'range'=>$params['range'],
            'account'=>$params['account'],
            'marks'=>$params['marks'],
            ]);
        
        if($result){
            return json(['msg'=>'新增成功','code'=>0,'data'=>[]]);
        }else{
             return json(['msg'=>'新增失败,请检查~','code'=>1,'data'=>[]]);
        }
        
    }
    public function delete(Request $request)
    {
        $data = $request->param();
        
        
        if(!EnterpriseModel::find($data['id'])){
            return json(['code' => 1, 'msg' => '数据不存在']);
        }
        $result = EnterpriseModel::destroy($data['id']);
        if ($result) {
            return json(['code' => 0, 'msg' => '删除成功']);
        } else {
            return json(['code' => 1, 'msg' => '删除失败']);
        }
       
    }
}