package com.happy.action;

import com.baidubce.model.User;
import com.google.gson.Gson;
import com.happy.Model.Booking;
import com.happy.Model.FileInfo;
import com.happy.Model.Hotel;
import com.happy.Model.weixin.*;
import com.happy.Until.*;
import com.happy.Until.Enum.B;
import com.happy.Until.Enum.DataType;
import com.happy.Until.Enum.TempEnum;
import com.happy.common.JwtUtil;
import com.happy.common.http.HttpsClient;
import com.happy.common.wx.WxUtil;
import com.happy.constant.ConstDefault;
import com.happy.constant.ResultStatusCode;
import com.happy.dto.IPage;
import com.happy.service.*;
import com.happy.vo.TokenUsersVo;
import com.happy.vo.UsersVo;
import com.opensymphony.xwork2.ActionSupport;
import net.sf.json.JSONObject;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.*;

/**
 * 我的进去Action请求交互
 */
public class AppMePageAction extends ActionSupport implements ServletRequestAware {

    private HttpServletRequest request;
    public HttpServletResponse response;

    @Resource
    public BookService bookService;
    @Resource
    public UserService userService;
    @Resource
    public AppService appService;
    @Resource
    public HotelService hotelService;
    @Resource
    public FileService fileService;
    @Resource
    public AppHomePageService appHomePageService;

    private String contactUserName; // 常用联系人姓名
    private String contactUserIdNum; // 常用联系人身份证
    private String contactUserPhone; // 常用联系人电话


    public int page = 1; // 当前页
    public int rows = 5;// 每页显示的行数rows
    private String userId; // 用户id
    private String bookingId; // 订单id
    private String userName; // 用户姓名
    private String headPhoto; // 用户头像地址
    private String contactId; // 相关联系人的id
    public String status;
    private String code; // 授权前端给用户code

    private String userCode; // 第一次进来获取用户的code
    private String queryValue; // 首页查寻搜索关键词
    public String type; // 类型：收藏、住过

    public HttpServletRequest getRequest() {
        return request;
    }

    public void setRequest(HttpServletRequest request) {
        this.request = request;
    }

    public void setServletRequest(HttpServletRequest request) {
        this.request = request;
    }

    public HttpServletResponse getResponse() {
        return response;
    }

    public void setResponse(HttpServletResponse response) {
        this.response = response;
    }

