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.conditions.update.LambdaUpdateWrapper;
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.PropertyHouseOwnerDto;
import com.yuchen.saas.park.api.dto.property.PropertyHouseOwnerQueryDto;
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.PropertyHouseOwnerMapper;
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 PropertyHouseOwnerServiceImpl extends BaseServiceImpl<PropertyHouseOwnerMapper, PropertyHouseOwner> implements IPropertyHouseOwnerService {

    @Resource
    private PmgBatParkInfoService parkInfoService;
    @Resource
    private IPropertyCustomerArchivesService customerArchivesService;
    @Resource
    private PropertyHousesService housesService;
    @Lazy
    @Resource
    private IPropertyUserHouseService userHouseService;
    @Lazy
    @Resource
    private IPropertyHouseResidentService houseResidentService;
    @Resource
    private PropertyBillService propertyBillService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveHouseOwner(PropertyHouseOwnerDto houseOwnerDto) {
        if (houseOwnerDto.getOwnerType() == CustomerTypeEnum.ORGAN.getValue()) {
            if (Func.isEmpty(houseOwnerDto.getOrganType())) {
                throw new ServiceException("机构类型不能为空");
            }
            if (Func.isEmpty(houseOwnerDto.getOrganIndustry())) {
                throw new ServiceException("所属行业不能为空");
            }
            if (Func.isEmpty(houseOwnerDto.getOrganScale())) {
                throw new ServiceException("组织规模不能为空");
            }
        } else {
            if (Func.isEmpty(houseOwnerDto.getSex())) {
                throw new ServiceException("性别不能为空");
            }
        }

        PropertyHouseOwner houseOwner = BeanUtil.copyProperties(houseOwnerDto, PropertyHouseOwner.class);
        ContextUser contextUser = AuthUtil.getUser();
        if (Func.isEmpty(contextUser)) {
            throw new ServiceException("用户不存在");
        }
        Long registerPeopleId = contextUser.getUserDetailId();
        List<Long> houseIds = Func.toLongList(houseOwnerDto.getHouseIds());
        for (Long houseId : houseIds) {
            PropertyHouseOwner select = this.lambdaQuery().eq(PropertyHouseOwner::getHouseId, houseId).eq(PropertyHouseOwner::getCustomerArchivesId, houseOwnerDto.getCustomerArchivesId()).one();
            if (Func.isNotEmpty(select)) {
                continue;
            }
            houseOwner.setId(null);
            houseOwner.setHouseId(houseId);
            houseOwner.setCreatePeopleId(registerPeopleId);
            save(houseOwner);
        }
        //同步客户档案
        PropertyCustomerArchives customerArchives = customerArchivesService.getCustomerArchivesById(houseOwnerDto.getCustomerArchivesId());
        if (houseOwnerDto.getOwnerType() == OwnerTypeEnum.PERSON.getValue()) {
            Integer count = customerArchivesService.lambdaQuery().eq(PropertyCustomerArchives::getCustomerType, CustomerTypeEnum.PERSON.getValue())
                    .eq(PropertyCustomerArchives::getLinkPhoneOne, houseOwnerDto.getLinkPhoneOne())
                    .ne(PropertyCustomerArchives::getId, customerArchives.getId()).count();
            if (count > 0) {
                throw new ServiceException("个人类型客户该手机号已存在，不能重复添加");
            }
        }
        customerArchives.setOrganType(houseOwnerDto.getOrganType());
        customerArchives.setOrganIndustry(houseOwnerDto.getOrganIndustry());
        customerArchives.setOrganScale(houseOwnerDto.getOrganScale());
        customerArchives.setSex(houseOwnerDto.getSex());
        customerArchives.setIdType(houseOwnerDto.getIdType());
        customerArchives.setIdNo(houseOwnerDto.getIdNo());
        customerArchives.setLinkManOne(houseOwnerDto.getLinkManOne());
        customerArchives.setLinkPhoneOne(houseOwnerDto.getLinkPhoneOne());
        customerArchives.setIsLink(YesOrNoEnum.YES.getValue());
        return customerArchivesService.updateById(customerArchives);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateHouseOwner(PropertyHouseOwnerDto houseOwnerDto) {
        if (houseOwnerDto.getOwnerType() == CustomerTypeEnum.ORGAN.getValue()) {
            if (Func.isEmpty(houseOwnerDto.getOrganType())) {
                throw new ServiceException("机构类型不能为空");
            }
            if (Func.isEmpty(houseOwnerDto.getOrganIndustry())) {
                throw new ServiceException("所属行业不能为空");
            }
            if (Func.isEmpty(houseOwnerDto.getOrganScale())) {
                throw new ServiceException("组织规模不能为空");
            }
        } else {
            if (Func.isEmpty(houseOwnerDto.getSex())) {
                throw new ServiceException("性别不能为空");
            }
        }
        PropertyHouseOwner houseOwner = BeanUtil.copyProperties(houseOwnerDto, PropertyHouseOwner.class);
        houseOwner.setHouseId(Long.valueOf(houseOwnerDto.getHouseIds()));
        //同步客户档案
        PropertyCustomerArchives customerArchives = customerArchivesService.getCustomerArchivesById(houseOwnerDto.getCustomerArchivesId());
        customerArchives.setOrganType(houseOwnerDto.getOrganType());
        customerArchives.setOrganIndustry(houseOwnerDto.getOrganIndustry());
        customerArchives.setOrganScale(houseOwnerDto.getOrganScale());
        customerArchives.setSex(houseOwnerDto.getSex());
        customerArchives.setIdType(houseOwnerDto.getIdType());
        customerArchives.setIdNo(houseOwnerDto.getIdNo());
        customerArchives.setLinkManOne(houseOwnerDto.getLinkManOne());
        customerArchives.setLinkPhoneOne(houseOwnerDto.getLinkPhoneOne());
        customerArchivesService.updateById(customerArchives);
        return updateById(houseOwner);
        //1.注意编辑房源能不能改
        //2.还有这个客户档案已经被添加为房产业主了，就不能再被添加为房产业主吗
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteHouseOwner(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);
            //业主底下住户状态更新
            LambdaUpdateWrapper<PropertyUserHouse> userHouseUpdateWrapper = Wrappers.lambdaUpdate();
            userHouseUpdateWrapper.eq(PropertyUserHouse::getOwnerDetailId, userHouse.getUserDetailId());
            userHouseUpdateWrapper.set(PropertyUserHouse::getIsInvalid, 1);
            userHouseService.update(userHouseUpdateWrapper);
        }
        LambdaUpdateWrapper<PropertyHouseResident> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.eq(PropertyHouseResident::getOwnerId, id);
        updateWrapper.set(PropertyHouseResident::getRegisterStatus, RegisterStatusEnum.EXPIRED.getValue());
        houseResidentService.update(updateWrapper);
        return removeById(id);
    }

    @Override
    public PropertyHouseOwnerVo getHouseOwnerById(Long id) {
        PropertyHouseOwner houseOwner = getById(id);
        if (Func.isEmpty(houseOwner)) {
            throw new ServiceException("房产业主不存在");
        }
        PropertyCustomerArchives customerArchives = customerArchivesService.getCustomerArchivesById(houseOwner.getCustomerArchivesId());
        PropertyHouseOwnerVo houseOwnerVo = new PropertyHouseOwnerVo();
        BeanUtil.copyProperties(customerArchives, houseOwnerVo);
        BeanUtil.copyProperties(houseOwner, houseOwnerVo);
        PmgBatParkInfo pmgBatParkInfo = parkInfoService.getById(houseOwnerVo.getParkId());
        houseOwnerVo.setParkName(pmgBatParkInfo.getParkName());
        PropertyHouses houses = housesService.getById(houseOwnerVo.getHouseId());
        houseOwnerVo.setHouseName(houses.getHouseName());
        return houseOwnerVo;
    }

    @Override
    public NestPage<PropertyHouseOwnerListVo> getHouseOwnerPageList(PropertyHouseOwnerQueryDto queryDto) {
        if (Func.isNotEmpty(queryDto.getBuildingId()) && Func.isEmpty(queryDto.getHouseId())) {
            List<Long> houseIdList = housesService.listByBuildingId(queryDto.getBuildingId()).stream().map(PropertyHouses::getId).collect(Collectors.toList());
            queryDto.setHouseIdList(houseIdList);
        }
        // 分页获取数据
        Page<PropertyHouseOwnerListVo> page = new Page<>(queryDto.getCurrent(), queryDto.getSize());
        page = baseMapper.getHouseOwnerPageList(page, queryDto);
        List<PropertyHouseOwnerListVo> list = page.getRecords();
        Map<Long, String> parkMap = getParkMap();
        for (PropertyHouseOwnerListVo vo : list) {
            vo.setParkName(parkMap.get(vo.getParkId()));
            PropertyHousesVo propertyHousesVo = housesService.getPropertyHousesDetail(vo.getHouseId());
            vo.setHouseCode(propertyHousesVo.getResourceCode());
        }
        return PageConverterUtils.convert(page);
    }

    @Override
    public PropertyHouseOwnerImportResVo importHouseOwner(MultipartFile file) {
        if (!(file.getOriginalFilename().endsWith(".xlsx") || file.getOriginalFilename().endsWith(".xls"))) {
            throw new ServiceException("请选择正确的excel文件");
        }
        PropertyHouseOwnerImportResVo vo = new PropertyHouseOwnerImportResVo();
        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(),
                    PropertyHouseOwnerImportExcelVo.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);
                            PropertyHouseOwnerImportExcelVo importVo = (PropertyHouseOwnerImportExcelVo) 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(PropertyHouseOwnerImportExcelVo importVo, Map<String, PmgBatParkInfo> parkMap, Map<String, PropertyHouses> houseMap) {
        if (Func.isBlank(importVo.getParkName())) {
            throw new ServiceException("园区不能为空");
        }
        if (Func.isBlank(importVo.getHouseCode())) {
            throw new ServiceException("房间代码不能为空");
        }
        if (Func.isBlank(importVo.getOwnerTypeName())) {
            throw new ServiceException("业主类型不能为空");
        }
        if (Func.isBlank(importVo.getOwnerName())) {
            throw new ServiceException("业主名称不能为空");
        }
        if (Func.isBlank(importVo.getIdTypeName())) {
            throw new ServiceException("证件类型不能为空");
        }
        if (Func.isBlank(importVo.getIdNo())) {
            throw new ServiceException("证件号码不能为空");
        }
        if (Func.isBlank(importVo.getLinkPhone())) {
            throw new ServiceException("联系电话不能为空");
        }
        if (!Validator.isMobile(importVo.getLinkPhone())) {
            throw new ServiceException("联系电话格式错误");
        }
        PropertyHouseOwner houseOwner = new PropertyHouseOwner();
        BeanUtils.copyProperties(importVo, houseOwner);

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

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

        String ownerTypeName = importVo.getOwnerTypeName().replaceAll("\\s*", "");
        if (ownerTypeName.equals(OwnerTypeEnum.getDescByCode(OwnerTypeEnum.ORGAN.getValue()))) {
            houseOwner.setOwnerType(OwnerTypeEnum.ORGAN.getValue());
        } else if (ownerTypeName.equals(OwnerTypeEnum.getDescByCode(OwnerTypeEnum.PERSON.getValue()))) {
            houseOwner.setOwnerType(OwnerTypeEnum.PERSON.getValue());
        } else {
            throw new ServiceException("业主类型不存在");
        }

        String idTypeName = importVo.getIdTypeName().replaceAll("\\s*", "");
        Integer idType;
        if (idTypeName.equals(IdTypeEnum.getDescByCode(IdTypeEnum.ID_CARD.getValue()))) {
            idType = IdTypeEnum.ID_CARD.getValue();
        } else if (idTypeName.equals(IdTypeEnum.getDescByCode(IdTypeEnum.BUSINESS_LICENSE.getValue()))) {
            idType = IdTypeEnum.BUSINESS_LICENSE.getValue();
        } else {
            throw new ServiceException("证件类型不存在");
        }

        ContextUser contextUser = AuthUtil.getUser();
        if (Func.isEmpty(contextUser)) {
            throw new ServiceException("用户不存在");
        }

        LambdaQueryWrapper<PropertyCustomerArchives> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(PropertyCustomerArchives::getCustomerType, houseOwner.getOwnerType());
        queryWrapper.eq(PropertyCustomerArchives::getCustomerCategory, CustomerCategoryEnum.HOUSE_OWNER.getValue());
        if (houseOwner.getOwnerType() == OwnerTypeEnum.ORGAN.getValue()) {
            queryWrapper.eq(PropertyCustomerArchives::getIdType, IdTypeEnum.BUSINESS_LICENSE.getValue());
            queryWrapper.eq(PropertyCustomerArchives::getIdNo, importVo.getIdNo());
        }
        if (houseOwner.getOwnerType() == OwnerTypeEnum.PERSON.getValue()) {
            queryWrapper.eq(PropertyCustomerArchives::getLinkPhoneOne, importVo.getLinkPhone());
        }

        PropertyCustomerArchives customerArchives = customerArchivesService.getOne(queryWrapper);
        //存在
        if (Func.isNotEmpty(customerArchives)) {
            customerArchives.setCustomerCategory(CustomerCategoryEnum.HOUSE_OWNER.getValue());
            customerArchives.setCustomerName(importVo.getOwnerName());
            customerArchives.setIdType(idType);
            customerArchives.setIdNo(importVo.getIdNo());
            customerArchives.setLinkPhoneOne(importVo.getLinkPhone());
            customerArchives.setCreateType(CreateTypeEnum.AUTO_SYNC.getValue());
            customerArchives.setIsLink(YesOrNoEnum.YES.getValue());
            customerArchivesService.updateById(customerArchives);
            houseOwner.setCustomerArchivesId(customerArchives.getId());
        } else { //不存在，同步客户档案
            PropertyCustomerArchives add = new PropertyCustomerArchives();
            add.setParkId(houseOwner.getParkId());
            add.setCustomerType(houseOwner.getOwnerType());
            add.setCustomerCategory(CustomerCategoryEnum.HOUSE_OWNER.getValue());
            add.setCustomerName(importVo.getOwnerName());
            add.setIdType(idType);
            add.setIdNo(importVo.getIdNo());
            add.setLinkPhoneOne(importVo.getLinkPhone());
            add.setCreateType(CreateTypeEnum.AUTO_SYNC.getValue());
            add.setCreatePeopleId(contextUser.getUserDetailId());
            add.setIsLink(YesOrNoEnum.YES.getValue());
            customerArchivesService.save(add);
            houseOwner.setCustomerArchivesId(add.getId());
        }
        houseOwner.setCreatePeopleId(contextUser.getUserDetailId());

        //判断业主是否存在
        LambdaQueryWrapper<PropertyHouseOwner> isExitQuery = Wrappers.lambdaQuery();
        isExitQuery.eq(PropertyHouseOwner::getParkId, houseOwner.getParkId());
        isExitQuery.eq(PropertyHouseOwner::getHouseId, houseOwner.getHouseId());
        isExitQuery.eq(PropertyHouseOwner::getOwnerType, houseOwner.getOwnerType());
        isExitQuery.eq(PropertyHouseOwner::getCustomerArchivesId, houseOwner.getCustomerArchivesId());
        PropertyHouseOwner isExit = this.getOne(isExitQuery);
        if (Func.isNotEmpty(isExit)) {
            removeById(isExit.getId());
        }
        this.save(houseOwner);
    }


    @Override
    public void exportHouseOwner(PropertyHouseOwnerQueryDto 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<PropertyHouseOwnerListVo> list = baseMapper.getHouseOwnerList(queryDto);
        List<PropertyHouseOwnerExcelVo> excelVoList = BeanUtil.copyProperties(list, PropertyHouseOwnerExcelVo.class);
        Map<Long, String> parkMap = getParkMap();
        excelVoList.forEach(excelVo -> {
            excelVo.setParkName(parkMap.get(excelVo.getParkId()));
            PropertyHousesVo propertyHousesVo = housesService.getPropertyHousesDetail(excelVo.getHouseId());
            excelVo.setHouseCode(propertyHousesVo.getResourceCode());
            excelVo.setOwnerTypeName(OwnerTypeEnum.getDescByCode(excelVo.getOwnerType()));
            excelVo.setIdTypeName(IdTypeEnum.getDescByCode(excelVo.getIdType()));
        });
        try {
            String fileName = URLEncoder.encode("房产业主表", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), PropertyHouseOwnerExcelVo.class)
                    .sheet("房产业主表")
                    .doWrite(excelVoList); //最终处理好的数据结果集list
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    @Override
    public PropertyHouseOwner getByHouseId(Long houseId) {
        LambdaQueryWrapper<PropertyHouseOwner> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(PropertyHouseOwner::getHouseId,houseId)
                .orderByDesc(PropertyHouseOwner::getUpdateTime)
                .last("limit 1");
        return getOne(queryWrapper);
    }

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