package fcb.project.manager.core.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import fcb.project.manager.base.entity.ContextTokenBean;
import fcb.project.manager.base.entity.TmEstate;
import fcb.project.manager.base.entity.TmHouse;
import fcb.project.manager.base.service.custom.PanoService;
import fcb.project.manager.base.service.impl.TmEstateServiceImpl;
import fcb.project.manager.base.service.impl.TmHouseServiceImpl;
import fcb.project.manager.base.service.impl.TmOperationServiceImpl;
import fcb.project.manager.base.utils.DataUtils;
import fdage.back.sdk.base.entity.Result;
import fdage.back.sdk.base.enums.ResultCodeEnum;
import fdage.back.sdk.base.exception.CommonBaseException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

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

/**
 * 2 * @Author: Abner
 * 3 * @Date: 2021/1/7 12:16
 * 4
 */
@Api(tags = "项目管理相关接口")
@RestController
@RequestMapping("fcb/project/project")
@Log4j2
public class ProjectController extends BaseController {

    @Autowired
    private TmEstateServiceImpl tmEstateService;

    @Autowired
    private TmHouseServiceImpl tmHouseService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private PanoService panoService;

    @Autowired
    private TmOperationServiceImpl tmOperationService;


    @GetMapping("/queryOrSearchList")
    @ApiOperation(value = "根据条件拉取所有楼盘")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "estateName", value = "楼盘名称", paramType = "query", required = true, dataType = "String"),
            @ApiImplicitParam(name = "belongCompany", value = "所属公司", paramType = "query", required = true, dataType = "String"),
            @ApiImplicitParam(name = "pageNum", value = "当前页码", paramType = "query", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "pageSize", value = "每页大小", paramType = "query", required = true, dataType = "Long")
    })
    public Result<Object> getProjectList(@RequestParam(required = false) String estateName,
                                         @RequestParam(required = false) String belongCompany,
                                         @RequestParam(name = "pageNum") Long pageNum,
                                         @RequestParam(name = "pageSize") Long pageSize) {

        IPage<TmEstate> resultPage = tmEstateService.getListByNameOrBelong(estateName, belongCompany, getContextUserInfo(), pageNum, pageSize);
        return Result.success(DataUtils.assembleResult(resultPage.getTotal(), resultPage.getPages(),
                resultPage.getCurrent(), resultPage.getRecords()));
    }

    @PostMapping("/addEstate")
    @ApiOperation(value = "创建楼盘项目")
    public Result<Object> addNewEstate(@RequestBody TmEstate tmEstate, HttpServletRequest request) {

        if (!StringUtils.isNoneBlank(tmEstate.getEstateName())) {
            throw new CommonBaseException(ResultCodeEnum.D101, "楼盘名称不能为空");
        }
        ContextTokenBean tokenMap = getContextUserInfo();
        TmEstate dbEstate = tmEstateService.getOneByNameAndBelong(tmEstate.getEstateName(), tokenMap.getDepartmentName());
        if (null != dbEstate) {
            log.info("{}公司下面的楼盘{}已经存在", tmEstate.getBelongCompanyName(), tmEstate.getEstateName());
            throw new CommonBaseException(ResultCodeEnum.D101, "楼盘已经存在，无需再添加");
        }
        if (null != tokenMap) {
            tmEstate.setBelongCompanyId(tokenMap.getDepartmentId());
            tmEstate.setBelongCompanyName(tokenMap.getDepartmentName());
            tmEstate.setCreateById(tokenMap.getId());
            tmEstate.setCreateByName(tokenMap.getNickName());
        }
        if (tmEstateService.insertNew(tmEstate)) {
            int ins = tmOperationService.addNewWithTypeAndContent(getContextUserInfo() , "VR楼盘项目" , "创建楼盘/" + tmEstate.getEstateName());
            if(ins != 1){
                log.info("插入操作记录失败");
            }
            return Result.success("新增成功");
        } else {
            return Result.failure("新增失败");
        }
    }

    @PostMapping("/deleteEstate")
    @ApiOperation(value = "删除楼盘信息")
    public Result<Object> deleteEstate(String estateId) {

        if (StringUtils.isBlank(estateId)) {
            return Result.failure("楼盘ID不能为空");
        }
        TmEstate dbEstate = tmEstateService.getById(estateId);
        if(null == dbEstate){
            return Result.failure("楼盘不存在");
        }

        IPage<TmHouse> page = tmHouseService.checkEstateCanDelete(estateId);
        if (null != page && page.getTotal() > 0) {
            return Result.failure("楼盘下存在VR项目时不可删除");
        }
        List<TmHouse> houseList = tmHouseService.getListByEstate(estateId);
        if(!CollectionUtils.isEmpty(houseList)){
            for ( TmHouse house : houseList) {
                if(null != house){
                    List<String> sceneNumList = panoService.getKanKanSceneNums(house.getId() , getToken());
                    log.info("720返回的房源的[{}]对应的四维场景码列表为:{}" , house.getId() , JSON.toJSONString(sceneNumList));
                    if(!CollectionUtils.isEmpty(sceneNumList)){
                        return Result.failure("楼盘下存在未解绑的VR项目，请解绑后删除");
                    }
                }
            }
        }
        int delete = tmEstateService.deleteEstateById(estateId);
        if (delete != 1) {
            return Result.failure("删除失败");
        }
        int ins = tmOperationService.addNewWithTypeAndContent(getContextUserInfo() , "VR楼盘项目" , "删除楼盘/" + dbEstate.getEstateName());
        if(ins != 1){
            log.info("插入操作记录失败");
        }

        return Result.success("删除楼盘成功");

    }

    @PostMapping("/updateEstate")
    @ApiOperation(value = "修改楼盘项目信息")
    public Result<Object> updateEstate(@RequestBody TmEstate tmEstate) {

        if (null == tmEstate) {
            return Result.failure("入参为空");
        }
        if (StringUtils.isBlank(tmEstate.getId())) {
            return Result.failure("id不能为空");
        }
        TmEstate dbEstate = tmEstateService.getById(tmEstate.getId());
        if(null == dbEstate){
            return Result.failure("楼盘不存在");
        }
        if (tmEstate.getIsDelete().compareTo(1) == 0 && dbEstate.getIsDelete().compareTo(0) == 0) {
            //删除楼盘操作,需要检查楼盘下面是否还有有效房源

        }
        if (tmEstateService.updateEstate(tmEstate)) {
            int ins = tmOperationService.addNewWithTypeAndContent(getContextUserInfo() , "VR楼盘项目" , "修改楼盘/" + dbEstate.getEstateName());
            if(ins != 1){
                log.info("插入操作记录失败");
            }
            return Result.success("修改成功");
        } else {
            return Result.failure("修改失败");
        }
    }


}