    public int getPage() {
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public int getRows() {
        return rows;
    }

    public void setRows(int rows) {
        this.rows = rows;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }


    /**
     * userId
     * 进入我的，查询订单列表
     *
     * @return
     */
    public String getBookingList() {
        if (Func.checkNull(userId))
            return null;
        // 通过用户id查询所有订单列表数据

        StringBuilder querySql = new StringBuilder("");
        querySql.append(" and status_del = 1");
        if (!Func.checkNull(userId)) {
            querySql.append(" and create_userid = '").append(userId).append("' ");
        }

        IPage<Booking> iPage = bookService.queryPage(querySql.toString(), page, rows, "create_time");
        List<Booking> bookList = iPage.getPageList();
        if (bookList != null) {
            for (Booking book : bookList) {
                if (book == null || Func.checkNull(book.getHouseId()))
                    continue;

                // 将房间图片，写入房型对象中
                List<FileInfo> fileInfoList = fileService.queryListByLinkId(book.getHouseId());
                book.setHouseFileInfoList(fileInfoList);
            }
        }

        ResponseUtil.writeJsonIPage(ServletActionContext.getResponse(), iPage);
        return null;
    }

    /**
     * 收藏、住过的酒店列表
     * userId
     * type  收藏、住过
     *
     * @return
     */
    public String getHotelAndUsersList() {
        if (Func.checkNull(userId) || Func.checkNull(type))
            return null;

        Users users = userService.queryByUserId(userId);
        if (users == null)
            return null;

        List<String> collectList = new ArrayList<>();
        List<String> liveList = new ArrayList<>();
        if (!Func.checkNull(users.getCollect_hotel()))
            collectList = Arrays.asList(users.getCollect_hotel().split(","));
        if (!Func.checkNull(users.getLive_hotel()))
            liveList = Arrays.asList(users.getLive_hotel().split(","));

        IPage<Hotel> iPage = new IPage<>();
        if (TempEnum.收藏.name().equals(type)) {
            iPage = appHomePageService.getHotelList(collectList, page, rows);
        } else if (TempEnum.住过.name().equals(type)) {
            iPage = appHomePageService.getHotelList(liveList, page, rows);
        }

        ResponseUtil.writeJsonIPage(ServletActionContext.getResponse(), iPage);
        return null;
    }

    /**
     * 通过订单id查订单数据
     *
     * @return
     */
    public String getBookingById() {
        if (Func.checkNull(bookingId))
            return null;
        // 通过用户id查询所有订单列表数据
        JSONObject resultJson = new JSONObject();
        Booking book = bookService.getById(Func.parseInt(bookingId));
        if (book == null) {
            resultJson.put(B.code, ResultStatusCode.BAD_REQUEST.getStatus());
            resultJson.put(B.message, "查无此数据");
            return null;
        }


        // 数据字典写入book
        Map dicMap = hotelService.queryHotelDicMap();
        // 酒店配置列表数据填充
        if (!Func.checkNull(book.getHotelConfig())) {
            List<String> list = Arrays.asList(book.getHotelConfig().split(","));
            List hotelDicList = new ArrayList();
            for (String hotelDicId : list) {
                if (!dicMap.containsKey(Func.parseInt(hotelDicId)))
                    continue;

                hotelDicList.add(dicMap.get(Func.parseInt(hotelDicId)));
            }
            book.setHotelConfigList(hotelDicList);
        }
        // 房型配置列表数据填充
        if (!Func.checkNull(book.getHouseConfig())) {
            List<String> list = Arrays.asList(book.getHouseConfig().split(","));
            List houseDicList = new ArrayList();
            for (String hotelDicId : list) {
                if (!dicMap.containsKey(Func.parseInt(hotelDicId)))
                    continue;

                houseDicList.add(dicMap.get(Func.parseInt(hotelDicId)));
            }
            book.setHouseConfigList(houseDicList);
        }

        // 将房间图片，写入房型对象中
        List<FileInfo> fileInfoList = fileService.queryListByLinkId(book.getHouseId());
        book.setHouseFileInfoList(fileInfoList);

        /**
         * 未付款订单的实际支付金额为房间总价
         */
        String orderStatus = book.getOrderStatus();
        if (!"2".equals(orderStatus) && !"3".equals(orderStatus) && !"4".equals(orderStatus) && !"5".equals(orderStatus)) {
            book.setPayAccount(book.getHouseTotalPrice());
        }

        resultJson.put(B.code, ResultStatusCode.OK.getStatus());
        resultJson.put(B.message, ResultStatusCode.OK.getMsg());
        resultJson.put(B.data, book);
        ResponseUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
        return null;
    }


    /**
     * userId 当前用户id，获取列表
     * 进入我的页面，跳转常用旅客列表
     */
    public void getUserContactList() {
        // 通过用户id查询所有订单列表数据
        if (Func.checkNull(userId))
            return;

        StringBuilder querySql = new StringBuilder("");
        if (!Func.checkNull(userId)) {
            querySql.append(" and contact_id = '").append(userId).append("' ");
        }
        querySql.append(" and data_type = '").append(DataType.关联数据.toString()).append("' ");

        IPage listPage = userService.queryUserPage(querySql.toString(), page, rows); // 查询分页
        ResponseUtil.writeJsonIPage(ServletActionContext.getResponse(), listPage);
    }

    /**
     * 用户点击设置按钮，获取数据
     * 通过用户id查询用户信息
     */
    public void queryUsersById() {
        if (Func.checkNull(userId))
            return;
        Users users = userService.queryByUserId(userId);

        JSONObject resultJson = new JSONObject();
        resultJson.put(B.code, ResultStatusCode.OK.getStatus());
        resultJson.put(B.message, ResultStatusCode.OK.getMsg());
        resultJson.put(B.data, users);
        ResponseUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());

    }

    /**
     * 通过UserId进行更改或添加数据
     */
    public void updateContact() {
        if (Func.checkNull(contactId))
            return;

        JSONObject resultJson = new JSONObject();
        Users users = userService.queryByUserId(contactId);
        if (users == null) {

            resultJson.put(B.code, ResultStatusCode.BAD_REQUEST.getStatus());
            resultJson.put(B.message, "无此用户数据，请重新查询");
            ResponseUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
            return;
        }

        users.setUser_name(contactUserName);

//        // 验证手机号码
//        if ( !Func.checkPhone(contactUserPhone))
//        {
//            resultJson.put(B.code,ResponseStatusEnum.FAILED.getStatus());
//            resultJson.put(B.message,"请确认手机号码");
//            ResponseUtil.writeJson(ServletActionContext.getResponse(),resultJson.toString());
//            return;
//        }
//        // 验证身份证
//        if (!Func.isCard(contactUserIdNum))
//        {
//            resultJson.put(B.code,ResponseStatusEnum.FAILED.getStatus());
//            resultJson.put(B.message,"请确认身份证");
//            ResponseUtil.writeJson(ServletActionContext.getResponse(),resultJson.toString());
//            return;
//        }

        users.setUser_phone(contactUserPhone);
        users.setCard_number(contactUserIdNum);
        userService.update(users);

        resultJson.put(B.code, ResultStatusCode.OK.getStatus());
        resultJson.put(B.message, ResultStatusCode.OK.getMsg());
        ResponseUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
    }

