package com.huiju.estateagents.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huiju.estateagents.base.BaseController;
import com.huiju.estateagents.base.ResponseBean;
import com.huiju.estateagents.common.CommConstant;
import com.huiju.estateagents.common.StringUtils;
import com.huiju.estateagents.entity.TaBuilding;
import com.huiju.estateagents.entity.TaOrg;
import com.huiju.estateagents.entity.TaPerson;
import com.huiju.estateagents.mapper.TaBuildingMapper;
import com.huiju.estateagents.mapper.TaOrgMapper;
import com.huiju.estateagents.reportCustomerAop.ReportCustomer;
import com.huiju.estateagents.service.ITaBuildingService;
import com.huiju.estateagents.service.ITaPersonService;
import com.huiju.estateagents.service.ITaSaveService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

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

/**
 * <p>
 * 项目表 前端控制器
 * </p>
 *
 * @author jobob
 * @since 2019-05-10
 */
@RestController
@RequestMapping("/api")
@Api(value = "楼盘")
public class TaBuildingController extends BaseController {

    @Autowired
    ITaBuildingService taBuildingService;

    @Autowired
    ITaSaveService iTaSaveService;

    @Autowired
    ITaPersonService iTaPersonService;

    @Autowired
    TaBuildingMapper taBuildingMapper;

    @Autowired
    TaOrgMapper taOrgMapper;


    /**
     * 楼盘详情
     *
     * @param id
     * @return
     */
    @GetMapping("/admin/buildingSelectId/{id}")
    @ApiOperation(value = "项目详情", notes = "项目详情")
    @ApiImplicitParams({
            @ApiImplicitParam(dataTypeClass = String.class, paramType = "path", name = "id", value = "项目id")
    })
    public ResponseBean buildingSelectId(@PathVariable(value = "id") String id) {
        return taBuildingService.buildingSelectId(id);
    }

