<?php
/**
 * Created by PhpStorm.
 * User: ywl
 * Date: 2017/4/14
 * Time: 11:38
 */

namespace App\Web\Services;

use App\Common\Facades\ComSmsFacade;
use App\Common\Facades\UserCenterFacade;
use App\Exceptions\ApiException;
use App\Services\CommonUserBaseService;
use App\Web\Facades\WebFacade;
use App\Web\Models\MeetingModel;
use App\Web\Models\MeetingSpeechScheduleModel;
use App\Web\Models\MeetingTagModel;
use App\Web\Models\MeetingTagRelationModel;
use App\Web\Models\MeetingTypeModel;
use App\Web\Models\MeetingTypeRelationModel;
use Illuminate\Support\Facades\Cache;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;

class MeetingService extends CommonUserBaseService
{
    protected $cache = true;

    protected $cacheBucket = 'Meeting:';

    protected $meetingTypeModel;
    protected $meetingTypeRelationModel;
    protected $meetingTagModel;
    protected $meetingTagRelationModel;
    protected $meetingSpeechScheduleModel;

    /**
     * MeetingService construct
     * @param MeetingModel $model
     * @param MeetingTypeModel $meetingTypeModel
     * @param MeetingTagRelationModel $meetingTagRelationModel
     * @param MeetingTagModel $meetingTagModel
     * @param MeetingTypeRelationModel $meetingTypeRelationModel
     * @param MeetingSpeechScheduleModel $meetingSpeechScheduleModel
     * */
    public function __construct(MeetingModel $model,
                                MeetingTypeModel $meetingTypeModel,
                                MeetingTagRelationModel $meetingTagRelationModel,
                                MeetingTagModel $meetingTagModel,
                                MeetingTypeRelationModel $meetingTypeRelationModel,
                                MeetingSpeechScheduleModel $meetingSpeechScheduleModel
    )
    {
        $this->model = $model;
        $this->meetingTypeModel = $meetingTypeModel;
        $this->meetingTypeRelationModel = $meetingTypeRelationModel;
        $this->meetingTagModel = $meetingTagModel;
        $this->meetingTagRelationModel = $meetingTagRelationModel;
        $this->meetingSpeechScheduleModel = $meetingSpeechScheduleModel;
    }

    /**
     * 获取产品类型列表
     * */
    public function getMeetingTypeList($params)
    {
        $retData = $this->meetingTypeModel->getMeetingTypeList($params);
        if (!empty($retData['data'])) {
            $typeIds = array_column($retData['data'], 'id');
            $meetingCounts = $this->meetingTypeRelationModel->getMeetingTypeCount($typeIds);
            foreach ($retData['data'] as &$meetingItem) {
                $meetingItem['meeting_count'] = $meetingCounts[$meetingItem['id']] ?? 0;
                $meetingItem['expand_content'] = empty($meetingItem['expand_content']) ? [] : json_decode($meetingItem['expand_content'], true);
                $meetingItem['expand_array'] = $this->transformArrayToKeyValue($meetingItem['expand_content']);

            }
        }
        return $retData;
    }

    public function transformArrayToKeyValue($array)
    {
        $result = [];
        foreach ($array as $item) {
            if (isset($item['key']) && isset($item['value'])) {
                $result[$item['key']] = $item['value'];
            }
        }
        return $result;
    }

    /**
     * 产品类型保存
     * */
    public function saveMeetingType($params)
    {
        $saveData = [];
        $nowTime = nowTime();
        $saveData['update_time'] = $nowTime;
        $userId = $this->getAuthUserId();

        if (!empty($params['seo_data'])) {
            $urlaUnique = WebFacade::checkUrlaUnique($params['seo_data']['urla'], $params['seo_id']);
            if (!$urlaUnique) {
                throw new ApiException(10019, ['name' => $params['seo_data']['urla']]);
            }
        }

        if (!empty($params['id'])) {
            $saveData['id'] = $params['id'];
            if (isset($params['type_name'])) {
                $nameUnique = $this->meetingTypeModel->checkTypeNameUnique($params['type_name'], $params['id']);
                if (!$nameUnique) {
                    throw new ApiException(10018, ['name' => $params['type_name']]);
                }
                $saveData['type_name'] = $params['type_name'];
            }
            if (isset($params['status'])) {
                $saveData['status'] = $params['status'];
            }
            if (isset($params['sort'])) {
                $saveData['sort'] = $params['sort'];
            }
            if (isset($params['expand_content'])) {
                $saveData['expand_content'] = !empty($params['expand_content']) ? json_encode($params['expand_content']) : '';
            }
        } else {
            $nameUnique = $this->meetingTypeModel->checkTypeNameUnique($params['type_name']);
            if (!$nameUnique) {
                throw new ApiException(10018, ['name' => $params['type_name']]);
            }
            $saveData['user_id'] = $userId;
            $saveData['type_name'] = $params['type_name'];
            $saveData['expand_content'] = !empty($params['expand_content']) ? json_encode($params['expand_content']) : '';
            $saveData['sort'] = empty($params['sort']) ? 0 : $params['sort'];
            $saveData['create_time'] = $nowTime;
        }
        $id = $this->meetingTypeModel->saveTypeData($saveData);
        if (!empty($id) && isset($params['seo_data'])) {
            $seoParams = [
                'relation_table' => WebService::RELATION_TABLE_MEETING_TYPE,
                'relation_id' => $id,
                'urla' => $params['seo_data']['urla'],
                'seo_title' => $params['seo_data']['seo_title'],
                'seo_keyword' => $params['seo_data']['seo_keyword'],
                'seo_describe' => $params['seo_data']['seo_describe']
            ];

            if (empty($params['seo_id'])) {
                $seoParams['user_id'] = $userId;
                $urlaId = WebFacade::saveSeoData($seoParams);
                $this->meetingTypeModel->newInstance()->where('id', '=', $id)->update(['seo_id' => $urlaId]);
            } else {
                $seoParams['id'] = $params['seo_id'];
                $urlaId = WebFacade::saveSeoData($seoParams);
            }
            if (!empty($saveData['status']) && $saveData['status'] == 2) {
                //移除对应seo
                $delSeoParams = [];
                $delSeoParams['relation_table'] = WebService::RELATION_TABLE_MEETING_TYPE;
                $delSeoParams['relation_id'] = $id;
                $ret = WebFacade::delSeoByRelation($delSeoParams);
            }
        }
        //更新所有页面缓存
        WebFacade::clearPageCache('urla:');
        return $id;
    }

