package com.happy.action;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.happy.Model.*;
import com.happy.Model.app.Around_product;
import com.happy.Model.app.Arounds;
import com.happy.Until.GetHttpParam;
import com.happy.Until.ResUtil;
import com.happy.Until.ResponseUtil;
import com.happy.Until.TimeExchange;
import com.happy.service.*;
import com.opensymphony.xwork2.ActionSupport;
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.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

public class advertiseAction extends ActionSupport implements ServletRequestAware {

    private HttpServletRequest request;
    public HttpServletResponse response;

    @Resource
    public AdvertiseService advertiseService;
    @Resource
    public AdminManagerService adminManagerService;
    @Resource
    public HotelService hotelService;
    @Resource
    public ArticleTweetService articleTweetService;
    @Resource
    public HotelDictService hotelDictService;

    public Integer id;
    public int page; // 当前页
    public int rows;// 每页显示的行数rows
    public String title;
    public Integer state;
    public String startTime;
    public String endTime;

    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 Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    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 getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public Integer getState() {
        return state;
    }

    public void setState(Integer state) {
        this.state = state;
    }

    public String getStartTime() {
        return startTime;
    }

    public void setStartTime(String startTime) {
        this.startTime = startTime;
    }

    public String getEndTime() {
        return endTime;
    }

    public void setEndTime(String endTime) {
        this.endTime = endTime;
    }

