package com.huiju.estateagents.property.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huiju.estateagents.base.ResponseBean;
import com.huiju.estateagents.center.taUser.entity.TaUser;
import com.huiju.estateagents.property.common.UserElement;
import com.huiju.estateagents.property.dao.*;
import com.huiju.estateagents.property.model.*;
import com.huiju.estateagents.property.service.IHotelService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 酒店 服务实现类
 * </p>
 *
 * @author jobob
 * @since 2019-05-13
 */
@Service
public class HotelServiceImpl extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {

    @Autowired
    private HotelRoomMapper tpHotelRoomMapper;

    @Autowired
    private  HotelMapper tpHotelMapper;

    @Autowired
    private UserMapper tpUserMapper;
    
    @Autowired
    private TpHotelImgMapper hotelImgMapper;
    
    @Autowired
    private HotelSettingMapper hotelSettingMapper;
    
    @Override
    public ResponseBean hotelRoomLiset(String parameter, Integer communityId) {
        ResponseBean response= new ResponseBean<>();
        HotelRoom hotelRoom= JSONObject.parseObject(parameter, HotelRoom.class);

        JSONObject object= JSONObject.parseObject(parameter);
        Integer pageNum = object.getInteger("pageNum");
        Integer pageSize = object.getInteger("pageSize");

        Date beginTime = object.getDate("beginTime");
        Date endTime = object.getDate("endTime");

        Page<HotelRoom> page = new Page<>();
        page.setSize(pageSize == null ? 10 : pageSize);
        page.setCurrent(pageNum == null ? 1 : pageNum);

        IPage<HotelRoom> pageInfo = tpHotelRoomMapper.hotelRoomLiset(page,hotelRoom,beginTime,endTime,communityId);
        List<HotelRoom> hotelRoomList = pageInfo.getRecords();
        for (HotelRoom hotelRoomS:hotelRoomList){
            User user= tpUserMapper.selectById(hotelRoomS.getUpdateUser());
            if (null != user){
                hotelRoomS.setEditUser(user.getUserName());
            }
        }
        HashMap map=new HashMap<>();
        map.put("list",hotelRoomList);
        map.put("total", pageInfo.getTotal());
        map.put("pageNum", pageInfo.getCurrent());
        map.put("pageSize", pageInfo.getSize());
        response.addSuccess(map);
        return response;
    }

    @Override
    public ResponseBean hotelRoomAdd(String parameter, TaUser userElement) {
        ResponseBean response= new ResponseBean<>();
        HotelRoom hotelRoom= JSONObject.parseObject(parameter, HotelRoom.class);
        // 查询当前房间名称是否重复
        QueryWrapper<HotelRoom> HotelRoomName= new QueryWrapper<>();
        HotelRoomName.eq("community_id",userElement.getOrgId());
        HotelRoomName.eq("room_name",hotelRoom.getRoomName());
        List<HotelRoom> roomName= tpHotelRoomMapper.selectList(HotelRoomName);
        if (null != roomName && roomName.size()>0){
            response.addError("当前房间名称已存在");
            return response;
        }
        // 查询当前房间编号是否重复
//        QueryWrapper<HotelRoom> HotelRoomQuery= new QueryWrapper<>();
//        HotelRoomQuery.eq("community_id",userElement.getOrgId());
//        HotelRoomQuery.eq("room_no",hotelRoom.getRoomNo());
//        List<HotelRoom> RoomNo= tpHotelRoomMapper.selectList(HotelRoomQuery);
//        if (null != RoomNo && RoomNo.size()>0){
//            response.addError("当前房间号已存在");
//            return response;
//        }
        // 判断价格是否存在
        if (null == hotelRoom.getPrice()) {
            response.addError("请输入房间价格");
            return response;
        }
        Hotel hotel= tpHotelMapper.selectHotel(userElement.getOrgId());
        hotelRoom.setCommunityId(userElement.getOrgId())
                .setHotelId(hotel.getId())
                .setPrice(String.valueOf(hotelRoom.getPrice()))
                .setCreateDate(LocalDateTime.now())
                .setCreateUser(userElement.getUserId())
                .setUpdateDate(LocalDateTime.now())
                .setUpdateUser(userElement.getUserId());
        tpHotelRoomMapper.insert(hotelRoom);
        response.addSuccess("成功");
        return response;
    }

