<?php


namespace App\Form\Services;

use App\Exceptions\ApiException;
use App\Services\CommonUserBaseService;
use App\Form\Facades\FormItemDetailFacade;
use App\Form\Facades\FormItemFacade;
use App\Form\Facades\FormRecordFacade;
use App\Website\Facades\WebsitePageFacade;

class FormInfoService extends CommonUserBaseService
{
    protected $cache = true;

    protected $cacheBucket = 'FormInfo:';

    protected $tokenBucket = 'Token:';

    protected $activeBucket = "Active:";

    const DEF_FORM_NAME_EN='表单';

    public function getList($params)
    {
        $pageSize = !empty($params['page_size']) ? $params['page_size'] : 10; //页面大小，不传默认一页10条记录
        $pageNo = !empty($params['page']) ? $params['page'] : 1; //页码，不传默认第1页
        $skip = ($pageNo - 1) * $pageSize; //页面记录的开始位置，即偏移量
        $query = $this->getModel()->alias('a');
        if(!empty($params['status'])){
            $query= $query->where('a.status','=',$params['status']);
        }else{
            $query= $query->where('a.status','<',2);
        }

        if(!empty($params['keyword'])){
            $query= $query->where('a.name','like','%'.$params['keyword'].'%');
        }
        if(!empty($params['date'])){
            $date=$params['date'];
            $beginTime=$date.' 00:00:00';
            $endTime=$date.' 23:59:59';
            $query=$query->whereBetween('a.create_time',[$beginTime,$endTime ]);
        }
        $totalCount=$query->count();
        $data=$query->selectRaw('a.*,0 as count,0 as not_read_count')
            ->skip($skip)
            ->limit($pageSize)
            ->orderByDesc('a.data_update_time')
            ->orderByDesc('a.create_time')
            ->get()->toArray();
        $resultData = [];
        if(!empty($data)){
            $resultData =  mapByKey($data, 'id');
            $formIds = array_keys($resultData);
            $recordCountData = $this->getFormRecordCount($formIds);
            $recordNotReadCountData = $this->getFormRecordNotReadCount($formIds);
            $resultData = combineArray($resultData, $recordCountData, 'id');
            $resultData = combineArray($resultData, $recordNotReadCountData, 'id');
            $resultData = array_values($resultData);
        }
        $result = buildPage($resultData, $skip, $pageNo, $pageSize, $totalCount);
        return $result;
    }

    public function setDataUpdateTime($formId){
        $nowTime=nowTime();
       $ret= $this->model->where(['id'=>$formId])->update(['data_update_time'=>$nowTime,'update_time'=>$nowTime]);
       return $ret;
    }

    public function setFormIdsUpdateTime($formIds){
        $nowTime=nowTime();
       $ret= $this->model->whereIn('id',$formIds)->update(['data_update_time'=>$nowTime,'update_time'=>$nowTime]);
       return $ret;
    }

    private function getFormRecordCount($formIds)
    {
        $formRecordModel = FormRecordFacade::getModel();
        $data= $formRecordModel->whereIn('form_id',$formIds)
            ->where('status','<',2)
            ->selectRaw('form_id as id, count(1) as count')
            ->groupBy('form_id')->get()->toArray();
        return $data;
    }
    /**
     * 获取未读询盘数据数量
     * */
    private function getFormRecordNotReadCount($formIds)
    {
        $formRecordModel = FormRecordFacade::getModel();
        $data= $formRecordModel->whereIn('form_id',$formIds)
            ->where('is_read',0)
            ->where('status','<',2)
            ->selectRaw('form_id as id, count(0) as not_read_count')
            ->groupBy('form_id')->get()->toArray();
        return $data;
    }

    /**
     * 获取未读询盘数据总数量
     * */
    public function getCompanyFormRecordNotReadCount()
    {
        $formRecordModel = FormRecordFacade::getModel();
        $result= $formRecordModel->alias('a')
            ->where('a.is_read',0)
            ->where('b.status','=',0)
            ->selectRaw('count(0) as not_read_count')
            ->first()->toArray();
        return $result;
    }

    /**
     * 获取表单数据
     * @param $id
     * @return mixed
     */
    public function getData($id)
    {
        $form = $this->findOneBy(['id' => $id, 'status' => 0], 'id,name');
        $form['items'] = FormItemFacade::getData($id);
        return $form;
    }

    /**
     * 添加表单信息
     * @param array $params
     * @param null $userId
     * @return mixed
     */
    public function addData($params = [], $userId = null)
    {
        $userId = $userId ?? $this->getAuthUserId();
        $data= $this->buildFormData($params,$userId);
        if(!empty($data['id'])){
            $id = $data['id'];
            $this->model->where('id','=',$id)->update($data);
        } else {
            $id = $this->save($data)->id;
        }
        if(!empty($params['form_items'])){
             FormItemFacade::addList($id, $params['form_items'], $userId);
        }
        return $id;
    }

