<?php

namespace app\admin\controller\shopro\user;

use app\admin\model\shopro\ShoproUserTag;
use think\Db;
use app\admin\controller\shopro\Common;
use addons\shopro\service\Wallet as WalletService;
use app\admin\model\shopro\user\User as UserModel;
use app\admin\model\shopro\user\Coupon as UserCouponModel;
use traits\model\SoftDelete;

class User extends Common
{
    protected $model = null;

    protected $noNeedRight = ['select'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new UserModel;
    }

    /**
     * 用户列表
     */
    public function index()
    {
        if (!$this->request->isAjax()) {
            return $this->view->fetch();
        }

        $data = $this->model::with(['shopro_user_tag'])->sheepFilter()->paginate($this->request->param('list_rows', 10));

        $this->success('获取成功', null, $data);
    }

    /**
     * 用户详情
     *
     * @param  $id
     */
    public function detail($id)
    {
        if (!$this->request->isAjax()) {
            return $this->view->fetch();
        }

        $user = $this->model->with(['third_oauth', 'parent_user', 'shopro_user_tag'])->where('id', $id)->find();
        if (!$user) {
            $this->error(__('No Results were found'));
        }

        $this->success('获取成功', null, $user);
    }

    /**
     * 更新用户
     *
     * @param  $id
     * @return \think\Response
     */
    public function edit($id = null)
    {
        operate_filter();
        $params = $this->request->only(['username', 'nickname', 'mobile', 'password', 'avatar', 'gender', 'email', 'status', 'birthday']);

        if (empty($params['password'])) unset($params['password']);
        if (empty($params['username'])) unset($params['username']);
        
        if (isset($params['birthday']) && trim($params['birthday']) === '') {
            $params['birthday'] = null;
        }

        $params['id'] = $id;
        $this->svalidate($params, '.edit');
        unset($params['id']);

        $user = $this->model->where('id', $id)->find();
        $oldStatus = $user->status;
        $user->save($params);

        // 用户状态变更时同步更新代理商和分销商状态，并记录日志
        if (isset($params['status']) && $params['status'] !== $oldStatus) {
            custom_log("用户状态变更: user_id={$id}, {$oldStatus} -> {$params['status']}", $id, 'user_status_change', 'info');

            $agentStatus = $params['status'] === 'disabled' ? 'freeze' : ($params['status'] === 'normal' ? 'normal' : null);
            if ($agentStatus) {
                Db::table('fa_shopro_agent')->where('user_id', $id)->where('status', '<>', $agentStatus)->update(['status' => $agentStatus]);
                Db::table('fa_shopro_commission_agent')->where('user_id', $id)->where('status', '<>', $agentStatus)->update(['status' => $agentStatus]);
            }
        }

        $this->success('更新成功', null, $user);
    }

    /**
     * 删除用户(支持批量)
     * 管理后台-会员管理-删除
     * 删除功能已经被隐藏，此方法应该用不到了 - 2026.07.06
     *
     * @param  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        operate_filter();

        if (empty($id)) {
            $this->error(__('Parameter %s can not be empty', 'id'));
        }

        $id = explode(',', $id);
        $list = $this->model->where('id', 'in', $id)->select();
        $result = Db::transaction(function () use ($list) {
            $count = 0;
            foreach ($list as $item) {
//                $count += $item->delete(); // 物理删除，UserModel添加了软删除
                $count += $item->save(['status' => 'disabled']); // 改成逻辑删除，状态改为"禁用"

                // 批量禁用时同步更新代理商和分销商状态为冻结
                Db::table('fa_shopro_agent')->where('user_id', $item->id)->where('status', '<>', 'freeze')->update(['status' => 'freeze']);
                Db::table('fa_shopro_commission_agent')->where('user_id', $item->id)->where('status', '<>', 'freeze')->update(['status' => 'freeze']);
            }

            return $count;
        });

        if ($result) {
            $this->success('禁用成功', null, $result);
        } else {
            $this->error(__('No rows were deleted'));
        }
    }

    public function recharge()
    {
        if (!$this->request->isAjax()) {
            return $this->view->fetch();
        }

        $params = $this->request->only(['id', 'type', 'amount', 'memo']);
        if (!in_array($params['type'], ['money', 'score'])) {
            error_stop('参数错误');
        }

        $result = Db::transaction(function () use ($params) {
            return WalletService::change($params['id'], $params['type'], $params['amount'], 'admin_recharge', [], $params['memo']);
        });
        if ($result) {
            $this->success('充值成功');
        }
        $this->error('充值失败');
    }


    /**
     * 用户优惠券列表
     */
    public function coupon($id)
    {
        $userCoupons = UserCouponModel::sheepFilter()->with('coupon')->where('user_id', $id)
            ->order('id', 'desc')->paginate($this->request->param('list_rows', 10));

        $this->success('获取成功', null, $userCoupons);
    }


