import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutterappfuyou/code/base/YSNetWorking.dart';
import 'package:flutterappfuyou/code/base/YSTools.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'base/YSBase.dart';

import 'YSQuestionDetail.dart';

class YSQuestion extends StatefulWidget {
  @override
  _YSQuestionState createState() => _YSQuestionState();
}

class _YSQuestionState extends State<YSQuestion> {
  int _selected = 0;
  PageController _page = PageController();
  ScrollController _scrollPage1 = ScrollController();
  ScrollController _scrollPage2 = ScrollController();
  int _index = 1;
  String searchStr = '';
  List _dataArray = [];
  List _policyArray = [];
  int _policyIndex = 1;
  @override
  void initState() {
    Future.delayed(Duration(seconds: 0)).then((value){
      this._refreshData();
      _scrollPage1.addListener(() {
        if(_scrollPage1.position.pixels == _scrollPage1.position.maxScrollExtent){
          this._loadMoreData();
        }
      });
      _scrollPage2.addListener(() {
        if(_scrollPage2.position.pixels == _scrollPage2.position.maxScrollExtent){
          this._loadMorePolicyData();
        }
      });
    });
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return YSBase(
      ystitle: '问题大厅',
      ysright: PopupMenuButton<String>(
        padding: EdgeInsets.all(0),
        icon: Icon(Icons.more_horiz,color: Colors.white,),
        onSelected: (value){
          Navigator.of(context).push(
            CupertinoPageRoute(
              builder: (context){
                if(value == '我的提问'){
                  return YSSift(type: 1,);
                }else{
                  return YSSift(type: 2,);
                }
              }
            )
          );
        },
        itemBuilder: (context) {
          return <PopupMenuEntry<String>>[
            PopupMenuItem<String>(
              value: '我的提问',
              child: Text('我的提问',style: TextStyle(fontSize: 14,color: Color(0xFF292929)),),
            ),
            PopupMenuItem<String>(
              value: '我的收藏',
              child: Text('我的收藏',style: TextStyle(fontSize: 14,color: Color(0xFF292929)),),
            ),
          ];
        },
      ),
      yschild: SingleChildScrollView(
        child: Column(
          children: [
            Container(
              height: 50,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.only(topRight: Radius.circular(20),topLeft: Radius.circular(20)),
              ),
              padding: EdgeInsets.only(left: 20,right: 20,top: 10,bottom: 10),
              child: CupertinoTextField(
                placeholder: '搜索',
                textAlign: TextAlign.center,
                style: TextStyle(fontSize: 14,color: Color(0xFF808080),decoration: TextDecoration.none),
                placeholderStyle: TextStyle(fontSize: 14,color: Color(0xFF808080),decoration: TextDecoration.none),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.all(Radius.circular(15)),
                  color: Color(0xFFF5F3F0)
                ),
                textInputAction: TextInputAction.search,
                onSubmitted: (value){
                  if(value!=null){
                    searchStr = value;
                    _selected==0?_refreshData():_refreshPolicyData();
                  }
                },
              ),
            ),
            Container(
              height: 25,
              color: Colors.white,
              padding: EdgeInsets.only(left: 10,right: 10),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Row(
                    children: [
                      GestureDetector(
                        onTap: (){
                          _refreshData();
                          _selected = 0;
                          _page.jumpToPage(0);
                        },
                        child: Container(
                          margin: EdgeInsets.only(left: 5,right: 5),
                          child: Text(' 问专家',style: TextStyle(color: Color(0xFF7F3344),fontSize: 13,decoration: TextDecoration.none,fontWeight: FontWeight.w600),),
                        ),
                      ),
                      GestureDetector(
                        onTap: (){
                          _refreshPolicyData();
                          _selected = 1;
                          _page.jumpToPage(1);
                        },
                        child: Text(' 问政策',style: TextStyle(color: Color(0xFF7F3344),fontSize: 13,decoration: TextDecoration.none,fontWeight: FontWeight.w600),),
                      ),
                    ],
                  ),
                  Container(height: 2,width: 30,color: Color(0xFF7F3344),margin: EdgeInsets.only(left: _selected==0?15:60),),
                ],
              ),
            ),
            Container(
              height: MediaQuery.of(context).size.height-150,
              child: PageView(
                controller: _page,
                onPageChanged: (index){
                  index==0?_refreshData():_refreshPolicyData();
                  _selected = index;
                },
                children: [
                  Container(
                    height: MediaQuery.of(context).size.height-150,
                    child: RefreshIndicator(
                      onRefresh: _refreshData,
                      color: Color(0xFFDB5278),
                      child: ListView.separated(
                        controller: _scrollPage1,
                        physics: AlwaysScrollableScrollPhysics(),
                        itemBuilder: (context,index){
                          return GestureDetector(
                            onTap: (){
                              Navigator.of(context).push(
                                  CupertinoPageRoute(
                                      builder: (context){
                                        return YSQuestionDetail(questionId: _dataArray[index]['id'],isPolicy: _dataArray[index]['type']=='policy',);
                                      }
                                  )
                              );
                            },
                            child: Container(
                              margin: EdgeInsets.only(left: 5,right: 5),
                              padding: EdgeInsets.all(15),
                              height: 160,
                              decoration: BoxDecoration(
                                  color: Colors.white,
                                  borderRadius: BorderRadius.all(Radius.circular(6))
                              ),
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: [
                                  Row(
                                    children: [
                                      Container(
                                        height: 35,
                                        width: 35,
                                        decoration: BoxDecoration(
                                          color: Color(0xFFF5F3F0),
                                          borderRadius: BorderRadius.all(Radius.circular(17.5)),
                                          image: DecorationImage(image: NetworkImage('${_dataArray[index]['doctor_avatar']}'),fit: BoxFit.fill)
                                        ),
                                      ),
                                      Container(
                                        margin: EdgeInsets.only(left: 10),
                                        width: MediaQuery.of(context).size.width-85,
                                        child: Text('${_dataArray[index]['doctor_name']}医生  解答了该问题',style: TextStyle(fontSize: 14,color: Color(0xFF666666)),overflow: TextOverflow.ellipsis,),
                                      )
                                    ],
                                  ),
                                  Container(
                                    width: MediaQuery.of(context).size.width-40,
                                    child: Text('问：${_dataArray[index]['question_body']}',style: TextStyle(fontSize: 14,color: Color(0xFF292929)),overflow: TextOverflow.ellipsis,),
                                  ),
                                  Container(
                                    width: MediaQuery.of(context).size.width-40,
                                    child: _dataArray[index]['answer_type']=='voice'?Row(
                                      children: [
                                        Text('医生解答：',style: TextStyle(fontSize: 14,color: Color(0xFF428B8D)),overflow: TextOverflow.ellipsis,),
                                        Container(
                                          height: 26,
                                          width: 59,
                                          decoration: BoxDecoration(
                                              color: Color(0xFFF5F3F0),
                                              borderRadius: BorderRadius.all(Radius.circular(4))
                                          ),
                                          alignment: Alignment.center,
                                          child: Stack(
                                            children: [
                                              Row(
                                                children: [
                                                  Container(
                                                    child: Image.asset('lib/images/voice2.png'),
                                                    height: 15,
                                                    width: 15,
                                                    margin: EdgeInsets.only(left: 10,right: 5),
                                                  ),
                                                  Text('4',style: TextStyle(fontSize: 14,color: Color(0xFF428B8D)),overflow: TextOverflow.ellipsis,),
                                                ],
                                              )
                                            ],
                                          ),
                                        )
                                      ],
                                    ):Text('医生解答：${(_dataArray[index]['answer_body'])??''}',style: TextStyle(fontSize: 14,color: Color(0xFF428B8D)),overflow: TextOverflow.ellipsis,),
                                  ),
                                  Container(
                                    width: MediaQuery.of(context).size.width,
                                    height: 1.5,
                                    child: Image.asset('lib/images/line.png'),
                                  ),
                                  Row(
                                    children: [
                                      Container(
                                        width: MediaQuery.of(context).size.width-85,
                                        child: Text('${_dataArray[index]['question_time']}',style: TextStyle(fontSize: 12,color: Color(0xFF808080)),overflow: TextOverflow.ellipsis,),
                                      ),
                                      GestureDetector(
                                        child: Image(height: 15,width: 15,image: AssetImage(_dataArray[index]['is_favorite']==false?'lib/images/uncollection.png':'lib/images/collection.png'),),
                                        onTap: (){
                                          _postCollectionData(index,false);
                                        },
                                      )
                                    ],
                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                  )
                                ],
                              ),
                            ),
                          );
                        },
                        separatorBuilder: (context,index){
                          return Divider(height: 5,thickness: 5,color: Color(0xFFF5F3F0),);
                        },
                        itemCount: _dataArray.length,
                        padding: EdgeInsets.only(top: 5,bottom: 5),
                      ),
                    ),
                  ),
                  Container(
                    height: MediaQuery.of(context).size.height-150,
                    child: RefreshIndicator(
                      onRefresh: _refreshPolicyData,
                      child: ListView.separated(
                        controller: _scrollPage2,
                        itemBuilder: (context,index){
                          return GestureDetector(
                            onTap: (){
                              Navigator.of(context).push(
                                  CupertinoPageRoute(
                                      builder: (context){
                                        return YSQuestionDetail(questionId: _policyArray[index]['id'],isPolicy: _policyArray[index]['type']=='policy',);
                                      }
                                  )
                              );
                            },
                            child: Container(
                              margin: EdgeInsets.only(left: 5,right: 5),
                              padding: EdgeInsets.all(15),
                              height: 160,
                              decoration: BoxDecoration(
                                  color: Colors.white,
                                  borderRadius: BorderRadius.all(Radius.circular(6))
                              ),
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: [
                                  Row(
                                    children: [
                                      Container(
                                        height: 35,
                                        width: 35,
                                        decoration: BoxDecoration(
                                            color: Color(0xFFF5F3F0),
                                            borderRadius: BorderRadius.all(Radius.circular(17.5)),
                                            image: DecorationImage(image: NetworkImage('${_policyArray[index]['doctor_avatar']}'),fit: BoxFit.fill)
                                        ),
                                      ),
                                      Container(
                                        margin: EdgeInsets.only(left: 10),
                                        width: MediaQuery.of(context).size.width-85,
                                        child: Text('${_policyArray[index]['doctor_name']}医生  解答了该问题',style: TextStyle(fontSize: 14,color: Color(0xFF666666)),overflow: TextOverflow.ellipsis,),
                                      )
                                    ],
                                  ),
                                  Container(
                                    width: MediaQuery.of(context).size.width-40,
                                    child: Text('问：${_policyArray[index]['question_body']}',style: TextStyle(fontSize: 14,color: Color(0xFF292929)),overflow: TextOverflow.ellipsis,),
                                  ),
                                  Container(
                                    width: MediaQuery.of(context).size.width-40,
                                    child: _policyArray[index]['answer_type']=='voice'?Row(
                                      children: [
                                        Text('医生解答：',style: TextStyle(fontSize: 14,color: Color(0xFF428B8D)),overflow: TextOverflow.ellipsis,),
                                        Container(
                                          height: 26,
                                          width: 59,
                                          decoration: BoxDecoration(
                                              color: Color(0xFFF5F3F0),
                                              borderRadius: BorderRadius.all(Radius.circular(4))
                                          ),
                                          alignment: Alignment.center,
                                          child: Stack(
                                            children: [
                                              Row(
                                                children: [
                                                  Container(
                                                    child: Image.asset('lib/images/voice2.png'),
                                                    height: 15,
                                                    width: 15,
                                                    margin: EdgeInsets.only(left: 10,right: 5),
                                                  ),
                                                  Text('4',style: TextStyle(fontSize: 14,color: Color(0xFF428B8D)),overflow: TextOverflow.ellipsis,),
                                                ],
                                              )
                                            ],
                                          ),
                                        )
                                      ],
                                    ):Text('医生解答：${(_policyArray[index]['answer_body'])??''}',style: TextStyle(fontSize: 14,color: Color(0xFF428B8D)),overflow: TextOverflow.ellipsis,),
                                  ),
                                  Container(
                                    width: MediaQuery.of(context).size.width,
                                    height: 1.5,
                                    child: Image.asset('lib/images/line.png'),
                                  ),
                                  Row(
                                    children: [
                                      Container(
                                        width: MediaQuery.of(context).size.width-85,
                                        child: Text('${_policyArray[index]['created_at']}',style: TextStyle(fontSize: 12,color: Color(0xFF808080)),overflow: TextOverflow.ellipsis,),
                                      ),
                                     // GestureDetector(
                                     //   child: Image(height: 15,width: 15,image: AssetImage(_policyArray[index]['is_favorite']==true?'lib/images/collection.png':'lib/images/uncollection.png'),),
                                     //   onTap: (){
                                     //     _postCollectionData(index,true);
                                     //   },
                                     // )
                                    ],
                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                  )
                                ],
                              ),
                            ),
                          );
                        },
                        separatorBuilder: (context,index){
                          return Divider(height: 5,thickness: 5,color: Color(0xFFF5F3F0),);
                        },
                        itemCount: _policyArray.length,
                        padding: EdgeInsets.only(top: 5,bottom: 5),
                        physics: AlwaysScrollableScrollPhysics(),
                      ),
                    ),
                  )
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Future<void> _refreshData() async{
    SharedPreferences prefer = await SharedPreferences.getInstance();
    Map request = Map();
    _index = 1;
    request['page'] = _index;
    request['category_id'] = prefer.getInt('chapters')+1;
    request['title'] = searchStr;
    Map dict = await ysRequestHttpNoLoading(context, requestType.post, 'question/openQuestion', request);
    if(dict!=null){
      setState(() {
        _dataArray = dict['data']['datas'];
      });
    }
  }

  Future<void> _loadMoreData() async{
    SharedPreferences prefer = await SharedPreferences.getInstance();
    Map request = Map();
    _index++;
    request['page'] = _index;
    request['category_id'] = prefer.getInt('chapters')+1;
    request['title'] = searchStr;
    Map dict = await ysRequestHttp(context, requestType.post, 'question/openQuestion', request);
    if(dict!=null){
      setState(() {
        _dataArray.addAll(dict['data']['datas']);
      });
    }
  }

  Future<void> _refreshPolicyData() async{
    Map request = Map();
    _policyIndex = 1;
    request['page'] = _policyIndex;
    request['title'] = searchStr;
    Map dict = await ysRequestHttpNoLoading(context, requestType.get, 'policy/list', request);
    if(dict!=null){
      setState(() {
        _policyArray = dict['data'];
      });
    }
  }

  Future<void> _loadMorePolicyData() async{
    Map request = Map();
    _policyIndex++;
    request['page'] = _policyIndex;
    request['title'] = searchStr;
    Map dict = await ysRequestHttp(context, requestType.get, 'policy/list', request);
    if(dict!=null){
      setState(() {
        _policyArray.addAll(dict['data']);
      });
    }
  }

  _postCollectionData(int index,bool isPolicy) async{
    Map dict = await ysRequestHttpNoLoading(context, requestType.post, 'question/favorite', {'question_id':isPolicy==true?_policyArray[index]['id']:_dataArray[index]['id']});
    if(dict!=null){
      setState(() {
        isPolicy==true?_policyArray[index]['is_favorite'] = dict['data']['is_favorite']:_dataArray[index]['is_favorite'] = dict['data']['is_favorite'];
      });
    }
  }
}

class YSSift extends StatefulWidget {
  final int type;
  const YSSift({Key key, this.type}) : super(key: key);
  @override
  _YSSiftState createState() => _YSSiftState();
}

class _YSSiftState extends State<YSSift> {
  String searchStr = '';
  int _index = 1;
  List _dataArray = [];
  ScrollController _scroll = ScrollController();
  @override
  void initState() {
    Future.delayed(Duration(seconds: 0)).then((value){
      this._refreshData();
      _scroll.addListener(() {
        if(_scroll.position.pixels == _scroll.position.maxScrollExtent){
          this._loadMoreData();
        }
      });
    });
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return YSBase(
      ystitle: widget.type==1?'我的提问':'收藏列表',
      yschild: SingleChildScrollView(
        child: Column(
          children: [
            widget.type==1?Container(
              height: 50,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.only(topRight: Radius.circular(20),topLeft: Radius.circular(20)),
              ),
              padding: EdgeInsets.only(left: 20,right: 20,top: 10,bottom: 10),
              child: CupertinoTextField(
                placeholder: '搜索',
                textAlign: TextAlign.center,
                style: TextStyle(fontSize: 14,color: Color(0xFF808080),decoration: TextDecoration.none),
                placeholderStyle: TextStyle(fontSize: 14,color: Color(0xFF808080),decoration: TextDecoration.none),
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.all(Radius.circular(15)),
                    color: Color(0xFFF5F3F0)
                ),
                textInputAction: TextInputAction.search,
                onSubmitted: (value){
                  if(value!=null){
                    searchStr = value;
                    _refreshData();
                  }
                },
              ),
            ):Container(),
            Container(
              height: widget.type==1?MediaQuery.of(context).size.height-150:MediaQuery.of(context).size.height-75,
              child: _dataArray.length==0?Container(
                alignment: Alignment.center,
                child: Image.asset('lib/images/none.png',height: 200,width: 200,),
              ):ListView.separated(
                itemBuilder: (context,index){
                  return GestureDetector(
                    onTap: (){
                      Navigator.of(context).push(
                          CupertinoPageRoute(
                              builder: (context){
                                return YSQuestionDetail(questionId: _dataArray[index]['id'],isPolicy: _dataArray[index]['type']=='policy',);
                              }
                          )
                      );
                    },
                    child: Container(
                      margin: EdgeInsets.only(left: 5,right: 5),
                      padding: EdgeInsets.all(15),
                      height: 160,
                      decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.all(Radius.circular(6))
                      ),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Row(
                            children: [
                              Container(
                                height: 35,
                                width: 35,
                                decoration: BoxDecoration(
                                    color: Color(0xFFF5F3F0),
                                    borderRadius: BorderRadius.all(Radius.circular(17.5)),
                                    image: DecorationImage(image: NetworkImage('${_dataArray[index]['doctor_avatar']}'),fit: BoxFit.fill)
                                ),
                              ),
                              Container(
                                margin: EdgeInsets.only(left: 10),
                                width: MediaQuery.of(context).size.width-85,
                                child: Text('${_dataArray[index]['doctor_name']}医生  解答了该问题',style: TextStyle(fontSize: 14,color: Color(0xFF666666)),overflow: TextOverflow.ellipsis,),
                              )
                            ],
                          ),
                          Container(
                            width: MediaQuery.of(context).size.width-40,
                            child: Text('问：${_dataArray[index]['question_title']}',style: TextStyle(fontSize: 14,color: Color(0xFF292929)),overflow: TextOverflow.ellipsis,),
                          ),
                          Container(
                            width: MediaQuery.of(context).size.width-40,
                            child: _dataArray[index]['answer_type']=='voice'?Row(
                              children: [
                                Text('医生解答：',style: TextStyle(fontSize: 14,color: Color(0xFF428B8D)),overflow: TextOverflow.ellipsis,),
                                Container(
                                  height: 26,
                                  width: 59,
                                  decoration: BoxDecoration(
                                      color: Color(0xFFF5F3F0),
                                      borderRadius: BorderRadius.all(Radius.circular(4))
                                  ),
                                  alignment: Alignment.center,
                                  child: Stack(
                                    children: [
                                      Row(
                                        children: [
                                          Container(
                                            child: Image.asset('lib/images/voice2.png'),
                                            height: 15,
                                            width: 15,
                                            margin: EdgeInsets.only(left: 10,right: 5),
                                          ),
                                          Text('4',style: TextStyle(fontSize: 14,color: Color(0xFF428B8D)),overflow: TextOverflow.ellipsis,),
                                        ],
                                      )
                                    ],
                                  ),
                                )
                              ],
                            ):Text('医生解答：${(_dataArray[index]['answer_body'])??''}',style: TextStyle(fontSize: 14,color: Color(0xFF428B8D)),overflow: TextOverflow.ellipsis,),
                          ),
                          Container(
                            width: MediaQuery.of(context).size.width,
                            height: 1.5,
                            child: Image.asset('lib/images/line.png'),
                          ),
                          Row(
                            children: [
                              Container(
                                width: MediaQuery.of(context).size.width-85,
                                child: Text('${_dataArray[index]['question_time']??_dataArray[index]['created_at']??''}',style: TextStyle(fontSize: 12,color: Color(0xFF808080)),overflow: TextOverflow.ellipsis,),
                              ),
                              GestureDetector(
                                child: Image(height: 15,width: 15,image: AssetImage(_dataArray[index]['is_favorite']==false?'lib/images/uncollection.png':'lib/images/collection.png'),),
                                onTap: (){
                                  _postCollectionData(index,false);
                                },
                              )
                            ],
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          )
                        ],
                      ),
                    ),
                  );
                },
                separatorBuilder: (context,index){
                  return Divider(height: 5,thickness: 5,color: Color(0xFFF5F3F0),);
                },
                itemCount: _dataArray.length,
                padding: EdgeInsets.only(top: 5,bottom: 5),
              ),
            )
          ],
        ),
      ),
    );
  }

  Future<void> _refreshData() async{
    Map request = Map();
    _index = 1;
    request['page'] = _index;
    if(widget.type==1){
      request['title'] = searchStr;
    }
    Map dict = await ysRequestHttpNoLoading(context, widget.type==1?requestType.post:requestType.get, widget.type==1?'question/selfQuestion':'question/favoriteList', request);
    if(dict!=null){
      setState(() {
        _dataArray = dict['data']['datas']??[];
      });
    }
  }

  Future<void> _loadMoreData() async{
    Map request = Map();
    _index++;
    request['page'] = _index;
    if(widget.type==1){
      request['title'] = searchStr;
    }
    Map dict = await ysRequestHttpNoLoading(context, widget.type==1?requestType.post:requestType.get, widget.type==1?'question/selfQuestion':'question/favoriteList', request);
    if(dict!=null){
      setState(() {
        _dataArray.addAll(dict['data']['datas']??[]);
      });
    }
  }

  _postCollectionData(int index,bool isPolicy) async{
    Map dict = await ysRequestHttpNoLoading(context, requestType.post, 'question/favorite', {'question_id':_dataArray[index]['id']});
    if(dict!=null){
      setState(() {
        _dataArray[index]['is_favorite'] = dict['data']['is_favorite'];
      });
    }
  }
}



