package com.huiju.estateagents.property.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huiju.estateagents.base.BaseController;
import com.huiju.estateagents.base.ResponseBean;
import com.huiju.estateagents.center.taUser.entity.TaUser;
import com.huiju.estateagents.common.DateUtils;
import com.huiju.estateagents.common.ExcelUtils;
import com.huiju.estateagents.common.StringUtils;
import com.huiju.estateagents.excel.TpBuildingOwnerInfoExport;
import com.huiju.estateagents.property.common.UserElement;
import com.huiju.estateagents.property.model.TaFace;
import com.huiju.estateagents.property.model.TaUserVerify;
import com.huiju.estateagents.property.model.TpBuildingOwnerInfo;
import com.huiju.estateagents.property.service.IBuildingOwnerInfoService;
import com.huiju.estateagents.property.service.ITaFaceService;
import com.huiju.estateagents.property.service.ITaUserVerifyService;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 楼栋业主资料信息表 前端控制器
 * </p>
 *
 * @author weiximei
 * @since 2018-12-18
 */
@RestController

@RequestMapping("/api")
@Api(value = "楼栋业主资料信息", tags = "楼栋业主资料信息 Api")
public class BuildingOwnerInfoController extends BaseController {

    @Autowired
    private IBuildingOwnerInfoService iBuildingOwnerInfoService;

    @Autowired
    private ITaUserVerifyService iTaUserVerifyService;

    @Autowired
    private ITaFaceService iTaFaceService;

