<?php

/**
 * +----------------------------------------------------------------------
 * | Created By PhpStorm
 * +----------------------------------------------------------------------
 * | DATE: 2021/7/24
 * +----------------------------------------------------------------------
 * | TIME: 15:02
 * +----------------------------------------------------------------------
 * | Author: YangXing(925032253@qq.com)
 * +----------------------------------------------------------------------
 * | Class: photo
 * +----------------------------------------------------------------------
 */

namespace model\sample;


class photo extends \model\sample\sample
{

    /**
     * @param $id
     * @return array
     */
    public function photoList($id)
    {
        $data = $this->getRowByKey($id);
        $data = !empty($data['s_photos']) ? json_decode($data['s_photos'], true) : [];
        if ($data) {
            $file = new \model\file();
            foreach ($data as $key => $row) {
                $pinfo = pathinfo($row['filename']);
                $data[$key]['fileremark'] = '';
                if ($pinfo['extension'] == 'pdf') {
                    $fRow = $file->getRowByKey($row['fileid']);
                    $data[$key]['fileremark'] = $fRow['fileremark'];
                }
            }
        }
        return $data;
    }

    /**
     * @param $id
     * @param $data
     */
    public function save($id,$data)
    {
        $this->setValue($id,'s_photos',$data);
    }

    /**
     * @param $id
     * @param $photoList
     * @return false|\PDOStatement
     */
    public function delete($sId,$fileid)
    {
        $temp = $this->db->get($this->table,'s_photos',['s_id' => $sId]);
        if(!empty($temp)){
            $temp = json_decode($temp,true);
            foreach ($temp as $k => $v)
            {
                if($v['fileid']==$fileid) unset($temp[$k]);
            }
        }
		make(\model\files::class)->delete($fileid);
        return $this->db->update($this->table,['s_photos' => is_array($temp) && !empty($temp) ? json_encode($temp) : ''],['s_id' => $sId]);
    }

    /**
     * @param $sId
     * @param $name
     * @return false|\PDOStatement
     */
    public function  setFileValue($sId,$name)
    {
        $temp = $this->db->get($this->table,'s_photos',['s_id' => $sId]);
        if(!empty($temp)){
            $temp = json_decode($temp,true);
            array_push($temp,$name);
            $temp = json_encode($temp);
        }else{
            $temp = json_encode([$name]);
        }
        return $this->db->update($this->table,['s_photos' => $temp],['s_id' => $sId]);
    }


    public function findInSet()
    {
        $data = $this->db->get('sample', '*', [
            's_id' => 2,
            's_photos' => \three\medoo::raw('find_in_set(:id,<s_photos>)',[
                ':id' => 1
            ])
        ]);
        var_dump($this->db->last());
        var_dump($data);
    }
}