    /**
     * 楼盘列表 查询所有有效的
     *
     * @param pageNum
     * @param pageSize
     * @param name
     * @param code
     * @return
     */
    @ApiOperation(value = "项目列表 查询所有有效的", notes = "项目列表 查询所有有效的")
    @ApiImplicitParams({
            @ApiImplicitParam(dataTypeClass = String.class, paramType = "query", name = "pageNum", value = "第几页"),
            @ApiImplicitParam(dataTypeClass = String.class, paramType = "query", name = "pageSize", value = "一页多少行"),
            @ApiImplicitParam(dataTypeClass = String.class, paramType = "query", name = "name", value = "项目名称"),
            @ApiImplicitParam(dataTypeClass = String.class, paramType = "query", name = "code", value = "项目编号"),
            @ApiImplicitParam(dataTypeClass = String.class, paramType = "query", name = "startDate", value = "开盘时间"),
            @ApiImplicitParam(dataTypeClass = String.class, paramType = "query", name = "buildingStatus", value = "项目状态"),
            @ApiImplicitParam(dataTypeClass = String.class, paramType = "query", name = "marketStatus", value = "销售状态"),
            @ApiImplicitParam(dataTypeClass = String.class, paramType = "query", name = "cityId", value = "城市Id"),
            @ApiImplicitParam(dataTypeClass = String.class, paramType = "query", name = "isMain", value = "是否主推项目"),
    })
    @GetMapping("/admin/buildinglist")
    public ResponseBean buildingList(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                     @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                     @RequestParam(value = "name", required = false) String name,
                                     @RequestParam(value = "code", required = false) String code,
                                     @RequestParam(value = "startDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startDate,
                                     @RequestParam(value = "buildingStatus", required = false) String buildingStatus,
                                     @RequestParam(value = "marketStatus", required = false) String marketStatus,
                                     @RequestParam(value = "cityId", required = false) Integer cityId,
                                     @RequestParam(value = "isMain", required = false) Integer isMain,
                                     HttpServletRequest request) {
        return taBuildingService.buildingList(pageNum, pageSize, name, code, startDate, buildingStatus, marketStatus, cityId, isMain, getOrgId(request), getTaPersonBuildingListByUserId(request));
    }

    /**
     * 楼盘列表
     *
     * @param pageNum
     * @param pageSize
     * @param name
     * @param code
     * @return
     */
    @ApiOperation(value = "项目列表", notes = "项目列表")
    @ApiImplicitParams({
            @ApiImplicitParam(dataTypeClass = String.class, paramType = "query", name = "pageNum", value = "第几页"),
            @ApiImplicitParam(dataTypeClass = String.class, paramType = "query", name = "pageSize", value = "一页多少行"),
            @ApiImplicitParam(dataTypeClass = String.class, paramType = "query", name = "name", value = "项目名称"),
            @ApiImplicitParam(dataTypeClass = String.class, paramType = "query", name = "code", value = "项目编号"),
            @ApiImplicitParam(dataTypeClass = String.class, paramType = "query", name = "startDate", value = "开盘时间"),
            @ApiImplicitParam(dataTypeClass = String.class, paramType = "query", name = "buildingStatus", value = "项目状态"),
            @ApiImplicitParam(dataTypeClass = String.class, paramType = "query", name = "marketStatus", value = "销售状态"),
            @ApiImplicitParam(dataTypeClass = String.class, paramType = "query", name = "cityId", value = "城市Id"),
            @ApiImplicitParam(dataTypeClass = String.class, paramType = "query", name = "isMain", value = "是否主推项目"),
    })
    @GetMapping("/admin/buildinglist/select")
    public ResponseBean buildingListSelect(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                           @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                           @RequestParam(value = "name", required = false) String name,
                                           @RequestParam(value = "code", required = false) String code,
                                           @RequestParam(value = "startDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startDate,
                                           @RequestParam(value = "buildingStatus", required = false) String buildingStatus,
                                           @RequestParam(value = "marketStatus", required = false) String marketStatus,
                                           @RequestParam(value = "cityId", required = false) Integer cityId,
                                           @RequestParam(value = "isMain", required = false) Integer isMain,
                                           HttpServletRequest request) {
        return taBuildingService.buildingListSelect(pageNum, pageSize, name, code, startDate, buildingStatus, marketStatus, cityId, isMain, getOrgId(request), getTaPersonBuildingListByUserId(request));
    }

    /**
     * 更新楼盘
     *
     * @param parameter
     * @return
     */
    @ApiOperation(value = "更新项目", notes = "更新项目")
    @ApiImplicitParams({

    })
    @PutMapping("/admin/building/update")
    public ResponseBean buildingUpdate(@RequestBody String parameter, HttpServletRequest request) {
        return taBuildingService.buildingUpdate(parameter, getOrgId(request));
    }

    /**
     * 楼盘添加
     *
     * @param parameter
     * @return
     */
    @ApiOperation(value = "项目添加", notes = "项目添加")
    @ApiImplicitParams({

    })
    @RequestMapping(value = "/admin/building/add", method = RequestMethod.POST)
    public ResponseBean buildingAdd(@RequestBody String parameter, HttpServletRequest request) {
        return taBuildingService.buildingAdd(parameter, getOrgId(request), getUserId(request));
    }

    /**
     * 楼盘getPersonId(request);
     *
     * @param parameter
     * @return
     */
    @ApiOperation(value = "项目发布", notes = "项目发布")
    @ApiImplicitParams({
            @ApiImplicitParam(dataTypeClass = String.class, paramType = "body", name = "parameter", value = "status：状态，id：项目id"),
    })
    @RequestMapping(value = "/admin/building/update/status", method = RequestMethod.PUT)
    public ResponseBean buildingUpdateStatus(@RequestBody String parameter, HttpServletRequest request) {
        return taBuildingService.buildingUpdateStatus(parameter, getOrgId(request));
    }

    /**
     * 楼盘删除
     *
     * @param id
     * @param request
     * @return
     */
    @ApiOperation(value = "项目发布", notes = "项目发布")
    @ApiImplicitParams({
            @ApiImplicitParam(dataTypeClass = String.class, paramType = "path", name = "id", value = "项目id"),
    })
    @RequestMapping(value = "/admin/building/delete/{id}", method = RequestMethod.DELETE)
    public ResponseBean buildingdelete(@PathVariable("id") String id, HttpServletRequest request) {
        return taBuildingService.buildingdelete(id, getOrgId(request));
    }

    /**
     * 添加户型
     *
     * @param parameter
     * @param session
     * @return
     */
    @ApiOperation(value = "添加户型", notes = "添加户型")
    @RequestMapping(value = "/admin/buildingApartment/add", method = RequestMethod.POST)
    public ResponseBean buildingApartment(@RequestBody String parameter, HttpServletRequest request) {
        return taBuildingService.buildingApartmentAdd(parameter);
    }

    /**
     * 户型编辑
     *
     * @param parameter
     * @return
     */
    @ApiOperation(value = "户型编辑", notes = "户型编辑")
    @RequestMapping(value = "/admin/buildingApartment/update", method = RequestMethod.PUT)
    public ResponseBean buildingApartmentUpdate(@RequestBody String parameter) {
        return taBuildingService.buildingApartmentUpdate(parameter);
    }

    /**
     * 户型详情
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "户型详情", notes = "户型详情")
    @ApiImplicitParams({
            @ApiImplicitParam(dataTypeClass = String.class, paramType = "path", name = "id", value = "户型id"),
    })
    @RequestMapping(value = "/admin/buildingApartment/{id}", method = RequestMethod.GET)
    public ResponseBean buildingApartmentSelectId(@PathVariable(value = "id") String id) {
        return taBuildingService.buildingApartmentSelectId(id);
    }

    /**
     * 依据项目ID 查户型
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "依据项目ID 查户型", notes = "依据项目ID 查户型")
    @ApiImplicitParams({
            @ApiImplicitParam(dataTypeClass = String.class, paramType = "path", name = "id", value = "项目ID"),
            @ApiImplicitParam(dataTypeClass = String.class, paramType = "query", name = "apartmentType", value = "类型"),
    })
    @RequestMapping(value = "/admin/buildingApartment/buildingId/{id}", method = RequestMethod.GET)
    public ResponseBean buildingApartmentBuildingId(@PathVariable(value = "id") String id,
                                                    @RequestParam(value = "apartmentType", required = false) String apartmentType) {
        return taBuildingService.buildingApartmentBuildingId(id, apartmentType);
    }

    /**
     * 微信楼盘列表
     *
     * @return
     */
    @RequestMapping(value = "/wx/building/list", method = RequestMethod.GET)
    public ResponseBean getWxBuildingList(
            @RequestParam(defaultValue = "1") Integer pageNumber,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(defaultValue = "false") Boolean mine,
            @RequestParam(required = false) Integer cityId,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String buildingType, // 项目类型Id
            @RequestParam(required = false) String houseType, // 户型
            @RequestParam(required = false) String price,   // 价格
            @RequestParam(required = false) String priceType,   // 价格类型
            @RequestParam(required = false) String area,    // 面积
//            @RequestParam(required = false) Integer minPrice, // 最低价格
//            @RequestParam(required = false) Integer maxPrice, // 最高价格
//            @RequestParam(required = false) Double minBuildingArea, // 最小面积
//            @RequestParam(required = false) Double maxBuildingArea, // 最大面积
            HttpServletRequest request
    ) {
        Integer orgId = getOrgId(request);
        List<String> targets = null;
        if (null != mine && mine) {
            String openid = getOpenId(request);
            List<TaPerson> persons = iTaPersonService.getPersonsByOpenId(openid);
            if (null == persons || persons.size() == 0) {
                return ResponseBean.error("当前账户信息异常, 清除缓存重试", ResponseBean.ERROR_UNAVAILABLE);
            }

            targets = iTaSaveService.getTargesOfPerson(persons.get(0).getPersonId(), CommConstant.FAVOR_PROJECT);
        }

        String[] buildingTypeList = !StringUtils.isEmpty(buildingType) ? buildingType.split(",") : null;
        String[] houseTypeList = !StringUtils.isEmpty(houseType) ? houseType.split(",") : null;
        List<String[]> priceList = getParamListOf(price);
        List<String[]> areaList = getParamListOf(area);

        return taBuildingService.getWxBuildingList(pageNumber, pageSize, name, targets, cityId, mine, houseTypeList, buildingTypeList, priceList, areaList, orgId, priceType);
    }


    /**
     * 先按照 逗号 拆分, 再按照 横线 拆分
     *
     * @param params
     * @return
     */
    private List<String[]> getParamListOf(String params) {
        List<String[]> paramList = new ArrayList<>();

        if (null == params || "".equals(params.trim())) {
            return paramList;
        }

        String[] paramsArray = params.split(",");
        for (String param : paramsArray) {
            paramList.add(param.split("-"));
        }

        return paramList;
    }


    /**
     * 微信推荐楼盘列表
     *
     * @return
     */
    @RequestMapping(value = "/wx/building/main", method = RequestMethod.GET)
    public ResponseBean getWxMainBuildingList(@RequestParam(value = "cityId", required = false) String cityId, HttpServletRequest request) {
        Integer orgId = getOrgId(request);
        return taBuildingService.getWxMainBuildingList(cityId, orgId);
    }

    /**
     * 删除户型
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/admin/apartment/deleted/{id}", method = RequestMethod.DELETE)
    public ResponseBean apartmentDeleted(@PathVariable(value = "id") String id) {
        return taBuildingService.apartmentDel(id);
    }

    /**
     * 微信楼盘详情
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/wx/buildingSelectId/{id}", method = RequestMethod.GET)
    @ReportCustomer(type = "building")
    public ResponseBean wxBuildingSelectId(@PathVariable(value = "id") String id,
                                           @RequestParam(value = "qrCodeId", required = false) String qrCodeId,
                                           @RequestParam(value = "channelId", required = false) String channelId,
                                           @RequestParam(value = "sceneId", required = false) String sceneId,
                                           HttpServletRequest request) {
        String openid = getOpenId(request);
        Integer orgId = getOrgId(request);
        List<TaPerson> persons = iTaPersonService.getPersonsByOpenId(openid);
        if (null == persons || persons.size() == 0) {
            return ResponseBean.error("当前账户信息异常, 清除缓存重试", ResponseBean.ERROR_UNAVAILABLE);
        }
        TaPerson person = persons.get(0);
        return taBuildingService.buildingAllSelectId(id, person, orgId);
    }

    /**
     * 查询当前所有项目
     */
    @RequestMapping(value = "/admin/buildingAll", method = RequestMethod.GET)
    public ResponseBean buildingAll(HttpServletRequest request) {
        ResponseBean taBuilding = taBuildingService.buildingAll(getOrgId(request));
        return taBuilding;
    }

    /**
     * 校验楼盘是否可以添加
     */
    @RequestMapping(value = "/admin/verifyMax", method = RequestMethod.GET)
    public ResponseBean verifyMax(HttpServletRequest request) {
        // 根据orgId查询当前楼盘最大数
        TaOrg taOrg = taOrgMapper.selectById(getOrgId(request));
        QueryWrapper<TaBuilding> taBuildingQuery = new QueryWrapper<>();
        taBuildingQuery.eq("org_id", getOrgId(request));
        taBuildingQuery.gt("status", -1);
        int orgNum = taBuildingMapper.selectCount(taBuildingQuery);
        if (orgNum >= taOrg.getBuildingNum()) {
            return ResponseBean.error("当前系统仅供维护" + taOrg.getBuildingNum() + "个项目，需要维护更多项目，请联系相关管理人员", ResponseBean.ERROR_UNAVAILABLE);
        }
        return ResponseBean.success("成功");
    }
}