    /**
     * 保存产品类型关系
     * */
    public function typeRelationSave($params)
    {
        $userId = $this->getAuthUserId();
        $ret = $this->meetingTypeRelationModel->typeRelationSave($params, $userId);

        //更新所有页面缓存
        WebFacade::clearPageCache('urla:');
        return $ret;
    }

    /**
     * 根据产品类型 保存产品关系
     * */
    public function addRelationByTypeId($typeId, $meetingIds)
    {
        $userId = $this->getAuthUserId();
        $ret = $this->meetingTypeRelationModel->addByTypeId($typeId, $meetingIds, $userId);

        //更新所有页面缓存
        WebFacade::clearPageCache('urla:');
        return $ret;
    }

    /**
     * 根据类型id及产品id 删除关联关系
     * */
    public function delTypeRelation($typeId, $meetingId)
    {
        $ret = $this->meetingTypeRelationModel->delTypeRelation($typeId, $meetingId);

        //更新所有页面缓存
        WebFacade::clearPageCache('urla:');
        return $ret;
    }

    /**
     * 获取产品标签列表
     * */
    public function getMeetingTagList($params)
    {
        $retData = $this->meetingTagModel->getMeetingTagList($params);
        if (!empty($retData['data'])) {
            $tagIds = array_column($retData['data'], 'id');
            $meetingCounts = $this->meetingTagRelationModel->getMeetingTagCount($tagIds);
            foreach ($retData['data'] as &$meetingItem) {
                $meetingItem['meeting_count'] = $meetingCounts[$meetingItem['id']] ?? 0;
            }
        }
        return $retData;
    }

    /**
     * 产品标签保存
     * */
    public function saveMeetingTag($params)
    {
        $saveData = [];
        $nowTime = nowTime();
        $saveData['update_time'] = $nowTime;
        $userId = $this->getAuthUserId();

//        if (!empty($params['seo_data'])) {
//            $urlaUnique = WebFacade::checkUrlaUnique($params['seo_data']['urla'], $params['seo_id']);
//            if (!$urlaUnique) {
//                throw new ApiException(10019, ['name' => $params['seo_data']['urla']]);
//            }
//        }

        if (!empty($params['id'])) {
            $saveData['id'] = $params['id'];
            if (isset($params['tag_name'])) {
                $nameUnique = $this->meetingTagModel->checkTagNameUnique($params['tag_name'], $params['id']);
                if (!$nameUnique) {
                    throw new ApiException(10018, ['name' => $params['tag_name']]);
                }
                $saveData['tag_name'] = $params['tag_name'];
            }
            if (isset($params['status'])) {
                $saveData['status'] = $params['status'];
            }
            if (isset($params['sort'])) {
                $saveData['sort'] = $params['sort'];
            }
            if (isset($params['is_hot'])) {
                $saveData['is_hot'] = $params['is_hot'];
            }
//            if(isset($params['type'])){
//                $saveData['type']=empty($params['type'])?0:$params['type'];
//            }
        } else {
            $nameUnique = $this->meetingTagModel->checkTagNameUnique($params['tag_name']);
            if (!$nameUnique) {
                throw new ApiException(10018, ['name' => $params['tag_name']]);
            }
            $saveData['user_id'] = $userId;
            $saveData['tag_name'] = $params['tag_name'];
//            $saveData['type']=empty($params['type'])?0:$params['type'];
            $saveData['sort'] = empty($params['sort']) ? 0 : $params['sort'];
            $saveData['create_time'] = $nowTime;
        }
        $id = $this->meetingTagModel->saveTagData($saveData);
//        if (!empty($id) && isset($params['seo_data'])) {
//            $seoParams = [
//                'relation_table' => WebService::RELATION_TABLE_MEETING_TAG,
//                'relation_id' => $id,
//                'urla' => $params['seo_data']['urla'],
//                'seo_title' => $params['seo_data']['seo_title'],
//                'seo_keyword' => $params['seo_data']['seo_keyword'],
//                'seo_describe' => $params['seo_data']['seo_describe']
//            ];
//
//            if (empty($params['seo_id'])) {
//                $seoParams['user_id'] = $userId;
//                $urlaId = WebFacade::saveSeoData($seoParams);
//                $this->meetingTagModel->newInstance()->where('id','=',$id)->update(['seo_id' => $urlaId]);
//            } else {
//                $seoParams['id'] = $params['seo_id'];
//                $urlaId = WebFacade::saveSeoData($seoParams);
//            }
//        }
        return $id;
    }

    /**
     * 保存产品标签关系
     * */
    public function tagRelationSave($params)
    {
        $userId = $this->getAuthUserId();
        $ret = $this->meetingTagRelationModel->tagRelationSave($params, $userId);

        //更新所有页面缓存
        WebFacade::clearPageCache('urla:');
        return $ret;
    }

    /**
     * 根据产品标签 保存产品关系
     * */
    public function addRelationByTagId($tagId, $meetingIds)
    {
        $userId = $this->getAuthUserId();
        $ret = $this->meetingTagRelationModel->addByTagId($tagId, $meetingIds, $userId);

        //更新所有页面缓存
        WebFacade::clearPageCache('urla:');
        return $ret;
    }

    /**
     * 根据标签id及产品id 删除关联关系
     * */
    public function delTagRelation($tagId, $meetingId)
    {
        $ret = $this->meetingTagRelationModel->delTagRelation($tagId, $meetingId);
        //更新所有页面缓存
        WebFacade::clearPageCache('urla:');
        return $ret;
    }

