package org.springblade.modules.yjxt.business.resident.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springblade.constant.BusinessConstant;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;

import org.springblade.core.tool.utils.Func;
import org.springblade.enums.DangerAreaResidentHouseHolderEnum;
import org.springblade.modules.baseinfo.org.entity.DeptRegionEntity;
import org.springblade.modules.baseinfo.org.service.IDeptRegionService;
import org.springblade.modules.yjxt.business.resident.dto.DangerAreaResidentInfoDTO;
import org.springblade.modules.yjxt.business.resident.entity.DangerAreaResidentInfoEntity;
import org.springblade.modules.yjxt.business.resident.service.IDangerAreaResidentService;
import org.springblade.modules.yjxt.business.resident.vo.DangerAreaResidentInfoVO;
import org.springblade.modules.yjxt.business.resident.wrapper.DanagerAreaResidentWrapper;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("galaxy-business/yj/resident")
@AllArgsConstructor
@Api(value = "应急系统危险区居民管理接口", tags = "增、删、改、查")
public class DangerAreaResidentController extends BladeController {

    private final IDangerAreaResidentService dangerAreaResidentService;

    private final IDeptRegionService deptRegionService;

    @GetMapping("/page")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dangerAreaCode", value = "行政区", paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "adName", value = "行政区名称", paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "dangerAreaName", value = "危险区名称", paramType = "query", dataType = "string"),
    })
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "分页")
    public R<IPage<DangerAreaResidentInfoVO>> page(@ApiIgnore DangerAreaResidentInfoDTO dto, Query query) {
        BladeUser user = AuthUtil.getUser();
        if(Func.isNull(dto.getDangerAreaCode())){
            if (BusinessConstant.ROLE_SYS_ADMIN.equals(user.getRoleName())) {
                dto.setDangerAreaCode(BusinessConstant.REGION_NM_ADCODE);
            } else if (BusinessConstant.ROLE_ORG_ADMIN.equals(user.getRoleName())) {
                LambdaQueryWrapper<DeptRegionEntity> wrapper = Wrappers.<DeptRegionEntity>query().lambda();
                wrapper.eq(DeptRegionEntity::getDeptId, Func.toLong(user.getDeptId()));
                wrapper.last("limit 1");
                DeptRegionEntity deptRegionEntity = deptRegionService.getOne(wrapper);
                if (Func.isNull(deptRegionEntity)){
                    return R.fail("查询失败");
                }
                dto.setDangerAreaCode(deptRegionEntity.getAdcd());
            }else if(BusinessConstant.ROLE_YJ_SERVICE_PERSON.equals(user.getRoleName())){
                LambdaQueryWrapper<DeptRegionEntity> wrapper = Wrappers.<DeptRegionEntity>query().lambda();
                wrapper.eq(DeptRegionEntity::getDeptId, Func.toLong(user.getDeptId()));
                wrapper.last("limit 1");
                DeptRegionEntity deptRegionEntity = deptRegionService.getOne(wrapper);
                if (Func.isNull(deptRegionEntity)){
                    return R.fail("查询失败");
                }
                dto.setDangerAreaCode(deptRegionEntity.getAdcd());
            }else if(BusinessConstant.ROLE_QI_ADMIN.equals(user.getRoleName())){
                LambdaQueryWrapper<DeptRegionEntity> wrapper = Wrappers.<DeptRegionEntity>query().lambda();
                wrapper.eq(DeptRegionEntity::getDeptId, Func.toLong(user.getDeptId()));
                wrapper.last("limit 1");
                DeptRegionEntity deptRegionEntity = deptRegionService.getOne(wrapper);
                if (Func.isNull(deptRegionEntity)){
                    return R.fail("查询失败");
                }
                dto.setDangerAreaCode(deptRegionEntity.getAdcd());
            }else{
                return R.fail("查询失败");
            }
        }
        IPage<DangerAreaResidentInfoVO> pages = dangerAreaResidentService.selectPage(Condition.getPage(query), dto);
        List<DangerAreaResidentInfoVO> list = pages.getRecords();
        for (DangerAreaResidentInfoVO vo:list){
            DanagerAreaResidentWrapper.build().entityVO(vo);
        }
        return R.data(pages);
    }

    @GetMapping("/family/list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "personId", value = "手机号", paramType = "query", dataType = "string"),
    })
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "分页")
    public R<List<DangerAreaResidentInfoEntity>> getFamilyMembers(@ApiIgnore DangerAreaResidentInfoDTO dto) {
        if (Func.isNull(dto.getPersonId())) {
            return R.fail("参数错误");
        }
        LambdaQueryWrapper<DangerAreaResidentInfoEntity> wrapper = Wrappers.<DangerAreaResidentInfoEntity>query().lambda();
        wrapper.eq(DangerAreaResidentInfoEntity::getPersonId, dto.getPersonId());
        if(Func.notNull(dto.getPersonName())){
            wrapper.eq(DangerAreaResidentInfoEntity::getPersonName,dto.getPersonName());
        }
        wrapper.last("limit 1");
        DangerAreaResidentInfoEntity entity=dangerAreaResidentService.getOne(wrapper);
        if (Func.isNull(entity)){
            return R.data(new ArrayList<>(0));
        }
        if (0 ==  entity.getIsHouseholder()){
            dto.setPersonName(null);
            dto.setPersonId(entity.getHouseholderId());
        }
        List<DangerAreaResidentInfoEntity> list = dangerAreaResidentService.getFamilyMembers(dto);
        return R.data(list);
    }

    @GetMapping("/detail")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "详情", notes = "传入rtuInfoEntity")
    public R<DangerAreaResidentInfoVO> detail(DangerAreaResidentInfoEntity entity) {
        DangerAreaResidentInfoEntity detail = dangerAreaResidentService.getById(entity.getId());

        return R.data(DanagerAreaResidentWrapper.build().entityVO(detail));
    }


    /**
     * 工作人员注册
     */
    @PostMapping("/record")
    @ApiOperationSupport(order = 4)
    @ApiOperation(value = "新增", notes = "")
    public R report(@RequestBody DangerAreaResidentInfoDTO dto) {
        if (Func.isNull(dto.getPersonId()) || Func.isNull(dto.getPersonName())) {
            return R.fail("参数错误");
        }
        LambdaQueryWrapper<DangerAreaResidentInfoEntity> wrapper = Wrappers.<DangerAreaResidentInfoEntity>query().lambda();
        wrapper.eq(DangerAreaResidentInfoEntity::getPersonId, dto.getPersonId());
        long count = dangerAreaResidentService.count(wrapper);
        if (count > 0) {
            return R.fail("此人员【" + dto.getPersonName() + "】已注册");
        }
        dto.setRegisterType(1);
        dangerAreaResidentService.save(dto);
        //if (!Func.isNull(dto.getIsHouseholder())) {
        // if (dto.getIsHouseholder().intValue() == DangerAreaResidentHouseHolderEnum.TYPE_YES.getCode().intValue()) {
        if (Func.notNull(dto.getFamilyMembers())) {
            List<DangerAreaResidentInfoEntity> familyMembers = dto.getFamilyMembers();
            // if (Func.notNull(familyMembers)) {
            for (DangerAreaResidentInfoEntity residentInfoEntity : familyMembers) {
                residentInfoEntity.setDangerAreaPid(dto.getDangerAreaPid());
                residentInfoEntity.setIsHouseholder(DangerAreaResidentHouseHolderEnum.TYPE_NO.getCode());
                residentInfoEntity.setHouseholderId(dto.getPersonId());
                residentInfoEntity.setRegisterType(1);
                dangerAreaResidentService.save(residentInfoEntity);
            }
            //  }
        }
        // }
        // }
        return R.status(true);
    }


    /**
     * 群众注册
     */
    @PostMapping("/register")
    @ApiOperationSupport(order = 4)
    @ApiOperation(value = "新增", notes = "")
    public R register(@RequestBody DangerAreaResidentInfoDTO dto) {
        if (Func.isNull(dto.getPersonId()) || Func.isNull(dto.getPersonName())) {
            return R.fail("参数错误");
        }
        LambdaQueryWrapper<DangerAreaResidentInfoEntity> wrapper = Wrappers.<DangerAreaResidentInfoEntity>query().lambda();
        wrapper.eq(DangerAreaResidentInfoEntity::getIsDeleted, 0);
        wrapper.eq(DangerAreaResidentInfoEntity::getPersonId, dto.getPersonId());
        long count = dangerAreaResidentService.count(wrapper);
        if (count > 0) {
            return R.fail("此人员已注册");
        }
        dto.setRegisterType(2);
        dangerAreaResidentService.save(dto);
        if (!Func.isNull(dto.getIsHouseholder())) {
            if (dto.getIsHouseholder().intValue() == DangerAreaResidentHouseHolderEnum.TYPE_YES.getCode().intValue()) {
                //户主
                List<DangerAreaResidentInfoEntity> familyMembers = dto.getFamilyMembers();
                if (Func.notNull(familyMembers)) {
                    for (DangerAreaResidentInfoEntity residentInfoEntity : familyMembers) {
                        residentInfoEntity.setDangerAreaPid(dto.getDangerAreaPid());
                        residentInfoEntity.setIsHouseholder(DangerAreaResidentHouseHolderEnum.TYPE_NO.getCode());
                        residentInfoEntity.setHouseholderId(dto.getPersonId());
                        residentInfoEntity.setRegisterType(2);
                        dangerAreaResidentService.save(residentInfoEntity);
                    }
                }
            }
        }
        return R.status(true);
    }

    @PostMapping("/location/add")
    @ApiOperationSupport(order = 4)
    @ApiOperation(value = "新增", notes = "")
    public R addLocation(@RequestBody DangerAreaResidentInfoEntity entity) {
        if (Func.isNull(entity.getId()) || Func.isNull(entity.getLatitude()) || Func.isNull(entity.getLongitude())) {
            return R.fail("参数错误");
        }
        DangerAreaResidentInfoEntity detail = dangerAreaResidentService.getById(entity.getId());
        if (Func.notNull(detail)) {
            detail.setLongitude(entity.getLongitude());
            detail.setLatitude(entity.getLatitude());
            detail.setAddress(entity.getAddress());
        }
        dangerAreaResidentService.updateById(detail);
        return R.status(true);
    }
}