    public function select()
    {
        if (!$this->request->isAjax()) {
            return $this->view->fetch();
        }

        $data = $this->model->sheepFilter()->paginate($this->request->param('list_rows', 10));
        $this->success('获取成功', null, $data);
    }

    /**
     * 保存用户标签
     */
    public function saveTags()
    {
        operate_filter();

        $userId = $this->request->param('user_id');
        $tags = $this->request->param('tags/a', []);
        if (!$userId) {
            $this->error('用户ID不能为空');
        }
        // 删除旧标签
        Db::name('shopro_user_tag')->where('user_id', $userId)->delete();
        // 插入新标签
        if (!empty($tags)) {
            $tagMap = [
                'active' => '活跃用户',
                'valuable' => '高价值用户',
                'silent' => '沉默用户',
                'new' => '新用户',
                'vip' => 'VIP用户',
                'wholesale' => '批发客户',
            ];
            $data = [];
            $now = time();
            foreach ($tags as $tagCode) {
                if (isset($tagMap[$tagCode])) {
                    $data[] = [
                        'user_id' => $userId,
                        'tag_code' => $tagCode,
                        'tag_name' => $tagMap[$tagCode],
                        'create_time' => $now,
                        'update_time' => $now,
                    ];
                }
            }
            if (!empty($data)) {
                Db::name('shopro_user_tag')->insertAll($data);
            }
        }
        $this->success('保存成功');
    }


    /**
     * 导出用户列表（分页多选导出）
     */
    public function export()
    {
        $ids = $this->request->param('ids', '');
        if (empty($ids)) {
            $this->error('请选择要导出的用户');
        }

        $idArr = array_filter(array_map('intval', explode(',', $ids)));
        if (empty($idArr)) {
            $this->error('导出数据为空');
        }

        $cellTitles = [
            'id' => 'ID',
            'username' => '用户名',
            'nickname' => '昵称',
            'mobile' => '手机号',
            'email' => '邮箱',
            'gender_text' => '性别',
            'birthday' => '生日',
            'status_text' => '状态',
            'commission' => '佣金',
            'total_consume' => '总消费',
            'score' => '积分',
            'money' => '余额',
            'createtime' => '注册时间',
            'logintime' => '上次登录',
        ];

        $total = count($idArr);

        $export = new \addons\shopro\library\Export();
        $params = [
            'file_name' => '用户列表',
            'cell_titles' => $cellTitles,
            'total' => $total,
        ];

        $result = $export->export($params, function ($pages) use ($idArr) {
            $ids = array_slice($idArr, ($pages['page'] - 1) * $pages['list_rows'], $pages['list_rows']);

            $datas = $this->model->with(['shopro_user_tag'])
                ->where('id', 'in', $ids)
                ->select();

            $datas = collection($datas)->toArray();

            $newDatas = [];
            foreach ($datas as $user) {
                $newDatas[] = [
                    'id' => $user['id'] ?? '',
                    'username' => $user['username'] ?? '',
                    'nickname' => $user['nickname'] ?? '',
                    'mobile' => $user['mobile'] ?? '',
                    'email' => $user['email'] ?? '',
                    'gender_text' => $user['gender_text'] ?? '',
                    'birthday' => $user['birthday'] ?? '',
                    'status_text' => $user['status_text'] ?? '',
                    'commission' => $user['commission'] ?? '',
                    'total_consume' => $user['total_consume'] ?? '',
                    'score' => $user['score'] ?? '',
                    'money' => $user['money'] ?? '',
                    'createtime' => $user['createtime'] ?? '',
                    'logintime' => $user['logintime'] ?? '',
                ];
            }

            return $newDatas;
        });

        return $result;
    }

}