    /**
     * 保存产品数据
     * */
    public function saveMeeting($params)
    {
        $saveData = $this->buildMeetingData($params);
        $userId = $this->getAuthUserId();
        $typeIds = empty($params['type_ids']) ? [] : $params['type_ids'];
        $tagIds = empty($params['tag_ids']) ? [] : $params['tag_ids'];
        $seoData = empty($params['seo_data']) ? [] : $params['seo_data'];
        $urlaId = empty($saveData['seo_id']) ? 0 : $saveData['seo_id'];
        if (!empty($seoData)) {
            $urlaUnique = WebFacade::checkUrlaUnique($seoData['urla'], $urlaId);
            if (!$urlaUnique) {
                throw new ApiException(10019, ['name' => $seoData['urla']]);
            }
        }
        $id = $this->model->saveMeetingData($saveData);
        if (!empty($id)) {
            if (isset($params['seo_data'])) {
                $seoParams = [];
                $seoParams['relation_table'] = WebService::RELATION_TABLE_MEETING;
                $seoParams['relation_id'] = $id;
                $seoParams['urla'] = $seoData['urla'];
                $seoParams['seo_title'] = $seoData['seo_title'];
                $seoParams['seo_keyword'] = $seoData['seo_keyword'];
                $seoParams['seo_describe'] = $seoData['seo_describe'];
                if (empty($urlaId)) {
                    $seoParams['user_id'] = $userId;
                    $urlaId = WebFacade::saveSeoData($seoParams);
                    $this->model->newInstance()->where('id', '=', $id)->update(['seo_id' => $urlaId]);
                } else {
                    $seoParams['id'] = $urlaId;
                    $urlaId = WebFacade::saveSeoData($seoParams);
                }
            }
            if (isset($params['type_ids'])) {
                $meetingTypeParams = [];
                $meetingTypeParams['meeting_id'] = $id;
                $meetingTypeParams['type_ids'] = $typeIds;
                $this->meetingTypeRelationModel->typeRelationSave($meetingTypeParams, $userId);
            }
            if (isset($params['tag_ids'])) {
                $meetingTagParams = [];
                $meetingTagParams['meeting_id'] = $id;
                $meetingTagParams['tag_ids'] = $tagIds;
                $this->meetingTagRelationModel->tagRelationSave($meetingTagParams, $userId);
            }
            // 获取是否需要修改排序数据
            if (isset($saveData['sort'])) {
                $getData = $this->model->selectRaw('id')
                    ->where('sort', '=', $saveData['sort'])
                    ->where('id', '<>', $id)->first();
                if (!empty($getData['id'])) {
                    $this->model->where('sort', '>=', $saveData['sort'])
                        ->where('id', '<>', $id)
                        ->update(['sort' => DB::raw('sort + 1')]);
                }
            }
            if (!empty($params['id']) && !empty($params['virtual_view'])) {
                $this->updatePv($params['id'], $params['virtual_view']);
            }
            if (isset($params['speech_schedule'])) {
                $this->meetingSpeechScheduleModel->saveSpeechScheduleData($id, $params['speech_schedule'], $userId);
            }
            if (!empty($saveData['status']) && $saveData['status'] == 2) {
                //移除对应seo
                $delSeoParams = [];
                $delSeoParams['relation_table'] = WebService::RELATION_TABLE_MEETING;
                $delSeoParams['relation_id'] = $id;
                $ret = WebFacade::delSeoByRelation($delSeoParams);
            }
        }
        //更新所有页面缓存
        WebFacade::clearPageCache('urla:');
        return $id;
    }

