import 'package:flutter/material.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:flutter_slidable_demo/models/user_model.dart';

/// Description: home page
/// Time       : 05/26/2023 Friday
/// Author     : liuyuqi.gov@msn.cn
class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  List<UserModel> userList = [
    UserModel(id: 1, name: "User 1", email: "aa@qq.com", password: "123456"),
    UserModel(id: 2, name: "User 2", email: "bb@qq.com", password: "123456")
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text("Slidable Demo"),
        ),
        body: ListView.builder(
            itemBuilder: _itemBuilder, itemCount: userList.length));
  }

  Widget _itemBuilder(BuildContext context, int index) {
    return Container(
      margin: const EdgeInsets.all(5.0),
      child: Slidable(
        key: Key(userList[index].toString()),
        startActionPane: const ActionPane(
          openThreshold: 0.1,
          closeThreshold: 0.4,
          motion: BehindMotion(),
          children: [
            SlideAction(color: Colors.green, icon: Icons.share),
            SlideAction(color: Colors.amber, icon: Icons.delete),
          ],
        ),
        endActionPane: const ActionPane(
          motion: BehindMotion(),
          children: [
            SlideAction(color: Colors.red, icon: Icons.delete_forever),
            SlideAction(color: Colors.blue, icon: Icons.alarm, flex: 2),
          ],
        ),
        child: Container(
          height: 80,
          width: double.infinity,
          color: Colors.blue,
          alignment: Alignment.center,
          child: Text(
            "product${userList[index].name}",
            style: const TextStyle(color: Colors.white),
          ),
        ),
      ),
    );
  }

  /// 弹出对话框
  showToast(String s) {
    showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            content: Text(s),
          );
        });
  }
}

class SlideAction extends StatelessWidget {
  const SlideAction({
    Key? key,
    required this.color,
    required this.icon,
    this.flex = 1,
  }) : super(key: key);

  final Color color;
  final IconData icon;
  final int flex;

  @override
  Widget build(BuildContext context) {
    return SlidableAction(
      flex: flex,
      backgroundColor: color,
      foregroundColor: Colors.white,
      onPressed: (_) {
        print(icon);
      },
      icon: icon,
      label: 'hello',
    );
  }
}