package com.huiju.estateagents.controller;

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.huiju.estateagents.base.ResponseBean;
import com.huiju.estateagents.entity.TaBuilding;
import com.huiju.estateagents.entity.TaBuildingProjectType;
import com.huiju.estateagents.entity.TdBuildingType;
import com.huiju.estateagents.exception.EstaException;
import com.huiju.estateagents.mapper.TaBuildingMapper;
import com.huiju.estateagents.service.ITaBuildingProjectTypeService;
import com.huiju.estateagents.service.ITaBuildingService;
import com.huiju.estateagents.service.ITdBuildingTypeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.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 com.huiju.estateagents.base.BaseController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
    * 项目类型字典表  前端控制器
    * </p>
 *
 * @author jobob
 * @since 2019-07-29
 */
@RestController
@RequestMapping("/api")
@Api(value = "项目类型", tags = "项目类型")
public class TdBuildingTypeController extends BaseController {

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

    @Autowired
    public ITdBuildingTypeService iTdBuildingTypeService;

    @Autowired
    public TaBuildingMapper taBuildingMapper;

    @Autowired
    public ITaBuildingProjectTypeService iTaBuildingProjectTypeService;

    /**
     * 分页查询列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @ApiOperation(value = "查询项目类型", notes = "查询项目类型")
    @ApiImplicitParams({
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "pageNum", paramType = "query",value = "第几页"),
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "pageSize", paramType = "query",value = "一页多少行")
    })
    @RequestMapping(value="/admin/tdBuildingType",method= RequestMethod.GET)
    public ResponseBean tdBuildingTypeList(@RequestParam(value ="pageNum",defaultValue = "1") Integer pageNum,
                                           @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize,
                                           HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            //使用分页插件
		    IPage<TdBuildingType> pg = new Page<>(pageNum, pageSize);
            QueryWrapper<TdBuildingType> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("status", 1);
            queryWrapper.orderByDesc("create_date");
            queryWrapper.eq("org_id", getOrgId(request));

            IPage<TdBuildingType> result = iTdBuildingTypeService.page(pg, queryWrapper);
            responseBean.addSuccess(result);
        }catch (Exception e){
            logger.error("tdBuildingTypeList -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 分页查询列表
     * @return
     */
    @RequestMapping(value="/wx/getByBuildingIdSelectBuildingProjectType/{buildingId}",method= RequestMethod.GET)
    public ResponseBean wxGetBuildingProjectTypeByBuildingIdList(@PathVariable(value ="buildingId") String buildingId, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            // 项目类型
            QueryWrapper<TaBuildingProjectType> projectTypeQueryWrapper = new QueryWrapper<>();
            projectTypeQueryWrapper.eq("building_id", buildingId);
            projectTypeQueryWrapper.eq("status", 1);
            List<TaBuildingProjectType> result = iTaBuildingProjectTypeService.list(projectTypeQueryWrapper);
            responseBean.addSuccess(result);
        }catch (Exception e){
            logger.error("taBuildingProjectTypeList -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 分页查询列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @ApiOperation(value = "微信查询项目类型", notes = "微信查询项目类型")
    @ApiImplicitParams({
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "pageNum", paramType = "query",value = "第几页"),
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "pageSize", paramType = "query",value = "一页多少行")
    })
    @RequestMapping(value="/wx/tdBuildingType",method= RequestMethod.GET)
    public ResponseBean tdWxBuildingTypeList(@RequestParam(value ="pageNumber",defaultValue = "1") Integer pageNumber,
                                           @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize,
                                             HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        Integer orgId = getOrgId(request);
        try {
            //使用分页插件
            IPage<TdBuildingType> pg = new Page<>(pageNumber, pageSize);
            QueryWrapper<TdBuildingType> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("status", 1);
            queryWrapper.orderByDesc("create_date");
            queryWrapper.eq("org_id",orgId);

            IPage<TdBuildingType> result = iTdBuildingTypeService.page(pg, queryWrapper);
            responseBean.addSuccess(result);
        }catch (Exception e){
            logger.error("tdBuildingTypeList -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }


    /**
     * 保存对象
     * @param tdBuildingType 实体对象
     * @return
     */
    @ApiOperation(value = "项目类型保存", notes = "项目类型保存")
    @RequestMapping(value="/admin/tdBuildingType",method= RequestMethod.POST)
    public ResponseBean tdBuildingTypeAdd(@RequestBody TdBuildingType tdBuildingType, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            QueryWrapper<TdBuildingType> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("building_type_name", tdBuildingType.getBuildingTypeName());
            queryWrapper.eq("status", 1);
            queryWrapper.eq("org_id", getOrgId(request));
            Integer count = iTdBuildingTypeService.count(queryWrapper);
            if (count != null && count > 0) {
                responseBean.addError("已存在此类型");
                return responseBean;
            }
            tdBuildingType.setOrgId(getOrgId(request));
            if (iTdBuildingTypeService.save(tdBuildingType)){
                responseBean.addSuccess(tdBuildingType);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            logger.error("tdBuildingTypeAdd -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id删除对象
     * @param id  实体ID
     */
    @ApiOperation(value = "项目类型 根据项目类型id删除", notes = "项目类型删除 根据项目类型id删除")
    @ApiImplicitParams({
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "id", paramType = "path",value = "项目类型id"),
    })
    @ResponseBody
    @RequestMapping(value="/admin/tdBuildingType/{id}", method= RequestMethod.DELETE)
    public ResponseBean tdBuildingTypeDelete(@PathVariable Integer id){
        ResponseBean responseBean = new ResponseBean();
        try {
            if(iTdBuildingTypeService.removeById(id)){
                responseBean.addSuccess("success");
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            logger.error("tdBuildingTypeDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 修改对象
     * @param id  实体ID
     * @param tdBuildingType 实体对象
     * @return
     */
    @ApiOperation(value = "项目类型 根据项目类型id修改", notes = "项目类型删除 根据项目类型id修改")
    @ApiImplicitParams({
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "id", paramType = "path",value = "项目类型id"),
            @ApiImplicitParam(dataTypeClass = TdBuildingType.class, name = "tdBuildingType", paramType = "body",value = "项目类型"),
    })
    @RequestMapping(value="/admin/tdBuildingType/{id}",method= RequestMethod.PUT)
    public ResponseBean tdBuildingTypeUpdate(@PathVariable Integer id,
                                        @RequestBody TdBuildingType tdBuildingType,
                                             HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {

            QueryWrapper<TdBuildingType> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("building_type_name", tdBuildingType.getBuildingTypeName());
            queryWrapper.eq("status", 1);
            queryWrapper.eq("org_id", getOrgId(request));
            TdBuildingType buildingType = iTdBuildingTypeService.getOne(queryWrapper);
            if (buildingType != null && buildingType.getBuildingTypeId().intValue() != id.intValue()) {
                responseBean.addError("已存在此类型");
                return responseBean;
            }

            // 如果是删除，状态为 -1
            if ( null != tdBuildingType.getStatus() && -1 == tdBuildingType.getStatus().intValue()) {
                List<TaBuilding> taBuildings = taBuildingMapper.selectBuildingByBuildingTypeId(tdBuildingType.getBuildingTypeId());
                if (CollectionUtils.isNotEmpty(taBuildings)) {
                    String buildingNames = taBuildings.stream().map(e -> e.getBuildingName()).collect(Collectors.joining(","));
                    throw new EstaException("项目 " + buildingNames + " 正在使用此类型，请先到项目列表中修改项目的项目类型为其他类型，再删除此类型");
                }
            }

            tdBuildingType.setOrgId(getOrgId(request));
            if (iTdBuildingTypeService.updateById(tdBuildingType)){
                responseBean.addSuccess(tdBuildingType);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            logger.error("tdBuildingTypeUpdate -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id查询对象
     * @param id  实体ID
     */
    @ApiOperation(value = "项目类型 根据项目类型id查询对象", notes = "项目类型删除 根据项目类型id查询对象")
    @ApiImplicitParams({
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "id", paramType = "path",value = "项目类型id"),
    })
    @RequestMapping(value="/admin/tdBuildingType/{id}",method= RequestMethod.GET)
    public ResponseBean tdBuildingTypeGet(@PathVariable Integer id){
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean.addSuccess(iTdBuildingTypeService.getById(id));
        }catch (Exception e){
            logger.error("tdBuildingTypeDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }
}