    /**
     * 构建产品保存数据
     * */
    private function buildMeetingData($params)
    {
        $saveData = [];
        $userId = $this->getAuthUserId();
        $nowTime = nowTime();
        $saveData['update_time'] = $nowTime;
        if (!empty($params['id'])) {
            $saveData['id'] = $params['id'];
            if (isset($params['seo_id'])) {
                $saveData['seo_id'] = $params['seo_id'];
            }
            if (isset($params['pub_date'])) {
                $saveData['pub_date'] = empty($params['pub_date']) ? null : $params['pub_date'];;
            }
            if (isset($params['title'])) {
                $nameUnique = $this->model->checkNameUnique($params['title'], $params['id']);
                if (!$nameUnique) {
                    throw new ApiException(10018, ['name' => $params['title']]);
                }
                $saveData['title'] = empty($params['title']) ? '' : $params['title'];
            }
            if (isset($params['description'])) {
                $saveData['description'] = empty($params['description']) ? '' : $params['description'];
            }
            if (isset($params['content'])) {
                $saveData['content'] = empty($params['content']) ? '' : $params['content'];
            }
            if (isset($params['start_date'])) {
                $saveData['start_date'] = empty($params['start_date']) ? '' : $params['start_date'];
            }
            if (isset($params['end_date'])) {
                $saveData['end_date'] = empty($params['end_date']) ? '' : $params['end_date'];
            }
            if (!empty($params['start_date']) && !empty($params['end_date'])) {
                $startDate = strtotime($params['start_date']);
                $endDate = strtotime($params['end_date']);
                if (!$startDate > $endDate) {
                    throw new ApiException(10022);
                }
            }
            if (isset($params['image_url'])) {
                $saveData['image_url'] = empty($params['image_url']) ? '' : $params['image_url'];
            }
            if (isset($params['image_alt'])) {
                $saveData['image_alt'] = empty($params['image_alt']) ? '' : $params['image_alt'];
            }
            if (isset($params['main_image'])) {
                $saveData['main_image'] = empty($params['main_image']) ? '' : $params['main_image'];
            }
            if (isset($params['main_image_alt'])) {
                $saveData['main_image_alt'] = empty($params['main_image_alt']) ? '' : $params['main_image_alt'];
            }
            if (isset($params['sub_image_urls'])) {
                $saveData['sub_image_urls'] = empty($params['sub_image_urls']) ? '' : json_encode($params['sub_image_urls']);
            }
            if (isset($params['country'])) {
                $saveData['country'] = empty($params['country']) ? '' : $params['country'];
            }
            if (isset($params['address'])) {
                $saveData['address'] = empty($params['address']) ? '' : $params['address'];
            }
            if (isset($params['download_url'])) {
                $saveData['download_url'] = empty($params['download_url']) ? '' : json_encode($params['download_url']);
            }
            if (isset($params['video_path'])) {
                $saveData['video_path'] = empty($params['video_path']) ? '' : $params['video_path'];
            }
            if (isset($params['video_image_url'])) {
                $saveData['video_image_url'] = empty($params['video_image_url']) ? '' : $params['video_image_url'];
            }
            if (isset($params['video_type'])) {
                $saveData['video_type'] = empty($params['video_type']) ? 0 : $params['video_type'];
            }
            if (isset($params['video_desc'])) {
                $saveData['video_desc'] = empty($params['video_desc']) ? '' : $params['video_desc'];
            }
            if (isset($params['is_top'])) {
                $saveData['is_top'] = empty($params['is_top']) ? 0 : $params['is_top'];
            }
            if (isset($params['status'])) {
                $saveData['status'] = $params['status'];
            }
            if (isset($params['meeting_host'])) {
                $saveData['meeting_host'] = empty($params['meeting_host']) ? '' : $params['meeting_host'];
            }
            if (isset($params['page_route'])) {
                $saveData['page_route'] = empty($params['page_route']) ? '' : $params['page_route'];
            }
            if (isset($params['expand_content'])) {
                $saveData['expand_content'] = empty($params['expand_content']) ? '' : json_encode($params['expand_content']);
            }
        } else {
            $nameUnique = $this->model->checkNameUnique($params['title']);
            if (!$nameUnique) {
                throw new ApiException(10018, ['name' => $params['title']]);
            }
            if (empty($params['title'])) {
                throw new ApiException(11002);
            }
            if (isset($params['status'])) {
                $saveData['status'] = $params['status'];
            }
            $saveData['user_id'] = $userId;
            $saveData['pub_date'] = empty($params['pub_date']) ? null : $params['pub_date'];
            $saveData['title'] = empty($params['title']) ? '' : $params['title'];
            $saveData['content'] = empty($params['content']) ? '' : $params['content'];
            $saveData['description'] = empty($params['description']) ? '' : $params['description'];
            $saveData['start_date'] = empty($params['start_date']) ? '' : $params['start_date'];
            $saveData['end_date'] = empty($params['end_date']) ? '' : $params['end_date'];
            if (!empty($params['start_date']) && !empty($params['end_date'])) {
                $startDate = strtotime($params['start_date']);
                $endDate = strtotime($params['end_date']);
                if (!$startDate > $endDate) {
                    throw new ApiException(10022);
                }
            }
            $saveData['image_url'] = empty($params['image_url']) ? '' : $params['image_url'];
            $saveData['image_alt'] = empty($params['image_alt']) ? '' : $params['image_alt'];
            $saveData['main_image'] = empty($params['main_image']) ? '' : $params['main_image'];
            $saveData['main_image_alt'] = empty($params['main_image_alt']) ? '' : $params['main_image_alt'];
            $saveData['sub_image_urls'] = empty($params['sub_image_urls']) ? '' : json_encode($params['sub_image_urls']);
            $saveData['download_url'] = empty($params['download_url']) ? '' : json_encode($params['download_url']);
            $saveData['country'] = empty($params['country']) ? '' : $params['country'];
            $saveData['address'] = empty($params['address']) ? '' : $params['address'];
            $saveData['virtual_view'] = empty($params['virtual_view']) ? 0 : $params['virtual_view'];
            $saveData['total_view'] = $saveData['virtual_view'];
            $saveData['video_path'] = empty($params['video_path']) ? '' : $params['video_path'];
            $saveData['video_image_url'] = empty($params['video_image_url']) ? '' : $params['video_image_url'];
            $saveData['video_type'] = empty($params['video_type']) ? 0 : $params['video_type'];
            $saveData['video_desc'] = empty($params['video_desc']) ? '' : $params['video_desc'];
            $saveData['is_top'] = empty($params['is_top']) ? 0 : $params['is_top'];
            $saveData['sort'] = empty($params['sort']) ? 0 : $params['sort'];
            $saveData['is_recommend'] = empty($params['is_recommend']) ? 0 : $params['is_recommend'];
            $saveData['meeting_host'] = empty($params['meeting_host']) ? '' : $params['meeting_host'];
            $saveData['page_route'] = empty($params['page_route']) ? '' : $params['page_route'];
            $saveData['expand_content'] = empty($params['expand_content']) ? '' : json_encode($params['expand_content']);
            $saveData['create_time'] = $nowTime;
            $saveData['update_time'] = $nowTime;
        }
        return $saveData;
    }

    public function updatePv($id, $newVirtualView)
    {

        $virtualView = $this->getFieldById('virtual_view', $id);
        $value = $newVirtualView - $virtualView;
        $ret = $this->model->where('id', '=', $id)->increment('total_view', $value);
        $ret = $this->model->where('id', '=', $id)->increment('virtual_view', $value);
        WebFacade::clearPageCache('urla:');
        return $ret;
    }

