<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\adminapi\logic\group_activity;


use think\Exception;
use think\facade\Db;
use think\facade\Log;
use app\common\logic\BaseLogic;
use app\common\service\wechat\WeChatMnpService;
use app\common\model\group_activity\GroupActivity;
use app\common\model\group_activity\GroupActivityCategory;

/**
 * 拼团活动分类逻辑
 * Class GroupActivityCategoryLogic
 * @package app\adminapi\logic\group_activity
 */
class GroupActivityCategoryLogic extends BaseLogic
{


    /**
     * @notes 添加
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2025/03/13 10:31
     */
    public static function add(array $params): bool
    {
        try {
            if ($params['type'] == 1) {
                $params['participant_num'] = $params['participant_num'][0];
            } else {
                $params['participant_num'] = implode(",",$params['participant_num']);
            }
            if ($params['is_simulate_form'] == 1) {
                $params['simulate_num'] = $params['type'] == 1 ? $params['simulate_num'][0] : implode(",",$params['simulate_num']);
            } else {
                $params['simulate_num'] = '';
            }
            $params['area'] = implode(",",$params['area']);
            $params['images'] = implode(",",$params['images']);

            Db::startTrans();
            $category = GroupActivityCategory::create([
                'title' => $params['title'],
                'images' => $params['images'],
                'start_time' => strtotime($params['start_time']),
                'end_time' => strtotime($params['end_time']),
                'service_time' => strtotime($params['service_time']),
                'property_head_id' => $params['property_head_id'],
                'participant_num' => $params['participant_num'],
                'type' => $params['type'],
                'form_time_limit' => $params['form_time_limit'],
                'is_simulate_form' => $params['is_simulate_form'],
                'simulate_num' => $params['simulate_num'],
                'area' => $params['area'],
                'status' => $params['status'],
            ]);

            foreach($params['block_data'] as $item) {
                foreach($item['activity'] as &$activity) {
                    if (empty($activity['origin_price']) || empty($activity['price'])) {
                        throw new Exception('请完善拼团活动配置');
                    }
                    $res = GroupActivity::create([
                        'title' => $activity['title'],
                        'image' => $activity['image'],
                        'equity_id' => $activity['equity_id'],
                        'block_key' => $item['block_key'],
                        'group_category_id' => $category['id'],
                        'origin_price' => $activity['origin_price'],
                        'price' => $activity['price'],
                        'work_amount' => isset($activity['work_amount']) ? $activity['work_amount'] : 0,
                        'settlement_amount' => isset($activity['settlement_amount']) ? $activity['settlement_amount'] : 0,
                    ]);
                    $activity['data_id'] = $res['id'];
                }
            }

            GroupActivityCategory::where('id',$category['id'])->update(['block_data' => json_encode($params['block_data'])]);
        
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * @notes 编辑拼团活动
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2025/03/13 10:31
     */
    public static function edit(array $params): bool
    {
        try {
            if ($params['type'] == 1) {
                $params['participant_num'] = $params['participant_num'][0];
            } else {
                $params['participant_num'] = implode(",",$params['participant_num']);
            }
            if ($params['is_simulate_form'] == 1) {
                $params['simulate_num'] = $params['type'] == 1 ? $params['simulate_num'][0] : implode(",",$params['simulate_num']);
            } else {
                $params['simulate_num'] = '';
            }
            
            $params['area'] = implode(",",$params['area']);
            $params['images'] = implode(",",$params['images']);
            
            Db::startTrans();

            $ids = [];
            foreach($params['block_data'] as $item) {
                foreach($item['activity'] as &$activity) {
                    if (empty($activity['origin_price']) || empty($activity['price'])) {
                        throw new Exception('请完善拼团活动配置');
                    }
                    $data = [
                        'title' => $activity['title'],
                        'image' => $activity['image'],
                        'equity_id' => $activity['equity_id'],
                        'block_key' => $item['block_key'],
                        'group_category_id' => $params['id'],
                        'origin_price' => $activity['origin_price'],
                        'price' => $activity['price'],
                        'work_amount' => isset($activity['work_amount']) ? $activity['work_amount'] : 0,
                        'settlement_amount' => isset($activity['settlement_amount']) ? $activity['settlement_amount'] : 0,
                        'delete_time' => null,
                    ];
                    if (!empty($activity['data_id'])) {
                        GroupActivity::where('id',$activity['data_id'])->update($data);
                    } else {
                        $res = GroupActivity::create($data);
                        $activity['data_id'] = $res['id'];
                    }
                    $ids[] = $activity['data_id'];
                }
            }
            
            GroupActivity::where('group_category_id', $params['id'])->whereNotIn('id',$ids)->update(['delete_time' => time()]);

            GroupActivityCategory::where('id', $params['id'])->update([
                'title' => $params['title'],
                'images' => $params['images'],
                'start_time' => strtotime($params['start_time']),
                'end_time' => strtotime($params['end_time']),
                'service_time' => strtotime($params['service_time']),
                'property_head_id' => $params['property_head_id'],
                'participant_num' => $params['participant_num'],
                'type' => $params['type'],
                'form_time_limit' => $params['form_time_limit'],
                'is_simulate_form' => $params['is_simulate_form'],
                'simulate_num' => $params['simulate_num'],
                'area' => $params['area'],
                'block_data' => json_encode($params['block_data']),
                'status' => $params['status'],
            ]);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * @notes 删除
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2025/03/13 10:31
     */
    public static function delete(array $params): bool
    {
        $result = GroupActivityCategory::destroy($params['id']);
        if ($result) {
            GroupActivity::where('group_category_id',$params['id'])->update(['delete_time' => time()]);
            return true;
        } 
        return $result;
    }


    /**
     * @notes 获取拼团分类详情
     * @param $params
     * @return array
     * @author likeadmin
     * @date 2025/03/13 10:31
     */
    public static function detail($params): array
    {
        
        $detail = GroupActivityCategory::findOrEmpty($params['id'])->toArray();
        $detail['end_time'] = date('Y-m-d H:i:s',$detail['end_time']);
        $detail['participant_num'] = explode(",",$detail['participant_num']);
        $detail['simulate_num'] = $detail['simulate_num'] ? explode(",",$detail['simulate_num']) : [];
        $detail['area'] = explode(",",$detail['area']);
        $detail['images'] = $detail['images'] ? explode(",",$detail['images']) : [];
        $detail['block_data'] = json_decode($detail['block_data'],true);
        foreach($detail['block_data'] as $key => $item) {
            $detail['block_data'][$key]['activity'] = GroupActivity::where(['block_key' => $item['block_key'],'group_category_id' => $detail['id']])
                    ->field('id,id as data_id,title,image,equity_id,block_key,origin_price,price,work_amount,settlement_amount')
                    ->select()
                    ->toArray();
        }
        
        return $detail;
    
    }

    /**
     * 获取二维码
     * @return string|void
     */
    public static function getQRCode($params,$url)
    {
        try {
            if (empty($params['id'])) {
                return '';
            }
            $mnp_page = 'pages/web_view/group';
            
            $scene_page = 'good';
            Log::info('getQRCode:'.rawurlencode($scene_page));
            $response = (new WeChatMnpService())->getUnlimitedQRCode(
                'page='.$scene_page.'&id='.$params['id'],
                $mnp_page,
                env('miniprogram.mini_env_version', 'release'),
                false
            );
            $qrcode = $response->getContent();
            if(!is_dir('./uploads/wx_qrcode/'.date('Ymd'))){
                mkdir('./uploads/wx_qrcode/'.date('Ymd'));
            }
            $file_name = 'uploads/wx_qrcode/'.date('Ymd').'/'.time().rand(1000,9999).'.png';
            file_put_contents($file_name, $qrcode);
            return $url.'/'.$file_name;
        } catch (\Throwable $e) {
            Log::info('getQRCode:'.$e->getMessage());
            return '';
        }
    }

    public static function copy($params)
    {
        try {
            
            Db::startTrans();
            $categoryDetail = self::detail($params);
            $category = GroupActivityCategory::create([
                'title' => $categoryDetail['title'],
                'images' => $categoryDetail['images'] ? implode(",", $categoryDetail['images']) : '',
                'start_time' => strtotime($categoryDetail['start_time']),
                'end_time' => strtotime($categoryDetail['end_time']),
                'service_time' => strtotime($categoryDetail['service_time']),
                'property_head_id' => $categoryDetail['property_head_id'],
                'participant_num' => implode(",", $categoryDetail['participant_num']),
                'type' => $categoryDetail['type'],
                'form_time_limit' => $categoryDetail['form_time_limit'],
                'is_simulate_form' => $categoryDetail['is_simulate_form'],
                'simulate_num' => $categoryDetail['simulate_num'] ? implode(",", $categoryDetail['simulate_num']) : '',
                'area' => implode(",", $categoryDetail['area']),
                'status' => $categoryDetail['status'],
            ]);
            
            $block_data = $categoryDetail['block_data'];
            foreach($block_data as $item) {
                foreach($item['activity'] as &$activity) {
                    
                    $res = GroupActivity::create([
                        'title' => $activity['title'],
                        'image' => $activity['image'],
                        'equity_id' => $activity['equity_id'],
                        'block_key' => $item['block_key'],
                        'group_category_id' => $category['id'],
                        'origin_price' => $activity['origin_price'],
                        'price' => $activity['price'],
                        'work_amount' => isset($activity['work_amount']) ? $activity['work_amount'] : 0,
                        'settlement_amount' => isset($activity['settlement_amount']) ? $activity['settlement_amount'] : 0,
                    ]);
                    $activity['data_id'] = $res['id'];
                }
            }
            GroupActivityCategory::where('id',$category['id'])->update(['block_data' => json_encode($block_data)]);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }
}