    @Override
    public ResponseBean hotelRoomEdit(String parameter, TaUser userElement) {
            ResponseBean response= new ResponseBean<>();
            HotelRoom hotelRoom= JSONObject.parseObject(parameter, HotelRoom.class);
            // 判断价格是否存在
            if (null == hotelRoom.getPrice()) {
                response.addError("请输入房间价格");
                return response;
            }
            Hotel hotel= tpHotelMapper.selectHotel(userElement.getOrgId());
            hotelRoom.setCommunityId(userElement.getOrgId())
                    .setHotelId(hotel.getId())
                    .setPrice(String.valueOf(hotelRoom.getPrice()))
                    .setUpdateDate(LocalDateTime.now())
                    .setUpdateUser(userElement.getUserId());
            tpHotelRoomMapper.updateById(hotelRoom);
            response.addSuccess("成功");
            return response;
        }

    @Override
    public ResponseBean hotelRoomRoomStatus(String parameter, TaUser userElement) {
        ResponseBean responseBean= new ResponseBean<>();
        JSONObject object= JSONObject.parseObject(parameter);
        JSONArray arr= object.getJSONArray("id");
        Integer[] arrId= arr.toArray(new Integer[]{});
        for (Integer id:arrId){
            String roomStatus= object.getString("roomStatus");
            HotelRoom hotelRoom= tpHotelRoomMapper.selectById(id);
            hotelRoom.setRoomStatus(roomStatus);
            hotelRoom.setUpdateDate(LocalDateTime.now());
            hotelRoom.setUpdateUser(userElement.getUserId());
            tpHotelRoomMapper.updateById(hotelRoom);
            responseBean.addSuccess("成功");
        }

        return responseBean;
    }
    
    /**
     * 根据小区id获取酒店信息
     *
     * @param userElement
     * @return
     */
    @Override
    public Hotel getHotelData(TaUser userElement) {
        QueryWrapper<Hotel> hotelQueryWrapper = new QueryWrapper<>();
        hotelQueryWrapper.eq("community_id",userElement.getOrgId());
        Hotel hotel = tpHotelMapper.selectOne(hotelQueryWrapper);
        if (null != hotel){
            //查看酒店开关是否开启
            QueryWrapper<HotelSetting> hotelSettingQueryWrapper = new QueryWrapper<>();
            hotelSettingQueryWrapper.eq("community_id",userElement.getOrgId());
            HotelSetting hotelSetting = hotelSettingMapper.selectOne(hotelSettingQueryWrapper);
            hotel.setHotelSettingValue(null == hotelSetting ? false : true);
            QueryWrapper<TpHotelImg> imgQueryWrapper = new QueryWrapper<>();
            imgQueryWrapper.eq("community_id",hotel.getCommunityId());
            imgQueryWrapper.eq("hotel_id",hotel.getId());
            imgQueryWrapper.eq("img_type","1");
            TpHotelImg tpHotelImg = hotelImgMapper.selectOne(imgQueryWrapper);
            hotel.setAppIndexImg(tpHotelImg.getImgUrl());
            //获取轮播图
            QueryWrapper<TpHotelImg> imgQueryWrappers = new QueryWrapper<>();
            imgQueryWrappers.eq("community_id",hotel.getCommunityId());
            imgQueryWrappers.eq("hotel_id",hotel.getId());
            imgQueryWrappers.eq("img_type","2");
            List<TpHotelImg> tpHotelImgList = hotelImgMapper.selectList(imgQueryWrappers);
            List<String> imgList = new ArrayList<>();
            tpHotelImgList.stream().forEach(e -> {
                imgList.add(e.getImgUrl());
            });
            hotel.setAppCarouselImg(imgList);
        }
        return hotel;
    }
    