    /**
     * 构造虚拟阅读量
     * */
    public function meetingUvFactory()
    {
        $page = 1;
        $total = 0;
        do {
            $where = [];
            $where['page_size'] = 500;
            $where['page'] = $page;
            $where['status'] = 0;
            $where['lt_total_view'] = 1000;
            $meetingData = $this->model->getMeetingList($where, 'a.id,a.virtual_view,a.total_view');
            if (!empty($meetingData) && !empty($meetingData['data'])) {
                $total = $meetingData['total'];
                $data = $meetingData['data'];
                $updateUvStr = '';
                // 规则：小于1千数随记增加 150以内位数
                foreach ($data as $item) {
                    $value = 0;
                    if ($item['total_view'] < 1000) {
                        $value = mt_rand(0, 150);
                    }
                    /*   if($item['total_view']<1000){
                           $value=  mt_rand(0, 150);
                       }else if($item['total_view']<5000){
                           $value=  mt_rand(0, 99);
                       }else{
                           $value=  mt_rand(0, 9);
                       }*/
                    $this->upMeetingPv($item['id'], $value);
                }
            }
            $page++;
        } while ($total > ($page * 500));
        WebFacade::clearPageCache('urla:');
    }

    /**
     * 更新产品浏览量
     * */
    public function upMeetingPv($meetingId, $value = 1)
    {
        if ($value > 1) {
            $ret = $this->model->where('id', '=', $meetingId)->increment('total_view', $value);
            $ret = $this->model->where('id', '=', $meetingId)->increment('virtual_view', $value);
        } else {
            $totalView = $this->getFieldById('total_view', $meetingId);
            $value = (($value * -1) > $totalView) ? ($totalView * -1) : $value;
            $ret = $this->model->where('id', '=', $meetingId)->increment('total_view', $value);
        }
        return $ret;
    }

    /**
     * 产品推荐设置
     * */
    public function recommendSet($params)
    {
        $id = empty($params['id']) ? 0 : $params['id'];
        $isRecommend = empty($params['is_recommend']) ? 0 : $params['is_recommend'];
        $ret = $this->model->where('id', '=', $id)
            ->update(['is_recommend' => $isRecommend, 'update_time' => nowTime()]);
        //更新所有页面缓存
        WebFacade::clearPageCache('urla:');
        return $id;
    }

    /**
     * 产品列表
     * */
    public function getMeetingList($params)
    {
        $ret = $this->model->getMeetingList($params);
        $pageListData = empty($ret['data']) ? [] : $ret['data'];
        if (!empty($pageListData)) {
            $ids = array_column($pageListData, 'seo_id');
            $seoList = [];
            if (!empty($ids)) {
                $seoList = WebFacade:: getSeoListByIds($ids);
                if (!empty($seoList)) {
                    $seoList = mapByKey($seoList, 'id');
                }
            }
            foreach ($pageListData as &$pageItem) {
                $pageItem['seo_data'] = empty($seoList[$pageItem['seo_id']]) ? [] : $seoList[$pageItem['seo_id']];
                $pageItem['expand_content'] = empty($pageItem['expand_content']) ? [] : json_decode($pageItem['expand_content'], true);
            }
        }
        $ret['data'] = $pageListData;
        return $ret;
    }

    /**
     * 获取产品详情
     * */
    public function getMeetingInfo($params)
    {
        $meetingInfo = $this->model->getMeetingInfo($params);
        if (!empty($meetingInfo)) {
            if (!empty($meetingInfo['seo_id'])) {
                $meetingInfo['seo_data'] = WebFacade::getSeoInfo(['id' => $meetingInfo['seo_id']]);
            } else {
                $meetingInfo['seo_data'] = [
                    'seo_describe' => '',
                    'seo_keyword' => '',
                    'seo_title' => '',
                    'urla' => ''
                ];
            }
            $meetingInfo['spec'] = empty($meetingInfo['spec']) ? [] : json_decode($meetingInfo['spec'], true);
            $meetingInfo['type_ids'] = $this->meetingTypeRelationModel->getTypeIds($meetingInfo['id']);
            $meetingInfo['tag_ids'] = $this->meetingTagRelationModel->getTagIds($meetingInfo['id']);
            $meetingInfo['expand_content'] = empty($meetingInfo['expand_content']) ? [] : json_decode($meetingInfo['expand_content'], true);
            /*if (!empty($meetingInfo['expand_content'])) {
                $meetingInfo['expand_content'] = mapByKey($meetingInfo['expand_content'],'key');
            }*/
            if (!empty($meetingInfo['download_url'])) {
                $meetingInfo['download_url'] = json_decode($meetingInfo['download_url'], true);
            } else {
                $meetingInfo['download_url'] = [];
            }
            if (!empty($meetingInfo['sub_image_urls'])) {
                $meetingInfo['sub_image_urls'] = json_decode($meetingInfo['sub_image_urls'], true);
            } else {
                $meetingInfo['sub_image_urls'] = [];
            }
            $meetingInfo['speech_schedule'] = $this->meetingSpeechScheduleModel->getSpeechScheduleByMeetingId($meetingInfo['id']);
            foreach ($meetingInfo['speech_schedule'] as $key => $speech_item) {
                $meetingInfo['speech_schedule'][$key]['expand_content'] = json_decode($speech_item['expand_content'], true);
            }
        }

        return $meetingInfo;
    }

    /**
     * 获取产品分类未关联的产品
     * */
    public function getUnrelatedMeetingByTypeIds($params)
    {
        $ret = $this->model->getUnrelatedMeetingByTypeIds($params);
        return $ret;
    }

    /**
     * 获取产品标签未关联的产品
     * */
    public function getUnrelatedMeetingByTagIds($params)
    {
        $ret = $this->model->getUnrelatedMeetingByTagIds($params);
        return $ret;
    }

