package com.yuchen.saas.park.service.service.property.impl;

import cn.hutool.core.lang.Validator;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.metadata.CellExtra;
import com.alibaba.excel.read.listener.ReadListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuchen.saas.integration.feign.api.util.PageConverterUtils;
import com.yuchen.saas.park.api.dto.property.PropertyHouseResidentDto;
import com.yuchen.saas.park.api.dto.property.PropertyHouseResidentQueryDto;
import com.yuchen.saas.park.api.entity.park.PmgBatParkInfo;
import com.yuchen.saas.park.api.entity.property.*;
import com.yuchen.saas.park.api.enums.property.*;
import com.yuchen.saas.park.api.vo.property.*;
import com.yuchen.saas.park.service.mapper.property.PropertyHouseResidentMapper;
import com.yuchen.saas.park.service.service.PmgBatParkInfoService;
import com.yuchen.saas.park.service.service.property.*;
import com.yuchen.saas.park.service.service.property.bill.PropertyBillService;
import lombok.extern.slf4j.Slf4j;
import org.nest.springwrap.core.log.exception.ServiceException;
import org.nest.springwrap.core.mp.base.BaseServiceImpl;
import org.nest.springwrap.core.mp.support.NestPage;
import org.nest.springwrap.core.secure.ContextUser;
import org.nest.springwrap.core.secure.utils.AuthUtil;
import org.nest.springwrap.core.tool.utils.BeanUtil;
import org.nest.springwrap.core.tool.utils.Func;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author 蔡文强
 * @Date 2023/11/28 10:56
 * @Description 房产住户表 服务实现类
 */
@Slf4j
@Service
public class PropertyHouseResidentServiceImpl extends BaseServiceImpl<PropertyHouseResidentMapper, PropertyHouseResident> implements IPropertyHouseResidentService {

    @Resource
    private PmgBatParkInfoService parkInfoService;
    @Resource
    private IPropertyCustomerArchivesService customerArchivesService;
    @Resource
    private IPropertyHouseOwnerService houseOwnerService;
    @Resource
    private PropertyHousesService housesService;
    @Lazy
    @Resource
    private IPropertyUserHouseService userHouseService;
    @Resource
    private PropertyBillService propertyBillService;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveOrUpdateHouseResident(PropertyHouseResidentDto houseResidentDto) {
        PropertyHouseResident houseResident = BeanUtil.copyProperties(houseResidentDto, PropertyHouseResident.class);
        if (Func.isEmpty(houseResidentDto.getId())) {
            ContextUser contextUser = AuthUtil.getUser();
            if (Func.isEmpty(contextUser)) {
                throw new ServiceException("用户不存在");
            }
            houseResident.setCreateType(CreateTypeEnum.BACK_ADD.getValue());
            Long registerPeopleId = contextUser.getUserDetailId();
            houseResident.setCreatePeopleId(registerPeopleId);
            if (Func.isNotEmpty(houseResidentDto.getStartDate()) && houseResidentDto.getStartDate().after(new Date())) {
                houseResident.setResidentStatus(ResidentStatusEnum.INVALID.getValue());
            } else if (Func.isNotEmpty(houseResidentDto.getStartDate()) && houseResidentDto.getStartDate().before(new Date())) {
                houseResident.setResidentStatus(ResidentStatusEnum.NORMAL.getValue());
            } else if (Func.isNotEmpty(houseResidentDto.getEndDate()) && houseResidentDto.getEndDate().before(new Date())) {
                houseResident.setResidentStatus(ResidentStatusEnum.INVALID.getValue());
            } else {
                houseResident.setResidentStatus(ResidentStatusEnum.NORMAL.getValue());
            }
            save(houseResident);
        } else {
            updateById(houseResident);
        }
        //同步客户档案
        PropertyCustomerArchives customerArchives = customerArchivesService.getCustomerArchivesById(houseResidentDto.getCustomerArchivesId());
        Integer count = customerArchivesService.lambdaQuery().eq(PropertyCustomerArchives::getCustomerType, CustomerTypeEnum.PERSON.getValue())
                .eq(PropertyCustomerArchives::getLinkPhoneOne, houseResidentDto.getLinkPhoneOne())
                .ne(PropertyCustomerArchives::getId, customerArchives.getId()).count();
        if (count > 0) {
            throw new ServiceException("个人类型客户该手机号已存在，不能重复添加");
        }
        customerArchives.setSex(houseResidentDto.getSex());
        customerArchives.setIdType(houseResidentDto.getIdType());
        customerArchives.setIdNo(houseResidentDto.getIdNo());
        customerArchives.setLinkPhoneOne(houseResidentDto.getLinkPhoneOne());
        customerArchives.setFacePhoto(houseResidentDto.getFacePhoto());
        customerArchives.setIsLink(YesOrNoEnum.YES.getValue());
        return customerArchivesService.updateById(customerArchives);
    }