    // @ApiOperation(value = "获取楼栋业主信息", notes = "根据条件获取")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body", dataTypeClass = String.class, name = "parameter",value = "buildingId栋;" +
                    "unitId单元;levelId楼层;roomNoId户号;" +
                    "ownerName业主姓名;" +"ownerTel业主手机号;" +"idCard身份证;" +
                    "pageNum第几页;pageSize 一页多少行;")
    })
    @RequestMapping(value = "/admin/buildingInfo/list", method = RequestMethod.POST)
    public ResponseBean getList(@RequestBody String parameter, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        TaUser userElement = getTaUser(request);
        responseBean = iBuildingOwnerInfoService.listQuery(parameter, userElement);
        return responseBean;
    }

    /**
     * 业主导出
     * @param parameter
     * @param request
     * @return
     */
    @RequestMapping(value = "/admin/buildingInfo/list/export", method = RequestMethod.POST)
    public ResponseBean getListExport(@RequestBody String parameter,
                                      HttpServletRequest request,
                                      HttpServletResponse response){
        ResponseBean responseBean = new ResponseBean();
        TaUser userElement = getTaUser(request);
        responseBean = iBuildingOwnerInfoService.listQuery(parameter, userElement);

        List<TpBuildingOwnerInfo> records = (List<TpBuildingOwnerInfo>) ((Map<String, Object>) responseBean.getData()).get("list");

        if (null != records) {
            List<TpBuildingOwnerInfoExport> list = new ArrayList<>();
            for (TpBuildingOwnerInfo item: records) {
                TpBuildingOwnerInfoExport ownerInfo = new TpBuildingOwnerInfoExport();
                ownerInfo.setOwnerName(item.getOwnerName());
                ownerInfo.setIdCard(item.getIdCard());
                ownerInfo.setOwnerTel(item.getOwnerTel());
                ownerInfo.setSex(getSexFromIdCard(item.getIdCard()));
                ownerInfo.setRoomNoName(item.getPhaseName()+item.getBuildingName()+item.getUnitName()+item.getLevelName()+item.getRoomNoName());
                ownerInfo.setRoleName(item.getRoleName());
                ownerInfo.setVerifyStatus("0".equals(item.getVerifyStatus()) ? "未审核" : ("1".equals(item.getVerifyStatus()) ? "审核通过" : ("1".equals(item.getVerifyStatus()) ? "审核不通过": "") ));
                ownerInfo.setCreateDate(DateUtils.format(item.getCreateDate(), "yyyy-MM-dd HH:mm"));
                list.add(ownerInfo);
            }

            try {
                ExcelUtils.flush(response, TpBuildingOwnerInfoExport.class, list, "业主记录.xlsx");
                return null;
            } catch (IOException e) {
                return ResponseBean.error("导出 Excel 失败 "+ e.getMessage(), ResponseBean.ERROR_UNAVAILABLE);
            }
        }

        return responseBean;
    }

    private String getSexFromIdCard(String idCard) {
        if (StringUtils.isEmpty(idCard) || idCard.length() != 18) {
            return null;
        }

        String sign = idCard.split("")[16];

        return Integer.parseInt(sign) % 2 == 1 ? "男" : "女";
    }


    // @ApiOperation(value = "获取楼栋业主审核详情", notes = "获取楼栋业主审核详情")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Integer.class, name = "userVerifyId",value = "审核Id")
    })
    @RequestMapping(value = "/admin/buildingInfo//verify/{userVerifyId}", method = RequestMethod.GET)
    public ResponseBean getById(@PathVariable(value = "userVerifyId") Integer userVerifyId) {
        ResponseBean responseBean = new ResponseBean();

        TaUserVerify userVerify = iTaUserVerifyService.getById(userVerifyId);
        if (null == userVerify) {
            responseBean.addError("审核数据不存在！");
            return responseBean;
        }
//        TaUser user = iTaUserService.getById(userVerify.getUserId());
        Map<String, Object> map = Maps.newHashMap();
        map.put("verify", userVerify);
//        map.put("info", user);

        // true 标识业主 false 非业主
        map.put("boolRole", false);

        // 默认人脸未录入
        map.put("face", "unregister");

        QueryWrapper<TaUserVerify> userVerifyQueryWrapper = new QueryWrapper<>();
        userVerifyQueryWrapper.eq("phase_id", userVerify.getPhaseId());
        userVerifyQueryWrapper.eq("building_id", userVerify.getBuildingId());
        userVerifyQueryWrapper.eq("unit_id", userVerify.getUnitId());
        userVerifyQueryWrapper.eq("level_id", userVerify.getLevelId());
        userVerifyQueryWrapper.eq("room_no_id", userVerify.getRoomNoId());
        userVerifyQueryWrapper.eq("user_id", userVerify.getPersonId());
        userVerifyQueryWrapper.eq("role_id", 1);
        TaUserVerify userVerifyOne = iTaUserVerifyService.getOne(userVerifyQueryWrapper);
        if (null != userVerifyOne) {
            map.put("boolRole", true);
        }

        // 人脸是否录入
        QueryWrapper<TaFace> faceQueryWrapper = new QueryWrapper<>();
        faceQueryWrapper.eq("ta_user_verify_id", userVerify.getId());
        TaFace face = iTaFaceService.getOne(faceQueryWrapper);
        if (null != face) {
            map.put("face", "register");
        }


        responseBean.addSuccess(map);
        return responseBean;

    }

    // @ApiOperation(value = "修改楼栋业务信息", notes = "修改楼栋业主信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body", dataTypeClass = String.class, name = "parameter",value = "userVerifyId审核编号;roleId角色编号;verifyStatus审核 true通过；false不通过;remark备注"),

    })
    @RequestMapping(value = "/admin/buildingInfo/update", method = RequestMethod.PUT)
    public ResponseBean update(@RequestBody String parameter, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        TaUser userElement = getTaUser(request);
        responseBean = iBuildingOwnerInfoService.update(parameter, userElement);
        return responseBean;
    }

    // @ApiOperation(value = "添加楼栋业务信息", notes = "添加楼栋业务信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body", dataTypeClass = String.class, name = "parameter", value = "phaseId期;buildingId栋;" +
                    "unitId单元;levelId楼层;roomNoId户号;" +
                    "ownerName业主姓名;" +
                    "ownerTel业主手机号;roleId角色id;gender性别 1：男   2：女;"),

    })
    @RequestMapping(value = "/admin/buildingInfo/add", method = RequestMethod.POST)
    public ResponseBean add(@RequestBody String parameter, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        TaUser userElement = getTaUser(request);
        responseBean = iBuildingOwnerInfoService.add(parameter, userElement);
        return responseBean;
    }

    // @ApiOperation(value = "批量删除楼栋业主信息", notes = "批量删除楼栋业主信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body", dataTypeClass = String.class, name = "ids",value = "id集合"),

    })
    @RequestMapping(value = "/admin/buildingInfo/delete", method = RequestMethod.DELETE)
    public ResponseBean delete(@RequestBody List<Integer> ids, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        TaUser userElement = getTaUser(request);
        responseBean = iBuildingOwnerInfoService.deleteIds(ids, userElement.getUserId());
        return responseBean;
    }

    private List<Integer> getCommunityIdsBy(String communityIds) {
        List<Integer> communityIdList = new ArrayList<>();
        String[] parts = communityIds.split(",");
        for (String id : parts) {
            communityIdList.add(Integer.parseInt(id));
        }
        return communityIdList;
    }

    // @ApiOperation(value = "查询 期区", notes = "查询 期区")
    @ApiImplicitParams({
    })
    @RequestMapping(value = "/admin/buildingInfo/phase",method = RequestMethod.GET)
    public ResponseBean getPhaseList(@RequestParam Integer communityId,
                                     HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();

        TaUser userElement = getTaUser(request);
        responseBean = iBuildingOwnerInfoService.getPhaseList(userElement.getOrgId(), communityId);
        return responseBean;
    }
    
    // @ApiOperation(value = "查询 楼栋", notes = "查询 楼栋")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "phaseId",value = "期区ID")
    })
    @RequestMapping(value = "/admin/buildingInfo/building",method = RequestMethod.GET)
    public ResponseBean getBuildingList(@RequestParam Integer phaseId, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        TaUser userElement = getTaUser(request);
        responseBean = iBuildingOwnerInfoService.getBuildingList(phaseId,userElement.getOrgId());
        return responseBean;
    }
    
    // @ApiOperation(value = "查询 单元", notes = "查询 单元")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "buildingId",value = "楼栋ID")
    })
    @RequestMapping(value = "/admin/buildingInfo/unit",method = RequestMethod.GET)
    public ResponseBean getUnitList(@RequestParam Integer buildingId, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        TaUser userElement = getTaUser(request);
        responseBean = iBuildingOwnerInfoService.getUnitList(buildingId,userElement.getOrgId());
        return responseBean;
    }
    
    // @ApiOperation(value = "查询 楼层", notes = "查询 楼层")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "unitId",value = "单元ID")
    })
    @RequestMapping(value = "/admin/buildingInfo/level",method = RequestMethod.GET)
    public ResponseBean getLevelList(@RequestParam Integer unitId, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        TaUser userElement = getTaUser(request);
        responseBean = iBuildingOwnerInfoService.getLevelList(unitId,userElement.getOrgId());
        return responseBean;
    }
    
    // @ApiOperation(value = "查询 房间号", notes = "查询 房间号")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "levelId",value = "楼层ID")
    })
    @RequestMapping(value = "/admin/buildingInfo/roomno",method = RequestMethod.GET)
    public ResponseBean getRoomNoList(@RequestParam Integer levelId, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        TaUser userElement = getTaUser(request);
        responseBean = iBuildingOwnerInfoService.getRoomNoList(levelId,userElement.getOrgId());
        return responseBean;
    }
    
    // @ApiOperation(value = "上传楼栋信息接口", notes = "上传楼栋信息接口")
    @PostMapping(value = "/admin/buildingInfo/uploadExcel", consumes = "multipart/*", headers = "content-type=multipart/form-data")
    public ResponseBean uploadExcel(@RequestParam("file") MultipartFile file) {
        ResponseBean responseBean = new ResponseBean();
        responseBean = iBuildingOwnerInfoService.getExcelData(file);
        return responseBean;
    }
 
    // @ApiOperation(value = "上传楼栋信息并入库", notes = "上传楼栋信息并入库")
    @PostMapping(value = "/admin/buildingInfo/submitExcel", consumes = "multipart/*", headers = "content-type=multipart/form-data")
    public ResponseBean submitExcel(@RequestParam("file") MultipartFile file,
                                    @RequestParam("communityId") Integer communityId,
                                    HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        TaUser userElement = getTaUser(request);
        try {
            responseBean = iBuildingOwnerInfoService.submitExcelData(file, communityId, userElement);
        }catch (Exception e){
            responseBean.addError("导入数据失败" + e.getMessage());
            e.printStackTrace();
        }
        
        return responseBean;
    }

    // @ApiOperation(value = "获取已认证通过的用户信息",nickname ="获取已认证通过的用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body", dataType = "String", name = "paramets", value ="ownerName:姓名,ownerTel:手机号 ,current:每页显示多少条,current:每页显示多少条,pageSzie:当前页数")})

    @RequestMapping(value="/userPassCertification",method = RequestMethod.POST)
    public ResponseBean userPassCertification(@RequestBody String paramets, HttpServletRequest request){
        TaUser userElement = getTaUser(request);
        ResponseBean allApprove=iBuildingOwnerInfoService.selectUserApprove(paramets,userElement.getOrgId());
        return allApprove;
    }

    // @ApiOperation(value = "修改用户当前认证状态",nickname ="修改用户当前认证状态")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body", dataType = "String", name = "paramets", value ="ownerTel:手机号,verifyStatus:当前状态")})

    @RequestMapping(value="/updataPassCertification",method = RequestMethod.POST)
    public ResponseBean updataPassCertification(@RequestBody String paramets){
        ResponseBean userParent=iBuildingOwnerInfoService.updataApprove(paramets);
        return userParent;
    }

    // @ApiOperation(value = "小区楼栋资料表",nickname ="小区楼栋资料表")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body", dataType = "String", name = "paramets", value ="phase:期,building:楼栋 ,unit:单元,level:楼层，roomNo:户号， pageNum:每页显示多少条,pageSzie:当前页数"),
            })
    @RequestMapping(value="/buildinglist",method = RequestMethod.POST)
    public ResponseBean buildinglist(@RequestBody String paramets, HttpServletRequest request){
        TaUser userElement = getTaUser(request);
        ResponseBean buildinglist=iBuildingOwnerInfoService.buildinglist(paramets,userElement);
        return buildinglist;
    }

    // @ApiOperation(value = "小区楼栋资料表-查询 楼栋/单元/楼层/户号", notes = "小区楼栋资料表-查询 楼栋/单元/楼层/户号")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body", dataTypeClass = String.class, name = "parameter", value = "phase:期;building楼栋;" +
                    "unit单元;level楼层：roomNo:户号") // ;roomNo户号
    })
    @RequestMapping(value = "/buildinghouse",method = RequestMethod.POST)
    public ResponseBean puildinghouse(@RequestBody String parameter, HttpServletRequest request){
        TaUser userElement = getTaUser(request);
        ResponseBean responseBean = iBuildingOwnerInfoService.puildinghouse(parameter, userElement.getOrgId());
        return responseBean;
    }

    // @ApiOperation(value = "小区楼栋资料表-修改 楼栋/单元/楼层/户号", notes = "小区楼栋资料表-修改 楼栋/单元/楼层/户号")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body", dataTypeClass = String.class, name = "parameter", value = "phase:期；building:当前楼栋;" +
                    "unit:当前楼层单元;level:当前楼层楼层;roomNo:当前楼层楼层")
    })
    @RequestMapping(value = "/communitybuilding/update",method = RequestMethod.POST)
    public ResponseBean communitybuildingAdd(@RequestBody String parameter, HttpServletRequest request){
        TaUser userElement = getTaUser(request);
        ResponseBean responseBean = iBuildingOwnerInfoService.communitybuildingUpdate(parameter, userElement.getOrgId());
        return responseBean;
    }

    // @ApiOperation(value = "下载Excel模板(小区楼栋信息)", notes = "下载Excel模板(小区楼栋信息)")
    @ApiImplicitParams({
//            @ApiImplicitParam(dataTypeClass = String.class, paramType = "body", name = "parameter", value = "billExplain收费组说明"),

    })
    @RequestMapping(value = "/admin/buildingInfo/downloadExcel", method = RequestMethod.GET)
    public void exportExcel(@RequestParam Integer communityId,
                            HttpServletResponse response,
                            HttpServletRequest request) {
        TaUser userElement = getTaUser(request);
        XSSFWorkbook workbook = (XSSFWorkbook) iBuildingOwnerInfoService.downloadExcel(communityId, userElement).getData();
//        this.setResponseHeader(response, "业主资料库.xlsx");
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=业主资料库.xlsx");
        //响应到客户端
        try {
            OutputStream os = response.getOutputStream();
            workbook.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    // @ApiOperation(value = "住户资料详情",nickname ="住户资料详情")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body", dataType = "String", name = "paramets", value ="id:楼栋住户ID"),
            })
    @RequestMapping(value="/admin/buildingInfo/details",method = RequestMethod.POST)
    public ResponseBean buildingDetails(@RequestBody String paramets, HttpServletRequest request){
        TaUser userElement = getTaUser(request);
        ResponseBean buildinglist=iBuildingOwnerInfoService.buildingDetails(paramets,userElement);
        return buildinglist;
    }

    @RequestMapping(value = "/wx/building/select/address", method = RequestMethod.GET)
    @ApiOperation(value = "根据 小区/期/楼栋/单元/楼层/户号 (申请注册绑定)", notes = "根据 小区/期/楼栋/单元/楼层/户号")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Integer.class, name = "orgId", value = "传1"),
            @ApiImplicitParam(paramType = "query", dataTypeClass = Integer.class, name = "phaseId", value = "期"),
            @ApiImplicitParam(paramType = "query", dataTypeClass = Integer.class, name = "buildingId", value = "楼栋"),
            @ApiImplicitParam(paramType = "query", dataTypeClass = Integer.class, name = "unitId", value = "单元"),
            @ApiImplicitParam(paramType = "query", dataTypeClass = Integer.class, name = "levelId", value = "楼层")
    })
    public ResponseBean selectByAddress(@RequestParam("orgId") Integer orgId,
                                        @RequestParam(value = "communityId") Integer communityId,
                                        @RequestParam(value = "phaseId", required = false) Integer phaseId,
                                        @RequestParam(value = "buildingId",required = false) Integer buildingId,
                                        @RequestParam(value = "unitId", required = false) Integer unitId,
                                        @RequestParam(value = "levelId", required = false) Integer levelId) {

        ResponseBean responseBean = new ResponseBean();
        responseBean = iBuildingOwnerInfoService.selectBuildList(orgId, communityId, phaseId, buildingId, unitId, levelId);
        return responseBean;

    }

    @RequestMapping(value = "/wx/building/has", method = RequestMethod.GET)
    @ApiOperation(value = "根据 小区、期、楼栋、单元、楼层、户号 （并校验这个用户，是否绑定了这个房产）", notes = "根据 小区、期、楼栋、单元、楼层、户号")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Integer.class, name = "orgId", value = "传1"),
            @ApiImplicitParam(paramType = "query", dataTypeClass = Integer.class, name = "phaseId", value = "期"),
            @ApiImplicitParam(paramType = "query", dataTypeClass = Integer.class, name = "buildingId", value = "楼栋"),
            @ApiImplicitParam(paramType = "query", dataTypeClass = Integer.class, name = "unitId", value = "单元"),
            @ApiImplicitParam(paramType = "query", dataTypeClass = Integer.class, name = "levelId", value = "楼层"),
            @ApiImplicitParam(paramType = "query", dataTypeClass = Integer.class, name = "roomNoId", value = "户号"),

    })
    public ResponseBean hasBuilding(@RequestParam(value = "orgId", required = false) Integer orgId,
                                    @RequestParam(value = "phaseId", required = false) Integer phaseId,
                                    @RequestParam(value = "buildingId",required = false) Integer buildingId,
                                    @RequestParam(value = "unitId", required = false) Integer unitId,
                                    @RequestParam(value = "levelId", required = false) Integer levelId,
                                    @RequestParam(value = "roomNoId", required = false) Integer roomNoId,
                                    HttpServletRequest request){

        ResponseBean responseBean = new ResponseBean();
        String personId = getPersonId(request);
        responseBean = iBuildingOwnerInfoService.hasBuild(personId, orgId ,phaseId, buildingId, unitId, levelId, roomNoId);
        return responseBean;
    }

}