    /**
     * 获取产品详情渲染数据
     * */
    public function getMeetingRenderData($params)
    {
        $meetingInfo = $this->model->getMeetingInfo($params);
        if (!empty($meetingInfo)) {
            $newestTypeAndTagData = $this->getTypeAndTagDataByMeetingId([$meetingInfo['id']]);
            if (!empty($newestTypeAndTagData[$meetingInfo['id']]['type_items'])) {
                $meetingInfo['type_items'] = $newestTypeAndTagData[$meetingInfo['id']]['type_items'];
            } else {
                $meetingInfo['type_items'] = [];
            }
            if (!empty($newestTypeAndTagData[$meetingInfo['id']]['tag_items'])) {
                $meetingInfo['tag_items'] = $newestTypeAndTagData[$meetingInfo['id']]['tag_items'];
            } else {
                $meetingInfo['tag_items'] = [];
            }
            if (!empty($meetingInfo['download_url'])) {
                $meetingInfo['download_url'] = json_decode($meetingInfo['download_url'], true);
            } else {
                $meetingInfo['download_url'] = [];
            }
            if (!empty($meetingInfo['sub_image_urls'])) {
                $meetingInfo['sub_image_urls'] = json_decode($meetingInfo['sub_image_urls'], true);
            } else {
                $meetingInfo['sub_image_urls'] = [];
            }
            $meetingInfo['seo_data'] = WebFacade::getSeoInfo(['id' => $meetingInfo['seo_id']]);
            $meetingInfo['speech_schedule'] = $this->meetingSpeechScheduleModel->getSpeechScheduleByMeetingId($meetingInfo['id']);
            $meetingInfo['expand_content'] = empty($meetingInfo['expand_content']) ? [] : json_decode($meetingInfo['expand_content'], true);
            /*//初始化会议自定义字段
            if (!empty($meetingInfo['expand_content'])) {
                $meetingInfo['expand_content'] = mapByKey($meetingInfo['expand_content'],'key');
            }*/
            //初始化会议日程自定义字段
            if (!empty($meetingInfo['speech_schedule'])) {
                foreach ($meetingInfo['speech_schedule'] as $speech_schedule_key => $speech_schedule_item) {
                    if (!empty($speech_schedule_item['expand_content'])) {
                        $speech_schedule_item['expand_content'] = empty($speech_schedule_item['expand_content']) ? [] : json_decode($speech_schedule_item['expand_content'], true);
//                        $meetingInfo['speech_schedule'][$speech_schedule_key]['expand_content'] = mapByKey($speech_schedule_item['expand_content'],'key');
                        $meetingInfo['speech_schedule'][$speech_schedule_key]['expand_content'] = $speech_schedule_item['expand_content'];
                    }
                }
            }
        }
        return $meetingInfo;
    }

    /**
     * 根据产品id获取产品类型及产品标签数据
     * */
    public function getTypeAndTagDataByMeetingId($newestMeetingIds)
    {
        $resultData = [];
        $newestTypeData = $this->meetingTypeRelationModel->getTypeListByMeetingIds($newestMeetingIds);
        foreach ($newestTypeData as $typeItem) {
            $resultData[$typeItem['meeting_id']]['type_items'][] = $typeItem;
        }
        $newestTagData = $this->meetingTagRelationModel->getTagListByMeetingIds($newestMeetingIds);
        foreach ($newestTagData as $tagItem) {
            $resultData[$tagItem['meeting_id']]['tag_items'][] = $tagItem;
        }
        return $resultData;
    }

    /**
     * 获取产品列表页渲染数据
     * */
    public function getMeetingRecentlyData($params = [])
    {
        // 获取举办地点
        $data = [
            'country' => [],//国家
        ];
        $data['country'] = $this->model->getLocalCountryList();
        return $data;
    }

    /**
     * 获取类型详情
     * */
    public function getMeetingTypeRenderInfo($params = [])
    {

        $typeWhere = [];
        $typeWhere['status'] = 0;
        $typeWhere['id'] = empty($params['id']) ? 0 : $params['id'];
        $typeInfo = $this->meetingTypeModel->getMeetingTypeInfo($typeWhere);
        return $typeInfo;
    }

    /**
     * 获取标签详情
     * */
    public function getMeetingTagRenderInfo($params = [])
    {
        $tagWhere = [];
        $tagWhere['status'] = 0;
        $tagWhere['id'] = empty($params['tag_id']) ? 0 : $params['tag_id'];
        $tagInfo = $this->meetingTagModel->getMeetingTagInfo($tagWhere);
        return $tagInfo;
    }

    /**
     * 获取相关商品
     * */
    public function getRelevanceList($params)
    {
        $newestListParams = [];
        $newestListParams['page_size'] = empty($params['relevance_page_size']) ? 5 : $params['relevance_page_size'];
        $newestListParams['sort']['is_top'] = 1;
        $newestListParams['sort']['pub_date'] = 1;
        $newestListParams['type_ids'] = empty($params['type_ids']) ? [] : $params['type_ids'];
        $newestList = $this->getPublishMeetingList($newestListParams);
        return $newestList;
    }

    /**
     * 获取已发布的连接
     * */
    public function getPublishMeetingList($params, $fields = '')
    {
        if (empty($fields)) {
            $fields = 'a.sort,a.id,a.pub_date,a.title,a.description,a.image_url,a.image_alt,a.expand_content,a.country,' .
                'a.is_top,a.is_recommend,a.download_url,a.total_view,a.meeting_host,a.start_date,a.end_date,b.urla,a.address';
        }
        $ids = [];
        if (!empty($params['type_ids'])) {
            $typeMeetingList = $this->getMeetingByTypeIds(['type_id' => $params['type_ids'], 'page_size' => 99999]);
            if (!empty($typeMeetingList['data'])) {
                $ids = array_column($typeMeetingList['data'], 'id');
            }
        }
        if (!empty($params['tag_ids'])) {
            $tagMeetingList = $this->getMeetingByTagIds(['tag_id' => $params['tag_ids'], 'page_size' => 99999]);
            if (!empty($tagMeetingList['data'])) {
                $tagReIds = array_column($tagMeetingList['data'], 'id');
                if (!empty($tagReIds) && !empty($params['type_ids'])) {
                    $ids = array_intersect($ids, $tagReIds);
                } else {
                    $ids = $tagReIds;
                }
            }
        }

        if (!empty($ids)) {
            $params['ids'] = $ids;
        }
        $meetingList = $this->model->getPublishMeetingList($params, $fields);
        $meetingListData = $meetingList['data'];
        $meetingIds = array_column($meetingListData, 'id');
        if ($meetingIds) {
            $newestTypeAndTagData = $this->getTypeAndTagDataByMeetingId($meetingIds);
            foreach ($meetingListData as &$meetingItem) {
                if (!empty($newestTypeAndTagData[$meetingItem['id']]['type_items'])) {
                    $meetingItem['type_items'] = $newestTypeAndTagData[$meetingItem['id']]['type_items'];
                } else {
                    $meetingItem['type_items'] = [];
                }
                if (!empty($newestTypeAndTagData[$meetingItem['id']]['tag_items'])) {
                    $meetingItem['tag_items'] = $newestTypeAndTagData[$meetingItem['id']]['tag_items'];
                } else {
                    $meetingItem['tag_items'] = [];
                }
                $meetingItem['expand_content'] = empty($meetingItem['expand_content']) ? [] : json_decode($meetingItem['expand_content'], true);
                $meetingItem['expand_content'] = mapByKey($meetingItem['expand_content'], 'key');
            }
            $meetingList['data'] = $meetingListData;
        }

        return $meetingList;
    }