    @Override
    public Boolean deleteHouseResident(Long id) {
        List<PropertyBill> propertyBillList = propertyBillService.lambdaQuery().in(PropertyBill::getPayStatus, 1, 2, 3)
                .eq(PropertyBill::getCustomerId, id).list();
        if (Func.isNotEmpty(propertyBillList)) {
            throw new ServiceException("该住户有未结账单，不能移除");
        }
        //小程序用户端状态更新
        PropertyUserHouse userHouse = userHouseService.lambdaQuery().eq(PropertyUserHouse::getLinkId, id).one();
        if (Func.isNotEmpty(userHouse)) {
            userHouse.setIsInvalid(1);
            userHouseService.updateById(userHouse);
        }
        return removeById(id);
    }

    @Override
    public PropertyHouseResidentVo getHouseResidentById(Long id) {
        PropertyHouseResident houseResident = getById(id);
        if (Func.isEmpty(houseResident)) {
            throw new ServiceException("房产住户不存在");
        }
        PropertyHouseResidentVo houseResidentVo = BeanUtil.copyProperties(houseResident, PropertyHouseResidentVo.class);
        PropertyHouses propertyHouses = housesService.getById(houseResidentVo.getHouseId());
        houseResidentVo.setHouseName(propertyHouses.getHouseName());
        PropertyHouseOwner houseOwner = houseOwnerService.getById(houseResidentVo.getOwnerId());
        if (Func.isEmpty(houseOwner)) {
            throw new ServiceException("房产业主不存在");
        }
        PropertyCustomerArchives ownerCustomerArchives = customerArchivesService.getCustomerArchivesById(houseOwner.getCustomerArchivesId());
        if (Func.isEmpty(ownerCustomerArchives)) {
            throw new ServiceException("房产业主客户档案不存在");
        }
        houseResidentVo.setOwnerName(ownerCustomerArchives.getCustomerName());
        PropertyCustomerArchives customerArchives = customerArchivesService.getCustomerArchivesById(houseResidentVo.getCustomerArchivesId());
        houseResidentVo.setResidentName(customerArchives.getCustomerName());
        houseResidentVo.setLinkPhoneOne(customerArchives.getLinkPhoneOne());
        houseResidentVo.setIdType(customerArchives.getIdType());
        houseResidentVo.setIdNo(customerArchives.getIdNo());
        houseResidentVo.setSex(customerArchives.getSex());
        houseResidentVo.setFacePhoto(customerArchives.getFacePhoto());
        return houseResidentVo;
    }

    @Override
    public NestPage<PropertyHouseResidentListVo> getHouseResidentPageList(PropertyHouseResidentQueryDto queryDto) {
        if (Func.isNotEmpty(queryDto.getBuildingId())) {
            List<Long> houseIdList = housesService.listByBuildingId(queryDto.getBuildingId()).stream().map(PropertyHouses::getId).collect(Collectors.toList());
            queryDto.setHouseIdList(houseIdList);
        }
        // 分页获取数据
        Page<PropertyHouseResidentListVo> page = new Page<>(queryDto.getCurrent(), queryDto.getSize());
        page = baseMapper.getHouseResidentPageList(page, queryDto);
        List<PropertyHouseResidentListVo> list = page.getRecords();
        Map<Long, String> parkMap = getParkMap();
        for (PropertyHouseResidentListVo vo : list) {
            vo.setParkName(parkMap.get(vo.getParkId()));
            PropertyHouseOwner houseOwner = houseOwnerService.getById(vo.getOwnerId());
            if (Func.isNotEmpty(houseOwner)) {
                PropertyCustomerArchives ownerCustomerArchives = customerArchivesService.getCustomerArchivesById(houseOwner.getCustomerArchivesId());
                if (Func.isEmpty(ownerCustomerArchives)) {
                    throw new ServiceException("业主客户档案不存在");
                }
                vo.setOwnerName(ownerCustomerArchives.getCustomerName());
            }
            PropertyHousesVo propertyHousesVo = housesService.getPropertyHousesDetail(vo.getHouseId());
            vo.setHouseCode(propertyHousesVo.getResourceCode());
        }
        return PageConverterUtils.convert(page);
    }

