<?php
/**
 *
 * @file:WechatKeywordsService.php
 * @Date: 2023/7/5
 * @Time: 16:31
 */


namespace Modules\WechatPlatform\Services;

use Illuminate\Support\Facades\DB;
use Modules\Common\Services\BaseService;
use Modules\WechatPlatform\Models\MiniprogramWechatGlobalConfig;
use Modules\WechatPlatform\Models\WechatAccountKeywordLog;
use Modules\WechatPlatform\Models\WechatKeywords;

class WechatKeywordsService extends BaseService
{

    protected static array $hideField = ['updated_at', 'is_del', 'del_at', 'user_id', 'puser_id', 'send_content']; // 公用的影藏字段
    const KEYWORD_SET_KEY = "miniprogram_wechat_keyword";

    /**
     *  添加关键字
     * name: addKeyword
     * @param mixed $param
     * date 2023/07/06 10:11
     */
    public static function addKeyword(mixed $param)
    {
        $res = WechatKeywords::create($param);
        if ($res) {
            return "操作成功";
        }
        return "操作失败";
    }

    /**
     *  关键词列表
     * name: getKeywordsList
     * @param array $param
     * date 2023/07/06 13:53
     */
    public static function getKeywordsList(array $param)
    {
        $sql = self::getQuery($param)->orderBy('id','desc');
        $isAll = getProp($param,'is_all',false);
        if($isAll){
            $list = $sql->get();
        }else{
            $list = $sql->paginate(getProp($param,'limit',10));
        }
        $list->makeHidden(array_merge(self::$hideField,['content']));
        return $list;
    }

    private static function getQuery(array $param)
    {
        $sql = WechatKeywords::query()->where('is_del',0);
        if (getProp($param, 'puser_id')) {
            $sql->where('puser_id', $param['puser_id']);
        }
        if (getProp($param, 'user_id')) {
            $sql->where('user_id', $param['user_id']);
        }
        if (getProp($param, 'keyword')) {
            $sql->where('keyword', "like", "%" . $param['keyword'] . "%");
        }
        if(getProp($param,'wechat_authorization_info_id')){
            $sql->whereJsonContains('wechat_accounts->id',$param['wechat_authorization_info_id']);
        }
        return $sql;
    }

    /**
     *  详情
     * name: detail
     * @param $id
     * date 2023/07/06 13:55
     */
    public static function detail($id)
    {
        return WechatKeywords::where('id', $id)->where('is_del', 0)->first()->makeHidden(array_merge(self::$hideField,['wechat_accounts']));
    }

    /**
     *  保存关键字
     * name: updateKeyWords
     * @param $id
     * @param mixed $param
     * @return string
     * date 2023/07/06 14:51
     */
    public static function updateKeyWords($id, mixed $param)
    {
        $info = WechatKeywords::where('id', $id)->where('is_del', 0)->first();
        if (is_empty($info)) {
            self::throwErrMsg('关键词不存在或已删除');
        }
        $appIds = [];
        if ($param['keyword'] != $info->keyword) {
            // 修改关键词，需要查询词关键词是否已配置
            $appIds = WechatAccountKeywordLog::where('weacht_keyworld_id', $info->id)->where('status', 1)->pluck('wechat_authorization_info_id')->toArray();
        }
        WechatKeywords::query()->where('id',$id)->update($param);
        if ($appIds){
            WechatAccountKeywordLog::where('weacht_keyworld_id',$info->id)->update(['status' => 0]);
            self::allocation($info->id,$appIds);
        }
        return "操作成功";
    }

    /**
     *  配置公众号列表
     * name: WechaAccountAuthListInfo
     * @param $id
     * @param mixed $userId
     * date 2023/07/06 15:31
     */
    public static function WechaAccountAuthListInfo($id, mixed $userId)
    {
        $list = DB::table('wechat_authorization_infos')
            ->where('user_id', $userId)
            ->select('id', 'nick_name', 'is_enabled')->get();
        $authList = WechatAccountKeywordLog::where('weacht_keyworld_id', $id)->get();
        if (!$list->isEmpty()) {
            foreach ($list as $val) {
                $val->is_auth = 0;
                $info = $authList->where('wechat_authorization_info_id', $val->id)->first();
                if (getProp($info, 'status') == 1) {
                    $val->is_auth = 1;
                }
                if ($val->is_enabled != 1) {
                    $val->nick_name .= "(取消授权)";
                }
                unset($val->is_enabled);
            }
        }
        return $list;
    }