    /**
     * 根据类型id 获取产品列表
     * */
    public function getMeetingByTypeIds($params)
    {
        $retData = $this->meetingTypeRelationModel->getMeetingByTypeIds($params);
        return $retData;
    }

    /**
     * 根据标签id 获取产品列表
     * */
    public function getMeetingByTagIds($params)
    {
        $retData = $this->meetingTagRelationModel->getMeetingByTagIds($params);
        return $retData;
    }

    /**
     * 热门产品列表
     * */
    public function getHotList($params)
    {
        $hotListParams = [];
        $hotListParams['page_size'] = empty($params['hot_news_size']) ? 4 : $params['hot_news_size'];
        $hotListParams['sort']['is_hot'] = 1;
        $hotListParams['sort']['pub_date'] = 1;
        $hotList = $this->getPublishMeetingList($hotListParams);
        return $hotList;
    }

    /**
     * 推荐产品列表
     * */
    public function getRecommendList($params)
    {
        $recommendListParams = [];
        $recommendListParams['page_size'] = empty($params['recommend_news_size']) ? 4 : $params['recommend_news_size'];
        $recommendListParams['sort']['is_recommend'] = 1;
        $recommendListParams['sort']['pub_date'] = 1;
        $recommendList = $this->getPublishMeetingList($recommendListParams);
        return $recommendList;
    }

    /**
     * 根据类型id获取产品
     * */
    public function getPublishMeetingListByTypeId($params)
    {
        $fields = 'a.id,a.pub_date,a.title,a.description,a.image_url,a.image_alt,a.is_top,a.is_recommend,a.download_url,a.total_view,b.type_id,c.urla';
        $ret = $this->model->getPublishMeetingListByTypeId($params, $fields);
        $meetingData = empty($ret['data']) ? [] : $ret['data'];
        if (!empty($meetingData)) {
            $newestMeetingIds = array_column($meetingData, 'id');
            $newestTypeAndTagData = $this->getTypeAndTagDataByMeetingId($newestMeetingIds);
            foreach ($meetingData as &$meetingItem) {
                if (!empty($newestTypeAndTagData[$meetingItem['id']]['type_items'])) {
                    $meetingItem['type_items'] = $newestTypeAndTagData[$meetingItem['id']]['type_items'];
                } else {
                    $meetingItem['type_items'] = [];
                }
                if (!empty($newestTypeAndTagData[$meetingItem['id']]['tag_items'])) {
                    $meetingItem['tag_items'] = $newestTypeAndTagData[$meetingItem['id']]['tag_items'];
                } else {
                    $meetingItem['tag_items'] = [];
                }
            }
            $ret['data'] = $meetingData;
        }

        return $ret;
    }

    /**
     * 根据标签id获取产品
     * */
    public function getPublishMeetingListByTagId($params)
    {
        $fields = 'a.id,a.pub_date,a.title,a.description,a.image_url,a.image_alt,a.is_top,a.is_recommend,a.download_url,a.total_view,b.tag_id,c.urla';
        $ret = $this->model->getPublishMeetingListByTagId($params, $fields);
        $meetingData = empty($ret['data']) ? [] : $ret['data'];
        if (!empty($meetingData)) {
            $newestMeetingIds = array_column($meetingData, 'id');
            $newestTypeAndTagData = $this->getTypeAndTagDataByMeetingId($newestMeetingIds);
            foreach ($meetingData as &$meetingItem) {
                if (!empty($newestTypeAndTagData[$meetingItem['id']]['type_items'])) {
                    $meetingItem['type_items'] = $newestTypeAndTagData[$meetingItem['id']]['type_items'];
                } else {
                    $meetingItem['type_items'] = [];
                }
                if (!empty($newestTypeAndTagData[$meetingItem['id']]['tag_items'])) {
                    $meetingItem['tag_items'] = $newestTypeAndTagData[$meetingItem['id']]['tag_items'];
                } else {
                    $meetingItem['tag_items'] = [];
                }
            }
            $ret['data'] = $meetingData;
        }
        return $ret;
    }

    /**
     * 搜索获取已发布的产品
     * */
    public function getSearchMeetingList($params)
    {
        if (empty($fields)) {
            $fields = 'a.id,a.title,b.urla';
        }
        $meetingList = $this->model->getPublishMeetingList($params, $fields);
        return $meetingList;
    }