    /**
     * 添加常用联系人数据
     */
    public void AddContact() {
        if (Func.checkNullOrEmpty(userId))
            return;

        // 相关联系人
        Users users = new Users();
        users.setContactId(Func.parseStr(userId));
        users.setContactName(userName);
        users.setCreate_time(TimeExchange.getDate());
        users.setDataType(DataType.关联数据.toString());
        users.setUser_name(contactUserName);    // 相关联系人的名字
        users.setUser_phone(contactUserPhone);  // 相关联系人的手机号码
        users.setCard_number(contactUserIdNum); // 相关联系人的身份证
        userService.insert(users);

        JSONObject resultJson = new JSONObject();
        resultJson.put(B.code, ResultStatusCode.OK.getStatus());
        resultJson.put(B.message, ResultStatusCode.OK.getMsg());
        ResponseUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
    }

    /**
     * 用户点击保存，更新用户信息
     */
    public void updateUserInfo() {
        if (Func.checkNullOrEmpty(userId))
            return;

        JSONObject resultJson = new JSONObject();
        Users users = userService.queryByUserId(userId);
        if (users == null) {
            resultJson.put(B.code, ResultStatusCode.BAD_REQUEST.getStatus());
            resultJson.put(B.message, "查无此用户数据，请先授权!");
            ResponseUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
            return;
        }

        users.setHeadPhoto(headPhoto);
        users.setUser_name(userName);
        users.setDataType(DataType.游客数据.toString());
        userService.update(users);

        resultJson.put(B.code, ResultStatusCode.OK.getStatus());
        resultJson.put(B.message, ResultStatusCode.OK.getMsg());
        ResponseUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
        return;
    }

    /**
     * contactId
     * 用户可以删除自己相关联系人
     */
    public void delContact() {
        if (Func.checkNull(contactId))
            return;

        JSONObject resultJson = new JSONObject();
        userService.del(Func.parseInt(contactId));

        resultJson.put(B.code, ResultStatusCode.OK.getStatus());
        resultJson.put(B.message, ResultStatusCode.OK.getMsg());
        ResponseUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
    }

    /**
     * 判断是否有当前用户（加访问记录）
     */
    public String isHaveUser() {
        if (Func.checkNull(this.code))
            return null;

        String OPEN_ID = "";
        JSONObject resultJson = new JSONObject();
        // 此处授权后的回调地址，主要获取token和openid
        String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
                + WeiXinUtil.appid_c
                + "&secret="
                + WeiXinUtil.screct_c
                + "&code="
                + this.getCode() + "&grant_type=authorization_code";

        // String json = HttpUtils.get(requestUrl);
        String json = HttpsClient.sendPost(requestUrl, "");
        Wechat_userinfo result = new Gson().fromJson(json, Wechat_userinfo.class);
        OPEN_ID = result.getOpenid();
        if (Func.checkNull(OPEN_ID)) {
            resultJson.put(B.code, ResultStatusCode.BAD_REQUEST.getStatus());
            resultJson.put(B.message, "未获取到OpenId");
            ResponseUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
            return null;
        }

        /*
         *  手机号前端过来，昵称、省份、性别等其他信息已保存的result中，
         * 查询用户openid是否存在，存在就返回信息给前端，不存在就保存到数据库
         * */
        Users users = userService.queryByOpenid(OPEN_ID);
        if (users == null) {
            resultJson.put(B.code, ResultStatusCode.BAD_REQUEST.getStatus());
            resultJson.put(B.message, " 当前用户未授权");
            resultJson.put(B.data, users);
            ResponseUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
            return null;
        }

        resultJson.put(B.code, ResultStatusCode.OK.getStatus());
        resultJson.put(B.message, " 当前用户已授权");
        resultJson.put(B.data, users);
        ResponseUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
        return null;

    }