    @Override
    public PropertyHouseResidentImportResVo importHouseResident(MultipartFile file) {
        if (!(file.getOriginalFilename().endsWith(".xlsx") || file.getOriginalFilename().endsWith(".xls"))) {
            throw new ServiceException("请选择正确的excel文件");
        }
        PropertyHouseResidentImportResVo vo = new PropertyHouseResidentImportResVo();
        vo.setImportSize(0);
        vo.setFailSize(0);
        vo.setSuccessSize(0);
        List<String> msg = new ArrayList<>();
        vo.setMsg(msg);
        List<PmgBatParkInfo> list = parkInfoService.list();
        Map<String, PmgBatParkInfo> parkMap = list.stream().collect(Collectors.toMap(PmgBatParkInfo::getParkName, a -> a));
        List<PropertyHouses> houseList = housesService.list();
        Map<String, PropertyHouses> houseMap = houseList.stream().collect(Collectors.toMap(PropertyHouses::getResourceCode, a -> a));
        try {
            EasyExcel.read(file.getInputStream(),
                    PropertyHouseResidentImportExcelVo.class, new ReadListener() {

                        @Override
                        public void onException(Exception exception, AnalysisContext context) throws Exception {
                            log.error("导出异常", exception);
                            log.info("context", context);
                            vo.setFailSize(vo.getFailSize() + 1);
                            Integer rowIndex = context.readRowHolder().getRowIndex() - 1;
                            vo.getMsg().add(String.format("第%s条导入失败,失败原因:%s;", rowIndex, exception.getMessage()));
                        }

                        @Override
                        public void invokeHead(Map headMap, AnalysisContext context) {
                            log.info("context", context);
                            log.info("headMap", headMap);
                        }

                        @Override
                        public void invoke(Object o, AnalysisContext analysisContext) {
                            vo.setImportSize(vo.getImportSize() + 1);
                            PropertyHouseResidentImportExcelVo importVo = (PropertyHouseResidentImportExcelVo) o;
                            saveImport(importVo, parkMap, houseMap);

                        }

                        @Override
                        public void extra(CellExtra extra, AnalysisContext context) {
                            log.info("extra", context);
                        }

                        @Override
                        public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                            log.info("analysisContext", analysisContext);
                        }

                        @Override
                        public boolean hasNext(AnalysisContext context) {
                            return true;
                        }
                    }).sheet().doRead();
        } catch (IOException e) {
            log.info("导入异常", e);
        }

