package com.yunzhi.marketing.xlk.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunzhi.marketing.base.BaseController;
import com.yunzhi.marketing.base.ResponseBean;
import com.yunzhi.marketing.common.StringUtils;
import com.yunzhi.marketing.entity.TaBuilding;
import com.yunzhi.marketing.entity.TaPerson;
import com.yunzhi.marketing.service.ITaBuildingService;
import com.yunzhi.marketing.service.ITaPersonService;
import com.yunzhi.marketing.xlk.dto.SearchHouseDTO;
import com.yunzhi.marketing.xlk.dto.SearchHouseReplayDTO;
import com.yunzhi.marketing.xlk.entity.Curriculum;
import com.yunzhi.marketing.xlk.entity.SearchHouse;
import com.yunzhi.marketing.xlk.service.ISearchHouseService;
import com.yunzhi.marketing.xlk.vo.SearchHouseVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
    * 帮我找房  前端控制器
    * </p>
 *
 * @author jobob
 * @since 2021-05-19
 */
@RestController
@RequestMapping("/api")
@Api(value = "帮我找房", tags = "xlk-帮我找房")
public class SearchHouseController extends BaseController {

    private final Logger logger = LoggerFactory.getLogger(SearchHouseController.class);

    @Autowired
    public ISearchHouseService iSearchHouseService;

    @Autowired
    public ITaPersonService taPersonService;

    @Autowired
    private ITaBuildingService taBuildingService;

    /**
     * 分页查询列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @ApiOperation(value = "admin-获取帮我找房列表", notes = "admin-获取帮我找房列表")
    @RequestMapping(value="/admin/searchHouse",method= RequestMethod.GET)
    public ResponseBean searchHouseList(@RequestParam(value ="pageNum",defaultValue = "1") Integer pageNum,
                                        @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize,
                                        @RequestParam(value ="type") Integer type,
                                        @RequestParam(value ="name", required = false) String name,
                                        @RequestParam(value ="phone", required = false) String phone,
                                        @RequestParam(value ="status", required = false) String status,
                                        @RequestHeader("authorization") String token, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            SearchHouseVO searchHouse = new SearchHouseVO();
            searchHouse.setOrgId(getOrgId(request));
            searchHouse.setType(type);
            searchHouse.setNickname(name);
            searchHouse.setPhone(phone);
            searchHouse.setStatus(status);
            //使用分页插件
            IPage<SearchHouseVO> pg = new Page<>(pageNum, pageSize);
            responseBean = iSearchHouseService.selectSearchHouseList(pg,searchHouse);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("searchHouseList -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 保存对象
     * @param searchHouseDTO 实体对象
     * @return
     */
    @ApiOperation(value = "wx-保存帮我找房需求", notes = "wx-保存帮我找房需求")
    @RequestMapping(value="/wx/searchHouse",method= RequestMethod.POST)
    public ResponseBean searchHouseAdd(@RequestBody SearchHouseDTO searchHouseDTO, @RequestHeader("authorization") String token, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        String openid = getOpenId(request);
        Integer orgId = getOrgId(request);
        List<TaPerson> persons = taPersonService.getPersonsByOpenId(openid);
        if (null == persons || persons.size() == 0) {
            return ResponseBean.error("当前账户信息异常, 清除缓存重试", ResponseBean.ERROR_UNAVAILABLE);
        }
        TaPerson person = persons.get(0);
        try {
            SearchHouse searchHouse = new SearchHouse();
            BeanUtils.copyProperties(searchHouseDTO,searchHouse);
            searchHouse.setPersonId(person.getPersonId());
            searchHouse.setOrgId(orgId);
            searchHouse.setStatus("0");
            searchHouse.setCreatedTime(LocalDateTime.now());
            if (iSearchHouseService.save(searchHouse)){
                SearchHouseVO searchHouseVO = new SearchHouseVO();
                BeanUtils.copyProperties(searchHouse,searchHouseVO);
                // 获取价格相近的楼盘
                LambdaQueryWrapper<TaBuilding> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(!StringUtils.isEmpty(searchHouseDTO.getIntentArea()),TaBuilding::getBuildingArea,searchHouseDTO.getIntentArea());
                lambdaQueryWrapper.between(TaBuilding::getPrice,searchHouseDTO.getMinPrice(),searchHouseDTO.getMaxPrice());
                lambdaQueryWrapper.ne(TaBuilding::getStatus,-1);
                lambdaQueryWrapper.last(" limit 2");
                List<TaBuilding> list = taBuildingService.list(lambdaQueryWrapper);
                if (list.size() < 1){
                    lambdaQueryWrapper = new LambdaQueryWrapper<>();
                    lambdaQueryWrapper.eq(!StringUtils.isEmpty(searchHouseDTO.getIntentArea()),TaBuilding::getBuildingArea,searchHouseDTO.getIntentArea());
                    lambdaQueryWrapper.ne(TaBuilding::getStatus,-1);
                    lambdaQueryWrapper.last(" limit 2");
                    list = taBuildingService.list(lambdaQueryWrapper);
                }
                searchHouseVO.setTaBuildingList(list);
                responseBean.addSuccess(searchHouseVO);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("searchHouseAdd -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 修改对象
     * @param id  实体ID
     * @param searchHouse 实体对象
     * @return
     */
    @ApiOperation(value = "admin-修改帮我找房需求", notes = "admin-修改帮我找房需求")
    @RequestMapping(value="/admin/searchHouse/{id}",method= RequestMethod.PUT)
    public ResponseBean searchHouseUpdate(@PathVariable String id,
                                          @RequestBody SearchHouse searchHouse, @RequestHeader("authorization") String token, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            searchHouse.setId(id);
            if (iSearchHouseService.updateById(searchHouse)){
                responseBean.addSuccess(searchHouse);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("searchHouseUpdate -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id查询对象
     * @param id  实体ID
     */
    @ApiOperation(value = "admin-根据id查询帮我找房需求详情", notes = "admin-根据id查询帮我找房需求详情")
    @RequestMapping(value="/admin/searchHouse/{id}",method= RequestMethod.GET)
    public ResponseBean searchHouseGet(@PathVariable String id, @RequestHeader("authorization") String token, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean.addSuccess(iSearchHouseService.selectSearchHouseDetail(id));
        }catch (Exception e){
            e.printStackTrace();
            logger.error("searchHouseDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }


    /**
     * 帮我找房回访接口
     * @param id  实体ID
     * @param searchHouseReplayDTO 实体对象
     * @return
     */
    @ApiOperation(value = "admin-帮我找房回访接口", notes = "admin-帮我找房回访接口")
    @RequestMapping(value="/admin/reply/{id}",method= RequestMethod.PUT)
    public ResponseBean searchHouseReply(@PathVariable String id,
                                         @RequestBody SearchHouseReplayDTO searchHouseReplayDTO, @RequestHeader("authorization") String token, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            SearchHouse searchHouse = new SearchHouse();
            searchHouse.setId(id);
            searchHouse.setAuditRemark(searchHouseReplayDTO.getAuditRemark());
            searchHouse.setStatus(searchHouseReplayDTO.getStatus());
            searchHouse.setUpdatedTime(LocalDateTime.now());
            if (iSearchHouseService.updateById(searchHouse)){
                responseBean.addSuccess(searchHouse);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("searchHouseUpdate -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }
}
