<?php
/**
 *
 * @file:WechatSubscribeService.php
 * @Date: 2023/7/10
 * @Time: 09:35
 */


namespace Modules\WechatPlatform\Services;

use Illuminate\Support\Facades\DB;
use Modules\Common\Services\BaseService;
use Modules\WechatPlatform\Models\MiniprogramWechatGlobalConfig;
use Modules\WechatPlatform\Models\WechatAccountSubscribeDetail;
use Modules\WechatPlatform\Models\WechatSubscribeMsg;

class WechatSubscribeService extends BaseService
{

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


    /**
     *  获取配置
     * name: getConfig
     * @param $userId
     * @param $puserId
     * @param $miniprogramId
     * @return int
     * date 2023/07/10 09:40
     */
    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;
    }

    /**
     *  保存配置
     * name: setConfig
     * @param $param
     * @return string
     * date 2023/07/10 09:39
     */
    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 "操作成功";
        }
        self::throwErrMsg("操作失败");
    }

    public static function addSubscribe(mixed $param)
    {
        $res = WechatSubscribeMsg::create($param);
        if ($res) {
            return "操作成功";
        }
        self::throwErrMsg("操作失败");
    }


    /**
     *  获取详情
     * name: getDetail
     * @param $id
     * date 2023/07/10 10:08
     */
    public static function getDetail($id)
    {
        return WechatSubscribeMsg::query()->where('id', $id)->where('is_del', 0)->first()->makeHidden(array_merge(self::$hideField,['wechat_accounts']));
    }

    public static function allocation($id, $wxAuthIds)
    {
        $info = WechatSubscribeMsg::query()->where('id', $id)->where('is_del', 0)->first();
        if (is_empty($info)) {
            self::throwErrMsg('该关注回复不存在或已删除');
        }
        $data = [];
        $list = [];
        $appIds =[];
        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) . "的公众号没有使用权限");
            }
            foreach ($wechatAccountInfos as $val){
                $data['wechat_accounts'][] = [
                    'id' =>  $val->id,
                    'appid' =>$val->authorizer_appid,
                    'nick_name' => $val->nick_name,
                    'component_appid' => $val->component_appid
                ];
                $appIds[] = $val->authorizer_appid;
                $list[] = [
                    'subscribe_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,
                    'content' => $info->send_content,
                    'status' => 1,
                ];
            }
            unset($wechatAccountInfos);

        }
        DB::beginTransaction();
        try {
            if (!empty($appIds)){
                // 关闭所有要配置的公众号关注回复
                WechatAccountSubscribeDetail::whereIn('appid',$appIds)->update(['status' => 0]);
                foreach ($list as $val){
                    WechatAccountSubscribeDetail::updateOrCreate(
                        [
                            'subscribe_id' => $val['subscribe_id'],
                            'miniprogram_id' => $val['miniprogram_id'],
                            'wechat_authorization_info_id' => $val['wechat_authorization_info_id']
                        ],$val);
                }
            }else{
                // 关闭当前回复所涉及的公众号关注回复
                WechatAccountSubscribeDetail::where('subscribe_id',$id)->update(['status' => 0]);
            }

            WechatSubscribeMsg::where('id',$id)->update($data);
            DB::commit();
        }catch (\Exception $exception){
            self::throwErrMsg('操作失败');
        }
        return "操作成功";
    }

    /**
     *  编辑
     * name: updateSubscribe
     * @param $id
     * @param mixed $param
     * @return string
     * date 2023/07/10 11:03
     */
    public static function updateSubscribe($id, mixed $param)
    {
        $info = WechatSubscribeMsg::query()->where('id', $id)->where('is_del', 0)->first();
        if (is_empty($info)) {
            self::throwErrMsg('该关注回复不存在或已删除');
        }

        DB::beginTransaction();
        try {
            WechatSubscribeMsg::query()->where('id',$id)->update($param);
            WechatAccountSubscribeDetail::where('subscribe_id',$info->id)->update(['content' => $param['send_content']]);
            DB::commit();
        }catch (\Exception $exception){
            self::throwErrMsg('操作失败');
        }
        return "操作成功";
    }

    /**
     *  删除
     * name: del
     * @param array $ids
     * date 2023/07/10 11:03
     */
    public static function del(array $ids)
    {
        if (empty($ids)) {
            self::throwErrMsg('要删除的数据不能为空');
        }

        DB::beginTransaction();
        try {
            WechatSubscribeMsg::query()->whereIn('id',$ids)->update(['is_del' => 1, 'del_at' => get_date()]);
            WechatAccountSubscribeDetail::query()->whereIn('subscribe_id',$ids)->update(['status' => 0]);
            DB::commit();
        }catch (\Exception $exception){
            self::throwErrMsg('操作失败');
        }
        return "操作成功";
    }

    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 = WechatAccountSubscribeDetail::where('subscribe_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: list
     * @param array $param
     * date 2023/07/10 11:38
     */
    public static function list(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 = WechatSubscribeMsg::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;
    }

}