    /**
     * 用户登录小程序授权
     */
    public void authorizationUser() {
        if (Func.checkNull(this.code))
            return;

        String OPEN_ID = "";
        JSONObject resultJson = new JSONObject();
        CodeEntity codeEntity = appService.getCodeInfo(code);
        OPEN_ID = codeEntity.getOpenid();
        if (Func.checkNull(OPEN_ID)) {
            resultJson.put(B.code, ResultStatusCode.BAD_REQUEST.getStatus());
            resultJson.put(B.message, "未获取到OpenId");
            ResponseUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
        }

        /*
         *  手机号前端过来，昵称、省份、性别等其他信息已保存的result中，
         * 查询用户openid是否存在，存在就返回信息给前端，不存在就保存到数据库
         * */
        Users users = userService.queryByOpenid(OPEN_ID);
        if (users == null) {
            users = new Users();
            // 确定默认用户名，默认用户头像
            String userName = Func.parseStr(WxUtil.createDefaultUserName());
            users.setUser_name(userName);
            users.setHeadPhoto(ConstDefault.DefaultHeadPhoto);
            users.setOpenid(OPEN_ID);
            users.setCreate_time(DateUtil.getFormatPaternDate(new Date()));
            users.setDataType(DataType.游客数据.toString());
            userService.insert(users); // 写入用户数据

            users = userService.queryByOpenid(OPEN_ID);
        }

        /**
         * 2023-11-15 A-jax 添加token
         */
        String token = AesUtils.encrypt(String.valueOf(users.getId()));
        UsersVo result = new UsersVo();
        result.setId(users.getId());
        result.setCard_number(users.getCard_number());
        result.setUser_name(users.getUser_name());
        result.setUser_phone(users.getUser_phone());
        result.setUser_zz(users.getUser_zz());
        result.setOpenid(users.getOpenid());
        result.setCreate_time(users.getCreate_time());
        result.setRemark(users.getRemark());
        result.setIdentity_type(users.getIdentity_type());
        result.setContactId(users.getContactId());
        result.setContactName(users.getContactName());
        result.setDataType(users.getDataType());
        result.setHeadPhoto(users.getHeadPhoto());
        result.setCollect_hotel(users.getCollect_hotel());
        result.setLive_hotel(users.getLive_hotel());
        result.setToken(token);

        resultJson.put(B.code, ResultStatusCode.OK.getStatus());
        resultJson.put(B.message, ResultStatusCode.OK.getMsg());
        resultJson.put(B.data, result);
        ResponseUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
        return;
    }

    /**
     * 根据token获取用户ID
     * @return
     */
    public String getUserInfo(){
        String token = request.getHeader("token");
        JSONObject resultJson = new JSONObject();
        if(token == null){
            resultJson.put(B.code, ResultStatusCode.BAD_REQUEST.getStatus());
            resultJson.put(B.message, "token不能为空");
            ResponseUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
            return null;
        }

        String userId = null;
        try{
            userId = AesUtils.decrypt(token);
        }catch (Exception e){
            resultJson.put(B.code, ResultStatusCode.BAD_REQUEST.getStatus());
            resultJson.put(B.message, "token不合法，无法获取用户信息");
            ResponseUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
            return null;
        }


        if(userId == null){
            resultJson.put(B.code, ResultStatusCode.BAD_REQUEST.getStatus());
            resultJson.put(B.message, "token已失效，无法获取用户信息");
            ResponseUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
            return null;
        }

        Users user = userService.queryByUserId(userId);
        if(user == null){
            resultJson.put(B.code, ResultStatusCode.BAD_REQUEST.getStatus());
            resultJson.put(B.message, "用户信息查询失败");
            ResponseUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
            return null;
        }

        TokenUsersVo result = new TokenUsersVo();
        result.setId(user.getId());
        result.setUserName(user.getUser_name());
        result.setUserPhone(user.getUser_phone());
        result.setHeadPhoto(user.getHeadPhoto());
        result.setOpenId(user.getOpenid());

        resultJson.put(B.code, ResultStatusCode.OK.getStatus());
        resultJson.put(B.message, ResultStatusCode.OK.getMsg());
        resultJson.put(B.data, result);
        ResponseUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
        return null;
    }

    public String getUserCode() {
        return userCode;
    }

    public void setUserCode(String userCode) {
        this.userCode = userCode;
    }

    public String getQueryValue() {
        return queryValue;
    }

    public void setQueryValue(String queryValue) {
        this.queryValue = queryValue;
    }

    public String getContactUserName() {
        return contactUserName;
    }

    public void setContactUserName(String contactUserName) {
        this.contactUserName = contactUserName;
    }

    public String getContactUserIdNum() {
        return contactUserIdNum;
    }

    public void setContactUserIdNum(String contactUserIdNum) {
        this.contactUserIdNum = contactUserIdNum;
    }

    public String getContactUserPhone() {
        return contactUserPhone;
    }

    public void setContactUserPhone(String contactUserPhone) {
        this.contactUserPhone = contactUserPhone;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getContactId() {
        return contactId;
    }

    public void setContactId(String contactId) {
        this.contactId = contactId;
    }

    public String getHeadPhoto() {
        return headPhoto;
    }

    public void setHeadPhoto(String headPhoto) {
        this.headPhoto = headPhoto;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getBookingId() {
        return bookingId;
    }

    public void setBookingId(String bookingId) {
        this.bookingId = bookingId;
    }
}