    public String insert() {
        JSONObject resultjson = new JSONObject();
        Gson gson = new Gson();
        com.alibaba.fastjson.JSONObject json = GetHttpParam.getHttpParam(request);
        System.out.println(json);
        if (json == null) {
            resultjson.put("message", "请传入参数");
            ResUtil.writeJson(ServletActionContext.getResponse(), resultjson.toString());
            return null;
        }
        Advertise advertise = null;
        try {
            advertise = gson.fromJson(json.toString(), new TypeToken<Advertise>() {}.getType());
            if (advertise == null) {
                resultjson.put("message", "数据为空");
                resultjson.put("code", 500);
                ResUtil.writeJson(ServletActionContext.getResponse(), resultjson.toString());
                return null;
            }
            if (advertise.getTitle()==null || advertise.getLogoUrl()==null || advertise.getImageUrl()==null || advertise.getJumpWay()==null || advertise.getJumpDirection()==null || advertise.getJumpPoint()==null){
                resultjson.put("message", "各参数不能为空");
                resultjson.put("code", 500);
                ResUtil.writeJson(ServletActionContext.getResponse(), resultjson.toString());
                return null;
            }
            Advertise listc = advertiseService.queryByTitle(advertise.getTitle());
            if (listc != null) {
                resultjson.put("message", "该广告已存在");
                resultjson.put("code", 500);
                ResUtil.writeJson(ServletActionContext.getResponse(), resultjson.toString());
                return null;
            }
            List<Advertise> open = advertiseService.queryOpenAdvertise();
            if (open!=null){
                List<Integer> ids = open.stream().map(Advertise::getId).collect(Collectors.toList());
                if (open.size()>=3 && !ids.contains(advertise.getId()) && advertise.getState()==1){
                    resultjson.put("message", "最多开启三个广告");
                    resultjson.put("code", 500);
                    ResUtil.writeJson(ServletActionContext.getResponse(), resultjson.toString());
                    return null;
                }
            }
            advertise.setCreateTime(TimeExchange.getTime());
            if (advertise.getJumpWay().equals("小程序") && advertise.getJumpDirection().equals("攻略") && !advertise.getJumpPoint().equals("首页")){
                ArticleTweet articleTweet = articleTweetService.queryArticleById(advertise.getJumpPoint(),null);
                advertise.setTownId(articleTweet.getLocationId());
            }
            if (advertise.getJumpWay().equals("小程序") && advertise.getJumpDirection().equals("民宿") && !advertise.getJumpPoint().equals("首页")){
                AdminManager adminManager = adminManagerService.getById(Integer.parseInt(advertise.getJumpPoint()));
                HotelDict hotelDict = hotelDictService.getById(Integer.parseInt(adminManager.getHotelTownship()));
                advertise.setTownId(hotelDict.getName());
                List<Hotel> hotelList = hotelService.queryList(" and manager_id='"+adminManager.getId()+"' ");
                if (hotelList!=null){
                    advertise.setJumpPoint(String.valueOf(hotelList.get(0).getId()));
                }
            }
            int m = advertiseService.insertAdvertise(advertise);
            if (m > 0) {
                resultjson.put("message", "添加成功");
                resultjson.put("code", 200);
                ResUtil.writeJson(ServletActionContext.getResponse(), resultjson.toString());
                return null;
            } else {
                resultjson.put("message", "添加失败");
                resultjson.put("code", 502);
                ResUtil.writeJson(ServletActionContext.getResponse(), resultjson.toString());
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        resultjson.put("message", "未知异常");
        resultjson.put("code", 205);
        ResUtil.writeJson(ServletActionContext.getResponse(), resultjson.toString());
        return null;
    }

    public String update() {
        JSONObject resultjson = new JSONObject();
        Gson gson = new Gson();
        JSONObject json = GetHttpParam.getHttpParam(request);
        System.out.println(json);
        if (json == null) {
            resultjson.put("code", 205);
            resultjson.put("message", "请传入参数");
            ResUtil.writeJson(ServletActionContext.getResponse(), resultjson.toString());
            return null;
        }
        Advertise advertise = null;
        try {
            advertise = gson.fromJson(json.toString(), new TypeToken<Advertise>() {}.getType());
            if (advertise == null) {
                resultjson.put("message", "数据为空");
                resultjson.put("code", 500);
                ResUtil.writeJson(ServletActionContext.getResponse(), resultjson.toString());
                return null;
            }
            if (advertise.getTitle()==null || advertise.getLogoUrl()==null || advertise.getImageUrl()==null || advertise.getJumpWay()==null || advertise.getJumpDirection()==null || advertise.getJumpPoint()==null){
                resultjson.put("message", "各参数不能为空");
                resultjson.put("code", 500);
                ResUtil.writeJson(ServletActionContext.getResponse(), resultjson.toString());
                return null;
            }
            Advertise listy = advertiseService.queryById(advertise.getId());
            if (listy==null){
                resultjson.put("message", "该条数据已删除");
                resultjson.put("code", 500);
                ResUtil.writeJson(ServletActionContext.getResponse(), resultjson.toString());
                return null;
            }
            Advertise listc = advertiseService.queryByTitle(advertise.getTitle());
            if (listc!=null && !Objects.equals(listc.getId(), advertise.getId())){
                resultjson.put("message", "广告已存在");
                resultjson.put("code", 500);
                ResUtil.writeJson(ServletActionContext.getResponse(), resultjson.toString());
                return null;
            }
            List<Advertise> open = advertiseService.queryOpenAdvertise();
            if (open!=null){
                List<Integer> ids = open.stream().map(Advertise::getId).collect(Collectors.toList());
                if (open.size()>=3 && !ids.contains(advertise.getId()) && advertise.getState()==1){
                    resultjson.put("message", "最多开启三个广告");
                    resultjson.put("code", 500);
                    ResUtil.writeJson(ServletActionContext.getResponse(), resultjson.toString());
                    return null;
                }
                if (open.size()==1 && ids.contains(advertise.getId()) && advertise.getState()==0){
                    resultjson.put("message", "必须保留一个广告");
                    resultjson.put("code", 500);
                    ResUtil.writeJson(ServletActionContext.getResponse(), resultjson.toString());
                    return null;
                }
            }
            if (advertise.getJumpWay().equals("小程序") && advertise.getJumpDirection().equals("攻略") && !advertise.getJumpPoint().equals("首页")){
                ArticleTweet articleTweet = articleTweetService.queryArticleById(advertise.getJumpPoint(),null);
                advertise.setTownId(articleTweet.getLocationId());
            }
            if (advertise.getJumpWay().equals("小程序") && advertise.getJumpDirection().equals("民宿") && !advertise.getJumpPoint().equals("首页")){
                if (!listy.getJumpPoint().equals(advertise.getJumpPoint())){
                    AdminManager adminManager = adminManagerService.getById(Integer.parseInt(advertise.getJumpPoint()));
                    HotelDict hotelDict = hotelDictService.getById(Integer.parseInt(adminManager.getHotelTownship()));
                    advertise.setTownId(hotelDict.getName());
                    List<Hotel> hotelList = hotelService.queryList(" and manager_id='"+adminManager.getId()+"' ");
                    if (hotelList!=null){
                        advertise.setJumpPoint(String.valueOf(hotelList.get(0).getId()));
                    }
                } else {
                    advertise.setTownId(listy.getTownId());
                }
            }
            advertise.setCreateTime(TimeExchange.getTime());
            int m = advertiseService.updateAdvertise(advertise);
            if (m > 0) {
                resultjson.put("message", "修改成功");
                resultjson.put("code", 200);
                ResUtil.writeJson(ServletActionContext.getResponse(), resultjson.toString());
                return null;
            } else {
                resultjson.put("message", "修改失败");
                resultjson.put("code", 502);
                ResUtil.writeJson(ServletActionContext.getResponse(), resultjson.toString());
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        resultjson.put("message", "未知异常");
        resultjson.put("code", 205);
        ResUtil.writeJson(ServletActionContext.getResponse(), resultjson.toString());
        return null;
    }

    public String del() {
        JSONObject resultjson = new JSONObject();
        if (id == null) {
            resultjson.put("message", "请传入id");
            resultjson.put("code", 500);
            ResUtil.writeJson(ServletActionContext.getResponse(), resultjson.toString());
            return null;
        }
        Advertise advertise = advertiseService.queryById(id);
        if (advertise==null){
            resultjson.put("message", "该数据已删除");
            resultjson.put("code", 500);
            ResUtil.writeJson(ServletActionContext.getResponse(), resultjson.toString());
            return null;
        }
        int m = advertiseService.delAdvertise(id);
        if (m > 0) {
            resultjson.put("message", "删除成功");
            resultjson.put("code", 200);
            ResUtil.writeJson(ServletActionContext.getResponse(), resultjson.toString());
            return null;
        }
        resultjson.put("message", "未知异常");
        resultjson.put("code", 205);
        ResUtil.writeJson(ServletActionContext.getResponse(), resultjson.toString());
        return null;
    }

    public String listPage() {
        JSONObject resultJson = new JSONObject();
        StringBuilder s1 = new StringBuilder("");
        if (state!=null){
            s1.append(" and state = '").append(this.state).append("' ");
        }
        if (title!=null){
            s1.append(" and title like '%").append(this.title).append("%' ");
        }
        if (startTime!=null){
            s1.append(" and create_time > '").append(this.startTime).append("' ");
        }
        if (endTime!=null){
            s1.append(" and create_time < '").append(this.endTime).append(" 24:60:60' ");
        }
        int total = advertiseService.queryAdvertiseTotal(s1.toString()); // 查询表中的总记录数
        List<Advertise> listPage = advertiseService.queryAdvertisePage(page,rows,s1.toString()); // 查询分页

        if (listPage == null) {
            resultJson.put("code", 200);
            resultJson.put("rows", "");
            resultJson.put("total", 0);
        } else {
            resultJson.put("code", 200);
            resultJson.put("rows", listPage);
            // int total = listAll.size();
            resultJson.put("total", total);// 总记录数
            int totalPage = total % rows == 0 ? (total / rows)
                    : (total / rows) + 1;// 总页数
            resultJson.put("totalPage", totalPage);
            resultJson.put("currentPage", page);// 当前页
            resultJson.put("numPerPage", rows);// 每页数
            resultJson.put("nextPage", totalPage - page == 0 ? page : page + 1);// 下一页
            resultJson.put("previousPage", page - 0 == 1 ? page : page - 1);// 上一页
            resultJson.put("hasPreviousPage", true);// 有上一页
            resultJson.put("hasNextPage", true);// 有下一页
            resultJson.put("firstPage", true);// 首页
            resultJson.put("lastPage", true);// 尾页
        }
        ResponseUtil.writeJson(ServletActionContext.getResponse(),
                resultJson.toString());
        return null;
    }

    public String openList(){
        JSONObject resultJson = new JSONObject();
        List<Advertise> list = advertiseService.queryOpenAdvertise();
        if (list==null){
            resultJson.put("message", "数据为空");
            resultJson.put("code", 205);
            ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
            return null;
        }
        resultJson.put("message", "返回成功");
        resultJson.put("code", 200);
        resultJson.put("data", list);
        ResponseUtil.writeJson(ServletActionContext.getResponse(),
                resultJson.toString());
        return null;
    }

    public String operateState(){
        JSONObject resultJson = new JSONObject();
        if (id==null || state==null){
            resultJson.put("message", "数据格式不对");
            resultJson.put("code", 205);
            ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
            return null;
        }
        Advertise advertise = advertiseService.queryById(id);
        if (advertise==null){
            resultJson.put("message", "当前广告已删除");
            resultJson.put("code", 205);
            ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
            return null;
        }
        List<Advertise> open = advertiseService.queryOpenAdvertise();
        if (open!=null){
            List<Integer> ids = open.stream().map(Advertise::getId).collect(Collectors.toList());
            if (open.size()>=3 && !ids.contains(advertise.getId()) && state==1){
                resultJson.put("message", "最多开启三个广告");
                resultJson.put("code", 500);
                ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
                return null;
            }
            if (open.size()==1 && ids.contains(advertise.getId()) && state==0){
                resultJson.put("message", "必须保留一个广告");
                resultJson.put("code", 500);
                ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
                return null;
            }
        }
        int m = advertiseService.updateState(id,state,TimeExchange.getTime());
        if (m>0){
            resultJson.put("message", "操作成功");
            resultJson.put("code", 200);
            ResponseUtil.writeJson(ServletActionContext.getResponse(),
                    resultJson.toString());
            return null;
        }
        resultJson.put("message", "操作失败");
        resultJson.put("code", 205);
        ResponseUtil.writeJson(ServletActionContext.getResponse(),
                resultJson.toString());
        return null;
    }
}
