<?php
/**
 * Created by PhpStorm.
 * User: xiaofeng
 * Date: 2018/3/12
 * Time: 上午9:57
 * 同步资讯
 */

namespace backend\server;

use Imagine\Image\ManipulatorInterface;
use yii\imagine\Image;
use common\models\CategoryWatermark;
use Yii;
use common\models\News;
use linslin\yii2\curl;

class SyncNews
{
    public $type = null;

    public function NewsList($input)
    {
        if (!empty($input['site']) && is_array($input['site'])) {
            $rows = News::find()->andWhere(['pfg_news.id' => $input['id']])
                ->select(['pfg_house.name as h_name', 'pfg_category_news.news_name', 'pfg_category_city.city_name', 'pfg_news.*'])
                ->leftJoin('pfg_house', 'pfg_news.hid = pfg_house.id')
                ->leftJoin('pfg_category_news', 'pfg_news.category = pfg_category_news.id')
                ->leftJoin('pfg_category_city', 'pfg_news.city = pfg_category_city.id')
                ->asArray()
                ->all();

            if ($rows) {
                foreach ($rows as &$val) {
                    if (!empty($val['thumb'])) {
                        $val['thumb'] = json_decode($val['thumb'], true);
                    }
                }

            }

            $curl = new curl\Curl();

            foreach ($input['site'] as $v) {
                $response = $curl->setPostParams([
                    'data' => $rows,
                    'url' => Yii::$app->params['httpImg']['host'] . Yii::$app->params['httpImg']['newsthumb'],
                    'source' => '11111'
                ])->post($v);
            }
            return $response;
        }
    }

    //资讯同步接收
    public function newsOpe($input)
    {
        $this->type = $input['type'];
        $oss_url = $input['url'];//资讯缩略图url
        $data = $input['data'];//资讯信息
        try {
            $Transaction = Yii::$app->db->beginTransaction();
            $arr = [];
            $arr['subject'] = $data['subject'];
            $arr['thumb'] = $this->PullImg(json_decode($data['thumb'], true), $oss_url);
//            $arr['thumb'] = $data['thumb'];
            $arr['abstract'] = $data['abstract'];
            $arr['author'] = $data['author'];
            if(trim($data['source']) == '同步站'){
                $arr['source'] = '易购房';
            }else{
                $arr['source'] = $data['source'];
            }
            $arr['sort'] = $data['sort'];
            $arr['clicks'] = $data['clicks'];
            $arr['state'] = $data['state'];
            if (isset($data['city_name']) && !empty($data['city_name'])) {
                $arr['city'] = $this->CityColumn($data['city_name'], $data['level']);
            }
            if ((isset($data['house_name']) || isset($data['unid'])) && !empty($data['house_name'])) {
                $arr['hid'] = $this->HouseColumn($data['house_name'], $data['unid']);
            }
            $arr['category'] = $this->NewsColumn($data['news_category']);
            $arr['content'] = $data['content'];
            $arr['del'] = $data['del'];
            $arr['create_at'] = $_SERVER['REQUEST_TIME'];
            $arr['update_at'] = $_SERVER['REQUEST_TIME'];
            $arr['open_time'] = $data['open_time'];
            $arr['thumb_size'] = $data['thumb_size'];
            $arr['short_subject'] = $data['short_subject'];
            $arr['true_click'] = $data['true_click'];
            $newsInfo = $this->exetNews($data);
            if($this->type == 1){
                $news = 'pfg_news';
            }elseif($this->type == 2){
//                $news = 'pfg_news';
            }
            if ($newsInfo) {
                //资讯存在
                $row = Yii::$app->db->createCommand()->update($news, $arr, 'id = ' . $newsInfo['id'])->execute();
                $thisid = $newsInfo['id'];
                $code = 'edit';
            } else {
                //资讯不存在
                $row = Yii::$app->db->createCommand()->insert($news, $arr)->execute();
                $thisid = Yii::$app->db->getLastInsertID();
                $code = 'add';
            }
            if ($row > 0) {
                $syncInfo = [];
                $syncInfo['this_content'] = json_encode($newsInfo);//原数据
                $syncInfo['content'] = json_encode($arr);//同步数据
                $syncInfo['audit_name'] = $input['auditor_name'];//审核人
                $syncInfo['unid'] = $data['unid'];
                $syncInfo['own_newsid'] = $thisid;
                $syncInfo['type'] = $this->type;
                $syncInfo['code'] = $code;
                $sync = Yii::$app->db->createCommand()->insert('pfg_syncnewsrecord', $syncInfo)->execute();
                if ($sync > 0) {
                    $Transaction->commit();
                    return true;
                } else {
                    $Transaction->rollBack();
                    return '添加记录表失败';
                }
            } else {
                $Transaction->rollBack();
                return '插入/修改信息失败(可能已存在完全相同的资讯信息)';
            }
        } catch (\Exception $e) {
            return $e->getMessage();
        }
    }

    /*
     *检测资讯是否存在
     * */
    public function exetnews($data)
    {
        if($this->type == 1){
            $state = \common\models\Syncnewsrecord::find()->andWhere(['unid' => $data['unid']])->one();
            if(!empty($state)){
                return \common\models\News::find()->andWhere(['id' => $state['own_newsid']])->asArray()->one();
            }
            return \common\models\News::find()->andWhere(['subject' => $data['subject']])->one();
        }elseif($this->type == 2){

        }
    }

    /*
     * 转换资讯栏目
     */
    private function NewsColumn($name)
    {
        if($this->type == 1){
            $model = \common\models\CategoryNews::find()->andWhere(['news_name' => $name])->andWhere(['del' => 1])->one();
            if ($model) {
                return $model['id'];
            } else {
                $rows = new \common\models\CategoryNews();
                $rows->news_name = $name;
                if ($rows->save()) {
                    return $rows->attributes['id'];
                }
            }
        }elseif($this->type == 2){

        }
        throw new \Exception('未检测到资讯栏目:' . $name);
    }

    /*
     * 转换区域ID
     */
    public function CityColumn($city, $level = 1)
    {
        if (!empty($city)) {
            if($this->type == 1){
                $row = \common\models\CategoryCity::find()->andFilterWhere(['like','city_name',$city])->andWhere([ 'del' => 1, 'level' => $level])->one();
                if ($row) {
                    return $row['id'];
                }
            }elseif($this->type ==2){

            }
            throw new \Exception('未检测到区域:' . $city);
        }
    }


    /*
 * 转换楼盘ID
 */
    public function HouseColumn($hname, $unid)
    {
        if($this->type == 1){
            if (!empty($hname)) {
                $row = \common\models\House::find()->andWhere(['name' => $hname, 'del' => 1])->one();
                if ($row) {
                    return $row['id'];
                }
            }
            if (!empty($unid)) {
                $row = \common\models\Synchouserecord::find()->andWhere(['unid' => $unid])->one();
                if ($row) {
                    return $row['own_hid'];
                }
            }
        }elseif($this->type == 2){

        }
        throw new \Exception('未检测到楼盘信息:' . $hname);
    }

    /*
     * 拉取图片
     */
    private function PullImg($img, $oos)
    {
        if (is_array($img) && !empty($img)) {
            foreach ($img as $val) {
                $curl = new curl\Curl();
                $resultImg = $curl->get($oos . $val);
                $imgUrl = Yii::$app->params['img_url']['news'];
                if (!is_file($imgUrl . $val)) {
                    if (!file_put_contents($imgUrl . $val, $resultImg)) {
                        throw new \Exception('图片添加失败,请联系管理员');
                    }
                }
            }
            return json_encode(array_values($img));
        }

    }

}