    private function buildFormData($params,$userId = null){
        $userId = $userId ?? $this->getAuthUserId();
        $add = [];
        $add['update_time']=nowTime();
        if(!empty($params['id'])){
            $add['id']=$params['id'];
            if(isset($params['name'])){
                $add['name'] = $params['name'];
                if(empty($params['name'])){
                    throw new ApiException(12001);
                }
                $nameUnique =$this->model->checkNameUnique($params['name'],$params['id']);
                if (!$nameUnique) {
                    throw new ApiException(10018, ['name' => $params['name']]);
                }
            }
        }else{
            if(empty($params['name'])){
                throw new ApiException(12001);
            }
            $nameUnique =$this->model->checkNameUnique($params['name'],'');
            if (!$nameUnique) {
                throw new ApiException(10018, ['name' => $params['name']]);
            }

            $add['name'] = $params['name'];
            $add['user_id']=$userId;
        }
        return $add;
    }

    public function setFormByEditor($param, $userId = null)
    {

        $formParams = $param ?? [];
        $formParams['name'] = $formParams['form_name'] ?? '';
        $formParams['id'] = $formParams['form_id'] ?? '';
        $return = $this->addData($formParams, true,$userId);
        return $return;
    }

    /**
     * 处理页面保存的表单信息
     * @param $element
     * @param null $userId
     * @return mixed
     */
    public function processElement($element, $userId = null)
    {
        $userId = $userId ?? $this->getAuthUserId();
        foreach ($element as &$el){
            if(isset($el['type']) && isset($el['value'])){
                //如果组件类型是表单
                if($el['type'] == 'form' || $el['type'] == 'contactForm'){
                    $el['value'] = $this->setFormByEditor($el['value'],  $userId);
                } else if($el['type'] == 'itemList' || $el['type'] == 'item'){
                    foreach ($el['value'] as &$elm){
                        $elm = $this->processElement($elm, $userId);
                    }
                }
            }
        }
        return $element;
    }

    /**
     * 添加表单项，单条
     * @param array $params
     * @return mixed
     */
    public function addItem($params = [])
    {
        $userId=$this->getAuthUserId();
        $formId = $params['form_id'] ?? '';
        $id=FormItemFacade::addData($params['form_id'] ?? '', $params);
        if($id&&!empty($params['content'])){
            FormItemDetailFacade::addList($formId,$id, $params['content'], $userId);
        }
        return $id;
    }

    /**
     *  删除表单项，单条
     * */
    public function delItem($params){
        $formId = $params['form_id'] ?? '';
        $itemId = $params['id'] ?? 0;
        $ret=FormItemFacade::delData($formId,$itemId);
        return $ret;
    }

    /**
     * 表单项排序
     * @param $id
     * @return mixed
     */
    public function sortItem($id)
    {
        return FormItemFacade::sortItem($id);
    }

    /**
     * 表单项详情排序
     * @param $id
     * @return mixed
     */
    public function sortItemDetail($id)
    {
        return FormItemDetailFacade::sortItemDetails($id);
    }

    public function setIsRemove($id){
        if(!is_array($id)){
            $id=[$id];
        }
       $ret= $this->model->whereIn('id',$id)->update(['is_remove'=>1]);
       return $ret;
    }

    /**
     * 禁用或删除表单
     * */
    public function stopAndDelFormById($id,$status=1){
        $model = $this->getModel();
        $updateData=[];
        $updateData['status']=$status;
        $updateData['update_time']=nowTime();
        $ret= $model->where('id','=',$id)->update($updateData);
        return $ret;
    }

    /**
     * 当有表单提交的时候重新激活禁用状态的表单
     * */
    public function reActivateFormById($id){
        $model = $this->getModel();
        $updateData=[];
        $updateData['status']=0;
        $updateData['update_time']=nowTime();
        $ret= $model->where('id','=',$id)->where('status','=','1')->update($updateData);
        return $ret;
    }
    /**
     * 获取对应公司下询盘列表
     * */
    public function correspondCompanyFormList($params)
    {
        $pageSize = !empty($params['page_size']) ? $params['page_size'] : 10; //页面大小，不传默认一页10条记录
        $pageNo = !empty($params['page']) ? $params['page'] : 1; //页码，不传默认第1页
        $skip = ($pageNo - 1) * $pageSize; //页面记录的开始位置，即偏移量
        $model = $this->getModel();



        $query= $model->alias('a')
            ->leftJoin('website_page as b', 'a.website_page_id', '=', 'b.id')
            ->where('a.status','=',0);
        if(!empty($params['keyword'])){
            $query= $query->where('a.name','like','%'.$params['keyword'].'%');
        }
        if(!empty($params['date'])){
            $date=$params['date'];
            $beginTime=$date.' 00:00:00';
            $endTime=$date.' 23:59:59';

            $query=$query->whereBetween('a.create_time',[$beginTime,$endTime ]);
        }

        $totalCount=$query->count();
        $data=$query->selectRaw('a.*,b.page_name,0 as count,0 as not_read_count,b.urla,b.link,c.name as website_name ')
            ->skip($skip)
            ->limit($pageSize)
            ->orderByDesc('a.data_update_time')
            ->orderByDesc('a.create_time')
            ->get()->toArray();
        $resultData = [];
        if(!empty($data)){
            $resultData =  mapByKey($data, 'id');
            $formIds = array_keys($resultData);
            $recordCountData = $this->getFormRecordCount($formIds);
            $recordNotReadCountData = $this->getFormRecordNotReadCount($formIds);
            $resultData = combineArray($resultData, $recordCountData, 'id');
            $resultData = combineArray($resultData, $recordNotReadCountData, 'id');
            $resultData = array_values($resultData);
        }
        $result = buildPage($resultData, $skip, $pageNo, $pageSize, $totalCount);
        return $result;
    }


}