    /**
     * 新闻排序
     */
    public function changeMeetingSort($meetingId, $sort)
    {
        $data = [];
        $getData = $this->findOneById($meetingId, 'id,sort');
        if ($sort == 0) { // 置顶
            $sortData = $this->findOneBy([
                'sort' => $sort,
                'id' => ['<>', $meetingId]
            ], 'id');
            if (empty($sortData['id'])) {
                throw new ApiException(1004, ['msg' => '当前已经是最高一行']);
            }
            if ($getData['sort'] == 0) {
                $this->incrementBy([
                    'id' => ['<>', $meetingId],
                ], 'sort');
            } else {
                $this->incrementBy([
                    'id' => ['<', $meetingId],
                ], 'sort');
            }
            $upData['sort'] = $sort;
        } elseif ($sort == '-1') { // 上移
            $upSortData = $this->model->where('sort', '<', $getData['sort'])
                ->orderBy('sort', 'desc')->first();
            if (empty($upSortData)) {
                throw new ApiException(1004, ['msg' => '当前已经是最高一行']);
            } else {
                $upData = $upSortData->toArray();
            }
        } elseif ($sort == '+1') { // 下移
            $downSortData = $this->model->where('sort', '>', $getData['sort'])
                ->orderBy('sort', 'asc')->first();
            if (empty($downSortData)) {
                throw new ApiException(1004, ['msg' => '当前已经是最后一行']);
            } else {
                $upData = $downSortData->toArray();
            }
        }
        $data['sort'] = $upData['sort'];
        $this->updateBy([
            'sort' => $data['sort']
        ], [
            'sort' => $getData['sort']
        ]);
        $is_top = 0;
        if ($data['sort'] == 0) {
            $is_top = 1;
        }
        $rst = $this->update($meetingId, [
            'sort' => $data['sort'],
            'is_top' => $is_top
        ]);
        //更新所有页面缓存
        WebFacade::clearPageCache('urla:');
        return $rst;

    }

    /**
     * 展会、会议下一项
     * */
    public function getNextMeetingItem($id)
    {
        $meeting = $this->model->getNextItem($id);
        return $meeting;
    }

    /**
     * 展会、会议上一项
     * */
    public function getPrevMeetingItem($id)
    {
        $meeting = $this->model->getPrevItem($id);
        return $meeting;
    }


    /**
     * 批量修改类型
     * @param $params
     * @return true
     */
    public function typePluralEdit($params)
    {
        $userId = $this->getAuthUserId();
        $ret = 1;
        foreach ($params['ids'] as $v) {
            $ret = $this->meetingTypeRelationModel->addByMeetingId($v, $params['type_ids'], $userId);
        }
        return $ret;
    }

    /**
     * 批量修改标签
     * @param $params
     * @return true
     */
    public function tagPluralEdit($params)
    {
        $userId = $this->getAuthUserId();
        $ret = 1;
        foreach ($params['ids'] as $v) {
            $ret = $this->meetingTagRelationModel->addByMeetingId($v, $params['tag_ids'], $userId);
        }
        return $ret;
    }

    public function batchDelete($params)
    {
        $ids = $params['ids'];
        $rst = $this->model->whereIn('id', $ids)->update(['status' => 2]);
        //删除处理
        if ($rst) {
            $this->meetingTypeRelationModel->deleteByMeetingId($ids);
            $this->meetingTagRelationModel->deleteByMeetingId($ids);
        }
        return $rst;
    }

    public function batchStatus($params)
    {
        $ids = $params['ids'];
        $status = $params['status'];
        $rst = $this->model->whereIn('id', $ids)->update(['status' => $status]);
        return $rst;
    }

    /**
     * 获取全球展会列表筛选项
     * @param $tagId
     * @param $part
     * @return array
     */
    public function getGlobalFilter($tagId = 1, $part = 0)
    {
        $typeData = $this->model->getTypesWithTagId($tagId);
        $timelineData = [];
        $nowYear = date('Y');
        $nowMonth = date('m');
        if ($part == 1) {
            $nextYear = $nowYear;
            $nextMonth = $nowMonth + 1;
            if ($nextMonth > 12) {
                $nextYear = $nextYear + 1;
                $nextMonth = 1;
            }
        } else {
            $nextYear = $nowYear - 2;
            $nextMonth = 1;
        }
        $timelineData[] = $this->generateYearAndMonthOptions($nextYear, $nextMonth);
        $nextYear = $nextYear + 1;
        $nextMonth = 1;
        $timelineData[] = $this->generateYearAndMonthOptions($nextYear, $nextMonth);
        if ($part != 1) {
            $nextYear = $nextYear + 1;
            $nextMonth = $nowMonth;
            $timelineData[] = $this->generateYearAndMonthOptions($nextYear, $nextMonth, true);
        }
        $areaData = $this->model->getAreaDataWithTagId($tagId);
        return [
            'type_data' => $typeData,
            'area_data' => $areaData,
            'timeline_data' => $timelineData
        ];
    }

    private function generateYearAndMonthOptions($nextYear, $nextMonth, $isPast = false)
    {
        $arr = ['text' => $nextYear];
        $children = [];
        if ($isPast) {
            if ($nextMonth >= 4) {
                $children[] = [
                    'id' => $nextYear . '-1 ' . $nextYear . '-3',
                    'text' => '1-3'
                ];
            }
            if ($nextMonth >= 7) {
                $children[] = [
                    'id' => $nextYear . '-4 ' . $nextYear . '-6',
                    'text' => '4-6'
                ];
            }
            if ($nextMonth >= 10) {
                $children[] = [
                    'id' => $nextYear . '-7 ' . $nextYear . '-9',
                    'text' => '7-9'
                ];
            }
        } else {
            if ($nextMonth <= 3) {
                $children[] = [
                    'id' => $nextYear . '-1 ' . $nextYear . '-3',
                    'text' => '1-3'
                ];
            }
            if ($nextMonth <= 6) {
                $children[] = [
                    'id' => $nextYear . '-4 ' . $nextYear . '-6',
                    'text' => '4-6'
                ];
            }
            if ($nextMonth <= 9) {
                $children[] = [
                    'id' => $nextYear . '-7 ' . $nextYear . '-9',
                    'text' => '7-9'
                ];
            }
            $children[] = [
                'id' => $nextYear . '-10 ' . $nextYear . '-12',
                'text' => '10-12'
            ];
        }
        $arr['children'] = $children;
        return $arr;
    }
}