    /**
     *   删除关键词
     * name: delKeywords
     * @param array $ids
     * date 2023/07/06 15:54
     */
    public static function delKeywords(array $ids)
    {
        if (empty($ids)) {
            self::throwErrMsg('要删除的数据不能为空');
        }
        DB::beginTransaction();
        try {
            WechatKeywords::query()->whereIn('id', $ids)->update(['is_del' => 1, 'del_at' => get_date()]);
            WechatAccountKeywordLog::query()->whereIn('weacht_keyworld_id', $ids)->update(['status' => 0]);
            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            self::throwErrMsg('删除失败');
        }
        return "操作成功";
    }

    public static function allocation($id, $wxAuthIds)
    {
        $info = WechatKeywords::where('id', $id)->where('is_del', 0)->first();
        if (is_empty($info)) {
            self::throwErrMsg('关键词不存在或已删除');
        }
        $data = [];
        $list = [];
        $errMsg = "";
        if (empty($wxAuthIds)){
            $data['wechat_accounts'] = [];
        }else{
            $wechatAccountInfos = DB::table('wechat_authorization_infos')
                ->whereIn('id',$wxAuthIds)
                ->where('is_enabled',1)
                ->where('user_id',$info->user_id)
                ->get();
            if($wechatAccountInfos->isEmpty()){
                self::throwErrMsg("优化师对提交的公众号没有使用权限");
            }

            $canNotUsed = $wechatAccountInfos->pluck('id')->toArray();
            $canNotUsed = array_diff($wxAuthIds,$canNotUsed);
            if (count($canNotUsed) > 0){
                self::throwErrMsg("优化师对id:为：".implode(',',$canNotUsed)."的公众号没有使用权限");
            }
            $keywords = explode(',',$info->keyword);

            $allSet =   WechatAccountKeywordLog::where('user_id',$info->user_id)->get();

            foreach ($wechatAccountInfos as  $val){
                $data['wechat_accounts'][] = [
                    'id' =>  $val->id,
                    'appid' =>$val->authorizer_appid,
                    'nick_name' => $val->nick_name,
                    'component_appid' => $val->component_appid
                ];
                foreach ($keywords as  $kval){
                    $has  = $allSet->where( 'keyword',$kval)
                        ->where( 'wechat_authorization_info_id', $val->id)
                    ->where( 'status', 1)
                        ->where('weacht_keyworld_id','<>',$info->id)->first();
                    if ($has){
                        $errMsg .=  "{$val->nick_name}已重新配置关键词{$kval};";
                    }
                    $list[] = [
                        'weacht_keyworld_id' => $info->id,
                        'user_id' => $info->user_id,
                        'puser_id' => $info->puser_id,
                        'miniprogram_id' =>  $info->miniprogram_id,
                        'appid' => $val->authorizer_appid,
                        'wechat_authorization_info_id'=> $val->id,
                        'nick_name' => $val->nick_name,
                        'keyword' => $kval,
                        'content' => $info->send_content,
                        'status' => 1,
                    ];
                }
            }
            unset($wechatAccountInfos,$allSet);
        }
        DB::beginTransaction();
        try {
            WechatAccountKeywordLog::where('weacht_keyworld_id',$id)->update(['status' => 0]);
            if (!empty($list)){
                WechatAccountKeywordLog::where('user_id',$info->user_id)
                    ->whereIn("keyword",$keywords)->whereIn('wechat_authorization_info_id',$wxAuthIds)->update(['status' => 0]);
                foreach ($list as $val){
                    WechatAccountKeywordLog::updateOrCreate(['weacht_keyworld_id' => $val['weacht_keyworld_id'],'keyword' => $val['keyword'],'wechat_authorization_info_id' => $val['wechat_authorization_info_id']],$val);
                }
            }
            WechatKeywords::where('id',$id)->update($data);
            DB::commit();
        }catch (\Exception $exception){
            self::throwErrMsg('操作失败');
        }
        return "操作成功".$errMsg;
    }

    public static function getConfig($userId, $puserId, $miniprogramId)
    {
        $set = MiniprogramWechatGlobalConfig::where(['user_id' =>  $userId,'puser_id' =>  $puserId,'miniprogram_id' =>  $miniprogramId])
                ->where('type',self::KEYWORD_SET_KEY)->value('value');
        return $set == 1 ? 1 :0;
    }

    public static function setConfig($param)
    {
        $param['type'] = self::KEYWORD_SET_KEY;
        $res = MiniprogramWechatGlobalConfig::updateOrCreate(
            ['user_id' =>  $param['user_id'],'puser_id' => $param['puser_id'],'miniprogram_id' =>  $param['miniprogram_id'],'type' => self::KEYWORD_SET_KEY],
            $param
        );
        if($res){
            return "操作成功";
        }
        return "操作失败";
    }
}