    /**
     * 添加或修改酒店
     *
     * @param hotel
     * @param userElement
     * @return
     */
    @Override
    public ResponseBean addHotel(Hotel hotel, TaUser userElement) {
        ResponseBean responseBean = new ResponseBean();
        if (StringUtils.isBlank(hotel.getHotelLongitude()) || StringUtils.isBlank(hotel.getHotelLatitude())) {
            responseBean.addError("地理坐标不能为空！");
            return responseBean;
        }
        if (hotel.getHotelSettingValue()){
            // 为true时判断tp_hotel_setting是否存在当前小区
            QueryWrapper<HotelSetting> hotelSettingQuery = new QueryWrapper<>();
            hotelSettingQuery.eq("community_id",userElement.getOrgId());
            HotelSetting communitySetting= hotelSettingMapper.selectOne(hotelSettingQuery);
            if (null == communitySetting) {
                HotelSetting hotelSetting = new HotelSetting();
                hotelSetting.setCommunityId(userElement.getOrgId());
                hotelSetting.setCreateDate(LocalDateTime.now());
                hotelSetting.setCreateUser(userElement.getUserId());
                hotelSettingMapper.insert(hotelSetting);
            }
        }else {
            QueryWrapper<HotelSetting> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("community_id",userElement.getOrgId());
            hotelSettingMapper.delete(queryWrapper);
        }
        if (null != hotel.getId()){
            updateHotel(hotel,userElement);
        }else{
            addFirstHotel(hotel,userElement);
        }
        responseBean.addSuccess("更新成功");
        return responseBean;
    }
    
    private void updateHotel(Hotel hotel, TaUser userElement) {
        hotel.setUpdateDate(LocalDateTime.now());
        hotel.setUpdateUser(userElement.getUserId());
        tpHotelMapper.updateById(hotel);
        //更新首页图
        TpHotelImg tpHotelImg = new TpHotelImg();
        tpHotelImg.setImgUrl(hotel.getAppIndexImg());
        QueryWrapper<TpHotelImg> tpHotelImgQueryWrapper = new QueryWrapper();
        tpHotelImgQueryWrapper.eq("community_id",userElement.getOrgId());
        tpHotelImgQueryWrapper.eq("hotel_id",hotel.getId());
        tpHotelImgQueryWrapper.eq("img_type","1");
        hotelImgMapper.update(tpHotelImg,tpHotelImgQueryWrapper);
        //更新轮播图
        QueryWrapper<TpHotelImg> deleteImgQueryWrapper = new QueryWrapper();
        deleteImgQueryWrapper.eq("community_id",userElement.getOrgId());
        deleteImgQueryWrapper.eq("hotel_id",hotel.getId());
        deleteImgQueryWrapper.eq("img_type","2");
        hotelImgMapper.delete(deleteImgQueryWrapper);
        //重新插入
        batchInsertImg(hotel,userElement);
    }
    
    private void addFirstHotel(Hotel hotel, TaUser userElement) {
        hotel.setCommunityId(userElement.getOrgId());
        hotel.setCreateDate(LocalDateTime.now());
        hotel.setCreateUser(userElement.getUserId());
        tpHotelMapper.insert(hotel);
        //添加首页图
        TpHotelImg tpHotelImg = new TpHotelImg();
        tpHotelImg.setCommunityId(userElement.getOrgId());
        tpHotelImg.setCreateDate(LocalDateTime.now());
        tpHotelImg.setHotelId(hotel.getId());
        tpHotelImg.setImgType("1");
        tpHotelImg.setImgUrl(hotel.getAppIndexImg());
        hotelImgMapper.insert(tpHotelImg);
        //添加轮播图
        batchInsertImg(hotel,userElement);
    }
    
    private void batchInsertImg(Hotel hotel, TaUser userElement) {
        List<String> imgList = hotel.getAppCarouselImg();
        List<TpHotelImg> hotelImgList = new ArrayList<>();
        imgList.stream().forEach(e -> {
            TpHotelImg hotelImg = new TpHotelImg();
            hotelImg.setCommunityId(userElement.getOrgId());
            hotelImg.setCreateDate(LocalDateTime.now());
            hotelImg.setHotelId(hotel.getId());
            hotelImg.setImgType("2");
            hotelImg.setImgUrl(e);
            hotelImgList.add(hotelImg);
        });
        hotelImgMapper.batchInsert(hotelImgList);
    }
}