        return vo;
    }

    @Transactional(rollbackFor = Exception.class)
    public void saveImport(PropertyHouseResidentImportExcelVo importVo,  Map<String, PmgBatParkInfo> parkMap, Map<String, PropertyHouses> houseMap) {
        PropertyHouseResident houseResident = new PropertyHouseResident();
        BeanUtils.copyProperties(importVo,houseResident);
        if (Func.isBlank(importVo.getParkName())){
            throw new ServiceException("园区不能为空");
        }
        if (Func.isBlank(importVo.getHouseCode())){
            throw new ServiceException("房间不能为空");
        }
        if (Func.isBlank(importVo.getOwnerName())){
            throw new ServiceException("业主不能为空");
        }
        if (Func.isBlank(importVo.getRelation())){
            throw new ServiceException("与业主的关系不能为空");
        }
        if (Func.isBlank(importVo.getResidentName())){
            throw new ServiceException("住户姓名不能为空");
        }
        if (Func.isBlank(importVo.getLinkPhoneOne())){
            throw new ServiceException("联系电话不能为空");
        }
        if (!Validator.isMobile(importVo.getLinkPhoneOne())) {
            throw new ServiceException("联系电话格式错误");
        }

        String parkName = importVo.getParkName().replaceAll("\\s*", "");
        if (parkMap.containsKey(parkName)) {
            PmgBatParkInfo parkInfo = parkMap.get(parkName);
            houseResident.setParkId(parkInfo.getId());
        } else {
            throw new ServiceException("园区名称不存在");
        }

        String houseCode = importVo.getHouseCode().replaceAll("\\s*", "");
        if (houseMap.containsKey(houseCode)) {
            PropertyHouses houses = houseMap.get(houseCode);
            houseResident.setHouseId(houses.getId());
        } else {
            throw new ServiceException("房间不存在");
        }

        //业主姓名
        List<PropertyCustomerArchives> customerArchivesList = customerArchivesService.lambdaQuery().eq(PropertyCustomerArchives::getCustomerName, importVo.getOwnerName())
                .eq(PropertyCustomerArchives::getCustomerCategory, CustomerCategoryEnum.HOUSE_OWNER.getValue()).list();

        if (Func.isEmpty(customerArchivesList)) {
            throw new ServiceException("业主不存在");
        }
        List<Long> idList = customerArchivesList.stream().map(PropertyCustomerArchives::getId).collect(Collectors.toList());
        PropertyHouseOwner houseOwner = houseOwnerService.lambdaQuery().in(PropertyHouseOwner::getCustomerArchivesId, idList).last("LIMIT 1").one();
        if (Func.isEmpty(houseOwner)) {
            throw new ServiceException("业主不存在");
        }
        houseResident.setOwnerId(houseOwner.getId());

        Integer idType = null;
        if (Func.isNotEmpty(importVo.getIdTypeName())) {
            String idTypeName = importVo.getIdTypeName().replaceAll("\\s*", "");
            if (idTypeName.equals(IdTypeEnum.getDescByCode(IdTypeEnum.ID_CARD.getValue()))) {
                idType = IdTypeEnum.ID_CARD.getValue();
            } else {
                throw new ServiceException("证件类型不存在");
            }
        }
        String idNo = null;
        if (Func.isNotEmpty(importVo.getIdNo())) {
            idNo = importVo.getIdNo();
        }
        Integer sex = null;
        if (Func.isNotEmpty(importVo.getSexName())) {
            String sexName = importVo.getSexName().replaceAll("\\s*", "");
            if (sexName.equals(SexEnum.getDescByCode(SexEnum.MALE.getValue()))) {
                sex=SexEnum.MALE.getValue();
            } else if (sexName.equals(SexEnum.getDescByCode(SexEnum.FEMALE.getValue()))) {
                sex=SexEnum.FEMALE.getValue();
            } else {
                throw new ServiceException("性别不存在");
            }
        }
        ContextUser contextUser = AuthUtil.getUser();
        if (Func.isEmpty(contextUser)) {
            throw new ServiceException("用户不存在");
        }
        //判断客户档案存不存在该住户
        PropertyCustomerArchives customerArchives = customerArchivesService.lambdaQuery().eq(PropertyCustomerArchives::getCustomerName, importVo.getOwnerName())
                .eq(PropertyCustomerArchives::getCustomerType, CustomerTypeEnum.PERSON)
                .eq(PropertyCustomerArchives::getLinkPhoneOne, importVo.getLinkPhoneOne())
                .eq(PropertyCustomerArchives::getCustomerCategory, CustomerCategoryEnum.OWNER_MEMBER.getValue()).one();
        if (Func.isNotEmpty(customerArchives)) {
            if(Func.isNotEmpty(idType)) customerArchives.setIdType(idType);
            if(Func.isNotEmpty(idNo)) customerArchives.setIdNo(idNo);
            if(Func.isNotEmpty(sex)) customerArchives.setSex(sex);
            customerArchives.setIsLink(YesOrNoEnum.YES.getValue());
            customerArchivesService.updateById(customerArchives);
            houseResident.setCustomerArchivesId(customerArchives.getId());
        } else { //不存在同步客户档案
            PropertyCustomerArchives add = new PropertyCustomerArchives();
            add.setParkId(houseResident.getParkId());
            add.setCustomerType(CustomerTypeEnum.PERSON.getValue());
            add.setCustomerCategory(CustomerCategoryEnum.OWNER_MEMBER.getValue());
            add.setCustomerName(importVo.getResidentName());
            if(Func.isNotEmpty(idType)) add.setIdType(idType);
            if(Func.isNotEmpty(idNo)) add.setIdNo(idNo);
            if(Func.isNotEmpty(sex)) add.setSex(sex);
            add.setLinkManOne(importVo.getResidentName());
            add.setLinkPhoneOne(importVo.getLinkPhoneOne());
            add.setCreateType(CreateTypeEnum.AUTO_SYNC.getValue());
            add.setCreatePeopleId(contextUser.getUserDetailId());
            add.setIsLink(YesOrNoEnum.YES.getValue());
            customerArchivesService.save(add);
            houseResident.setCustomerArchivesId(add.getId());
        }
        houseResident.setCreateType(CreateTypeEnum.BACK_ADD.getValue());
        houseResident.setCreatePeopleId(contextUser.getUserDetailId());
        houseResident.setRegisterStatus(RegisterStatusEnum.NO.getValue());
        houseResident.setResidentStatus(ResidentStatusEnum.NORMAL.getValue());
        //判断住户是否存在
        LambdaQueryWrapper<PropertyHouseResident> isExitQuery = Wrappers.lambdaQuery();
        isExitQuery.eq(PropertyHouseResident::getParkId, houseResident.getParkId());
        isExitQuery.eq(PropertyHouseResident::getHouseId, houseResident.getHouseId());
        isExitQuery.eq(PropertyHouseResident::getOwnerId, houseResident.getOwnerId());
        isExitQuery.eq(PropertyHouseResident::getCustomerArchivesId, houseResident.getCustomerArchivesId());
        PropertyHouseResident isExit = this.getOne(isExitQuery);
        if (Func.isNotEmpty(isExit)) {
            removeById(isExit.getId());
        }
        this.save(houseResident);
    }

    @Override
    public void exportHouseResident(PropertyHouseResidentQueryDto queryDto, HttpServletResponse response) {
        if (Func.isNotEmpty(queryDto.getBuildingId())) {
            List<Long> houseIdList = housesService.listByBuildingId(queryDto.getBuildingId()).stream().map(PropertyHouses::getId).collect(Collectors.toList());
            queryDto.setHouseIdList(houseIdList);
        }
        List<PropertyHouseResidentListVo> list = baseMapper.getHouseResidentList(queryDto);
        List<PropertyHouseResidentExcelVo> excelVoList = BeanUtil.copyProperties(list, PropertyHouseResidentExcelVo.class);
        Map<Long, String> parkMap = getParkMap();
        excelVoList.forEach(excelVo -> {
            excelVo.setParkName(parkMap.get(excelVo.getParkId()));

            PropertyHouseOwner houseOwner = houseOwnerService.getById(excelVo.getOwnerId());
            if (Func.isNotEmpty(houseOwner)) {
                PropertyCustomerArchives ownerCustomerArchives = customerArchivesService.getCustomerArchivesById(houseOwner.getCustomerArchivesId());
                if (Func.isEmpty(ownerCustomerArchives)) {
                    throw new ServiceException("业主客户档案不存在");
                }
                excelVo.setOwnerName(ownerCustomerArchives.getCustomerName());
            }
            excelVo.setSexName(SexEnum.getDescByCode(excelVo.getSex()));
            excelVo.setIdTypeName(IdTypeEnum.getDescByCode(excelVo.getIdType()));
            excelVo.setCreateTypeName(CreateTypeEnum.getDescByCode(excelVo.getCreateType()));
            PropertyHousesVo propertyHousesVo = housesService.getPropertyHousesDetail(excelVo.getHouseId());
            excelVo.setHouseCode(propertyHousesVo.getResourceCode());
        });

        try {
            String fileName = URLEncoder.encode("房产住户表", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), PropertyHouseResidentExcelVo.class)
                    .sheet("房产住户表")
                    .doWrite(excelVoList); //最终处理好的数据结果集list
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * @description 获取园区信息列表Map
     */
    private Map<Long, String> getParkMap() {
        List<PmgBatParkInfo> parkList = parkInfoService.getAllPark();
        return parkList.stream().collect(Collectors.toMap(PmgBatParkInfo::getId, PmgBatParkInfo::getParkName));
    }


    @Override
    public PropertyTenantOwnerVo getTenantOrOwnerInfo(long hoseId) {
        PropertyTenantOwnerVo vo = this.baseMapper.getTenantOrOwnerInfo(hoseId);
        if (vo != null && Func.isNotEmpty(vo.getCustomerArchivesId())) {
            PropertyCustomerArchivesVo archivesVo = customerArchivesService.getCustomerArchivesById(vo.getCustomerArchivesId());
            if (archivesVo != null) {
                vo.setCustomerArchivesId(archivesVo.getId());
                vo.setCustomerName(archivesVo.getCustomerName());
                vo.setPhone(archivesVo.getLinkPhoneOne());
                vo.setIdNo(archivesVo.getIdNo());
            }

        }
        return vo;
    }
}
