package com.happy.action;

import com.alibaba.fastjson.JSONArray;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.happy.Model.*;
import com.happy.Until.GetHttpParam;
import com.happy.Until.PwdDefind;
import com.happy.Until.ResUtil;
import com.happy.Until.UUIDUtil;
import com.happy.dto.HotelEto;
import com.happy.dto.IPage;
import com.happy.service.*;
import com.opensymphony.xwork2.ActionSupport;
import lombok.SneakyThrows;
import net.sf.json.JSONObject;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.springframework.beans.BeanUtils;

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

public class hotelAction extends ActionSupport implements ServletRequestAware {

    private HttpServletRequest request;
    public HttpServletResponse response;

    @Resource
    public BookService bookService;

    @Resource
    public WorkflowService workflowService;
    @Resource
    public AdminManagerService adminManagerService;

    @Resource
    public HotelService hotelService;

    @Resource
    public HotelDictService hotelDictService;

    @Resource
    public HouseService houseService;

    @Resource
    public FileService fileService;

    public Integer id;
    public Integer managerId;//所属商家账号id
    public Integer code;//查询字典编码
    public int page; // 当前页
    public int rows;// 每页显示的行数rows

    public String fileListJson;

    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;
    }

    /**
     * 描述:维护民宿信息
     * @return
     */
    public String updateHotel(){
        JSONObject resultJson = new JSONObject();
        Gson gson = new Gson();
        com.alibaba.fastjson.JSONObject json = GetHttpParam.getRequestParameters(request);
        if (json == null) {
            resultJson.put("message", "请传入参数");
            ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
            return null;
        }
        HotelEto hotelEto = new HotelEto();
        try{
            hotelEto = gson.fromJson(json.toString(), new TypeToken<HotelEto>() {}.getType());
            Hotel hotel = new Hotel();
            BeanUtils.copyProperties(hotelEto,hotel);
            int hotelId = hotel.getId()!=null ? hotel.getId():Math.toIntExact(UUIDUtil.generateID());
            if(hotelId==0){
                hotelId = Math.toIntExact(UUIDUtil.generateID());
            }
            int m = 0;
            //详细图附件
            List<FileInfo> fileList = JSONArray.parseArray(fileListJson, FileInfo.class);
            if(fileList==null || fileList.size() == 0){
                resultJson.put("message", "请上传详细图");
                ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
                return null;
            }
            //保存基本信息
            Hotel hotel1 = hotelService.getById(hotel.getId());
            boolean isOk = false;
            if(hotel1!= null){
                //修改
                if (1 == hotel1.getHstatus() && 2 == hotel.getHstatus()){ // 判断营业改休息
                    StringBuilder s1 = new StringBuilder("");
                    s1.append(" and order_status in ( 1,2,3,4,10) "); //待支付、已支付、待入住、已入住、退款中
                    s1.append(" and hotel_id = '").append(hotel.getId()).append("' ");
                    List<Booking> list = bookService.queryList(s1.toString()); // 查询分页
                    if (list != null){
                        resultJson.put("message", "民宿存在“待支付、已支付、待入住、已入住、退款中”状态的订单，不可更改民宿状态。");
                        resultJson.put("code", 200);
                        ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
                        return null;
                    }
                }
                //判断是否修改简介
                if (hotel1.getRemark() != null && !"".equals(hotel1.getRemark())){
                    if (!hotel1.getRemark().equals(hotel.getRemark())){
                        isOk = true;
                    }
                }else {
                    isOk = true;
                }

                //判断是否修改了封面图
                if (hotel1.getCoverImg() != null && !"".equals(hotel1.getCoverImg())){
                    if ( !hotel1.getCoverImg().equals(hotel.getCoverImg()) && hotel.getCoverImg() != null && !"".equals(hotel.getCoverImg())){
                        isOk = true;
                    }
                }else {
                    isOk = true;
                }
                //判断是否修改图片
                for(FileInfo file : fileList){
                    if ( "".equals(file.getLinkId()) || file.getLinkId()==null || file.getLinkId().length() == 0) {
                        isOk = true;
                        break;
                    }
                }
                //判断图片是否有删除
                List<FileInfo> fileInfoList = fileService.queryList("and link_id ='"+hotel.getManagerId()+"'");
                if (fileInfoList != null){
                    if (fileInfoList.size() != fileList.size()){
                        isOk = true;
                    }
                }else {
                    isOk = true;
                }
                if (isOk){
                    Workflow workflow = new Workflow();
                    String id = String.valueOf(UUID.randomUUID());
                    workflow.setLinkId(String.valueOf(hotel.getManagerId()));
                    workflow.setRemark(hotel.getRemark());
                    workflow.setCreateId(String.valueOf(hotel.getCreateId()));
                    workflow.setId(id);
                    workflow.setStatus(1);
                    workflow.setType(1);
                    workflow.setCoverImg(hotel.getCoverImg());
                    hotel.setRemark(hotel1.getRemark());
                    hotel.setCoverImg(hotel1.getCoverImg());
                    int i = workflowService.insert(workflow);
                    m = hotelService.updateHotel(hotel);
                    if (i > 0 && m > 0){
                        //将新修改的附件关联到流程id
                        for(FileInfo file : fileList){
                            file.setId(String.valueOf(UUID.randomUUID()));
                            file.setLinkId(id);
                            fileService.insertFile(file);
                        }
                        hotel.setRemark(hotel1.getRemark());
                        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;
                    }
                }else{
                    hotel.setId(hotelId);
                    m = hotelService.updateHotel(hotel);
                }
            }else{
                resultJson.put("message", "未找到数据Id:"+hotelId);
                resultJson.put("code", 502);
                ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
                return null;
            }
            if (m > 0) {
                if(hotel.getId()!= null){
                    fileService.delLinkFile(String.valueOf(hotel.getId()));
                }
                for(FileInfo file : fileList){
                    FileInfo fileInfo = fileService.getById(file.getId());
                    file.setLinkId(String.valueOf(hotel.getManagerId()));
                    if(fileInfo==null){
                        fileService.insertFile(file);
                    }else{
                        fileService.updateFile(file);
                    }
                }
                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;
    }

    /**
     * 描述：查看民宿详细
     * @return
     */
    public String getByHotelInfo(){
        JSONObject resultJson = new JSONObject();
        StringBuilder s1 = new StringBuilder("");
        if (managerId!=null){
            s1.append(" and manager_id = '").append(managerId).append("'");
        }else{
            resultJson.put("message", "请传入managerId");
            ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
            return null;
        }
        if(id!=null){
            s1.append(" and id = '").append(id).append("'");
        }
        //查询商户信息
        AdminManager adminManager = adminManagerService.getById(managerId);
        //查询民宿信息
        Hotel hotel = hotelService.getOen(s1.toString());

        HotelEto hotelEto = new HotelEto();
        if(adminManager!=null){
            hotelEto.setHotelName(adminManager.getHotelName());
            hotelEto.setHotelTownship(adminManager.getHotelTownship());
            hotelEto.setHotelTownshipName(adminManager.getHotelTownshipName());
            hotelEto.setCorpnName(adminManager.getCorpnName());
            hotelEto.setCorpnPhone(adminManager.getCorpnPhone());
            hotelEto.setManagerId(adminManager.getId());
            hotelEto.setBankCard(adminManager.getBankCard());
            hotelEto.setCardName(adminManager.getCardName());
        }
        if(hotel!=null){
            //获取有效民宿配置
            if(hotel.getHconfig() != null && !"".equals(hotel.getHconfig())){
                hotel.setHconfig(hotelDictService.setConfig(hotel.getHconfig()));
            }
            hotel.setRoomNumber(houseService.getHouseSum(managerId));
            if (!"".equals(hotel.getHtype()) && hotel.getHtype() !=null) {
                hotel.sethTypeName(hotelDictService.getDictNameById(Integer.parseInt(hotel.getHtype())));
            }
            BeanUtils.copyProperties(hotel,hotelEto);
            hotelEto.setHotelTownshipName(adminManager.getHotelTownshipName());
            StringBuilder fileSqlx = new StringBuilder("");
            fileSqlx.append("and link_id = '").append(hotel.getManagerId()).append("'");
            List<FileInfo> fileList = fileService.queryList(fileSqlx.toString());
            hotelEto.setFileInfoList(fileList);
            resultJson.put("message", "查询成功");
            resultJson.put("code", 200);
            resultJson.put("data", hotelEto);
            ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
        }else{
            hotelEto.setHstatus(1);
            hotelEto.setIsCanorder(1);
            hotelEto.setIsOrder(1);
            hotelEto.setIsCheckout(1);
            hotelEto.setLockTime("15");
        }
        if(adminManager == null && hotel == null){
            resultJson.put("message", "未查到数据请检查参数");
            resultJson.put("code", 500);
            ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
            return null;
        }
        hotelEto.setId(Math.toIntExact(UUIDUtil.generateID()));
        resultJson.put("message", "查询成功");
        resultJson.put("code", 200);
        resultJson.put("data", hotelEto);
        ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
        return null;
    }

    /**
     * 描述：新增民宿配置字典 code 1.民宿类型；2.民宿服务；3.房型名称；4.房型服务
     * @return
     */
    public String insterHotelDict(){
        JSONObject resultJson = new JSONObject();
        Gson gson = new Gson();
        com.alibaba.fastjson.JSONObject json = GetHttpParam.getRequestParameters(request);
        if (json == null) {
            resultJson.put("message", "请传入参数");
            ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
            return null;
        }
        HotelDict hotelDict = new HotelDict();
        try{
            hotelDict = gson.fromJson(json.toString(), new TypeToken<HotelDict>() {}.getType());
            if(hotelDict==null){
                resultJson.put("message", "数据为空");
                resultJson.put("code", 500);
                ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
                return null;
            }
            if(hotelDict.getName()==null || hotelDict.getCode()==null){
                resultJson.put("message", "各参数不能为空");
                resultJson.put("code", 500);
                ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
                return null;
            }
            if(hotelDict.getCode()==4 && hotelDict.getFileUrl()==null){
                resultJson.put("message", "服务图标不能为空");
                resultJson.put("code", 500);
                ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
                return null;
            }
            StringBuilder getOneSqlx = new StringBuilder("");
            getOneSqlx.append(" and code = '").append(hotelDict.getCode()).append("'")
                    .append(" and name = '").append(hotelDict.getName()).append("'");
            HotelDict listc = hotelDictService.getOen(getOneSqlx.toString());
            if(listc != null){
                resultJson.put("message", "已新增过相同名称的数据");
                resultJson.put("code", 500);
                ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
                return null;
            }
            int m = hotelDictService.insertHotelDict(hotelDict);
            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", "未知异常："+ e);
            resultJson.put("code", 205);
            ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
        }
        resultJson.put("message", "未知异常");
        resultJson.put("code", 205);
        ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
        return null;
    }

    /**
     * 描述：新增民宿配置字典 code 1.民宿类型；2.民宿服务；3.房型名称；4.房型服务
     * @return
     */
    public String updateHotelDict(){
        JSONObject resultJson = new JSONObject();
        Gson gson = new Gson();
        com.alibaba.fastjson.JSONObject json = GetHttpParam.getRequestParameters(request);
        if (json == null) {
            resultJson.put("message", "请传入参数");
            ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
            return null;
        }
        HotelDict hotelDict = new HotelDict();
        try{
            hotelDict = gson.fromJson(json.toString(), new TypeToken<HotelDict>() {}.getType());
            if(hotelDict==null){
                resultJson.put("message", "数据为空");
                resultJson.put("code", 500);
                ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
                return null;
            }
            if(hotelDict.getId()==null){
                resultJson.put("message", "修改Id不能为空");
                resultJson.put("code", 500);
                ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
                return null;
            }
            if(hotelDict.getName()==null){
                resultJson.put("message", "各参数不能为空");
                resultJson.put("code", 500);
                ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
                return null;
            }
            if(hotelDict.getCode()==4 && hotelDict.getFileUrl()==null){
                resultJson.put("message", "服务图标不能为空");
                resultJson.put("code", 500);
                ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
                return null;
            }
            StringBuilder getOneSqlx = new StringBuilder("");
            getOneSqlx.append(" and code = '").append(hotelDict.getCode()).append("'")
                    .append(" and name = '").append(hotelDict.getName()).append("'")
                    .append(" and id != '").append(hotelDict.getId()).append("'");
            HotelDict listc = hotelDictService.getOen(getOneSqlx.toString());
            if(listc != null){
                resultJson.put("message", "已新增过相同名称的数据");
                resultJson.put("code", 500);
                ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
                return null;
            }
            int m = hotelDictService.updateHotelDict(hotelDict);
            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", "未知异常："+ e);
            resultJson.put("code", 205);
            ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
        }
        resultJson.put("message", "未知异常");
        resultJson.put("code", 205);
        ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
        return null;
    }

    /**
     * 描述：删除民宿配置字典
     * @return
     */
    public String delHotelDict(){
        JSONObject resultJson = new JSONObject();
        if (id == null) {
            resultJson.put("message", "请传入id");
            resultJson.put("code", 500);
            ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
            return null;
        }
        int m = hotelDictService.delHotelDict(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;
    }

    /**
     * 描述：查询民宿配置列表
     * @return
     */
    public String queryList(){
        JSONObject resultJson = new JSONObject();
        StringBuilder s1 = new StringBuilder("");
        StringBuilder s2 = new StringBuilder("");
        StringBuilder s3 = new StringBuilder("");
        StringBuilder s4 = new StringBuilder("");
        if(code==null){//查询全部
            s1.append("and code = 1");
            List<HotelDict> list1 = hotelDictService.queryList(s1.toString());
            s2.append("and code = 2");
            List<HotelDict> list2 = hotelDictService.queryList(s2.toString());
            s3.append("and code = 3");
            List<HotelDict> list3 = hotelDictService.queryList(s3.toString());
            s4.append("and code = 4");
            List<HotelDict> list4 = hotelDictService.queryList(s4.toString());
            resultJson.put("message", "查询成功");
            resultJson.put("code", 200);
            resultJson.put("date1", list1);
            resultJson.put("date2", list2);
            resultJson.put("date3", list3);
            resultJson.put("date4", list4);
            ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
            return null;
        }else{
            s1.append("and code = ").append(code);
            List<HotelDict> list1 = hotelDictService.queryList(s1.toString());
            resultJson.put("message", "查询成功");
            resultJson.put("code", 200);
            resultJson.put("data", list1);
            ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
            return null;
        }
    }

    /**
     * 描述:查询所有民宿信息列表
     *
     */
    public String queryListhotel(){
        JSONObject resultJson = new JSONObject();
        List<Hotel> list = hotelService.queryList("");
        if (list != null){
            resultJson.put("message", "查询成功");
            resultJson.put("code", 200);
            resultJson.put("data", list);
            ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
        }else {
            resultJson.put("message", "数据为空！");
            resultJson.put("code", 205);
            ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
        }
        return null;
    }

    /**
     * 描述查询根据状态11的字典
     */

    public String queryTakeOrderDict(){
        JSONObject resultJson = new JSONObject();
        StringBuilder s1 = new StringBuilder("");
        s1.append("and code = 11");
        List<HotelDict> list1 = hotelDictService.queryList(s1.toString());
        List<Map<String,String>> data = new ArrayList<>();
        list1.forEach(hotelDict -> {
            switch (hotelDict.getId()){
                case 1111111111 : {
                    Map<String,String> map = new HashMap<>();
                    map.put("id", String.valueOf(hotelDict.getId()));
                    map.put("code",hotelDict.getName());
                    map.put("description","为多少分钟后接单");
                    data.add(map);
                } break;
                case 1000011002 : {
                    Map<String,String> map = new HashMap<>();
                    map.put("id", String.valueOf(hotelDict.getId()));
                    map.put("code",hotelDict.getName());
                    map.put("description","1.接单 2.拒单");
                    data.add(map);
                } break;
                case 1000011003 : {
                    Map<String,String> map = new HashMap<>();
                    map.put("id", String.valueOf(hotelDict.getId()));
                    map.put("code",hotelDict.getName());
                    map.put("description","可预定多少月内的");
                    data.add(map);
                } break;
            }
        });
        if (data.size()>0){
            resultJson.put("message", "查询成功");
            resultJson.put("code", 200);
            resultJson.put("date", data);
            ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
        }else {
            resultJson.put("message", "数据为空！");
            resultJson.put("code", 205);
            ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
        }
        return null;
    }

    @SneakyThrows
    public void updateTakeOrderDict(){
        String postDataStr = GetHttpParam.getRequestPostData(request);
        com.alibaba.fastjson.JSONObject postDataJSONObject = com.alibaba.fastjson.JSONObject.parseObject(postDataStr);
        List<HotelDict> dicts = postDataJSONObject.getJSONArray("dicts").toJavaList(HotelDict.class);
        List<HotelDict> updateDict = new ArrayList<>();
        dicts.forEach(dict->{
            HotelDict hotelDict = new HotelDict();
            hotelDict.setId(dict.getId());
            hotelDict.setName(String.valueOf(dict.getCode()));
            updateDict.add(hotelDict);
        });
        int i = hotelDictService.saveBacth(updateDict);
        if (i > 0){
            ResUtil.writeJson(ServletActionContext.getResponse(), new com.alibaba.fastjson.JSONObject() {{
                put("message", "修改成功");
                put("code", 200);
            }}.toString());
        }
    }
}
