package com.fs.his.service.impl;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.fs.common.utils.DateUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fs.his.dto.MemberExcelDTO;
import com.fs.his.listenner.MemberImportListener;
import com.fs.his.utils.KdzlJsonParser;
import com.fs.kdzl.dto.Custm;
import com.fs.kdzl.dto.Property;
import com.fs.kdzl.service.KdzlService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import com.fs.qw.mapper.FsCompanyCustomerMapper;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import com.fs.his.mapper.FsImportMemberMapper;
import com.fs.his.domain.FsImportMember;
import com.fs.qw.domain.FsCompanyCustomer;
import com.fs.his.service.IFsImportMemberService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

/**
 * 导入会员Service业务层处理
 * 
 * @author fs
 * @date 2026-05-25
 */
@Slf4j
@Service
public class FsImportMemberServiceImpl extends ServiceImpl<FsImportMemberMapper, FsImportMember> implements IFsImportMemberService {
    Logger logger= LoggerFactory.getLogger(getClass());
    @Autowired
    private FsCompanyCustomerMapper fsCompanyCustomerMapper;

    @Autowired
    private FsImportMemberMapper importMemberMapper;

    @Autowired
    private KdzlService kdzlService;

    /**
     * 查询导入会员
     * 
     * @param id 导入会员主键
     * @return 导入会员
     */
    @Override
    public FsImportMember selectFsImportMemberById(Long id)
    {
        return baseMapper.selectFsImportMemberById(id);
    }

    /**
     * 查询导入会员列表
     * 
     * @param fsImportMember 导入会员
     * @return 导入会员
     */
    @Override
    public List<FsImportMember> selectFsImportMemberList(FsImportMember fsImportMember)
    {
        return baseMapper.selectFsImportMemberList(fsImportMember);
    }

    /**
     * 新增导入会员
     * 
     * @param fsImportMember 导入会员
     * @return 结果
     */
    @Override
    public int insertFsImportMember(FsImportMember fsImportMember)
    {
        fsImportMember.setCreateTime(DateUtils.getNowDate());
        return baseMapper.insertFsImportMember(fsImportMember);
    }

    /**
     * 修改导入会员
     * 
     * @param fsImportMember 导入会员
     * @return 结果
     */
    @Override
    public int updateFsImportMember(FsImportMember fsImportMember)
    {
        fsImportMember.setUpdateTime(DateUtils.getNowDate());
        return baseMapper.updateFsImportMember(fsImportMember);
    }

    /**
     * 批量删除导入会员
     * 
     * @param ids 需要删除的导入会员主键
     * @return 结果
     */
    @Override
    public int deleteFsImportMemberByIds(Long[] ids)
    {
        return baseMapper.deleteFsImportMemberByIds(ids);
    }

    /**
     * 删除导入会员信息
     * 
     * @param id 导入会员主键
     * @return 结果
     */
    @Override
    public int deleteFsImportMemberById(Long id)
    {
        return baseMapper.deleteFsImportMemberById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchInsert(List<MemberExcelDTO> list) {
        List<FsImportMember> importMembers = list.stream().map(item -> {
            FsImportMember member = new FsImportMember();
            BeanUtils.copyProperties(item, member);
            member.setStatus(0);
            member.setCreateTime(DateUtils.getNowDate());
            member.setUpdateTime(DateUtils.getNowDate());
            return member;
        }).collect(Collectors.toList());
        baseMapper.batchInsertFsImportMember(importMembers);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> importExcel(MultipartFile file) {
        MemberImportListener listener = new MemberImportListener(this);
        try {
            EasyExcel.read(file.getInputStream(), MemberExcelDTO.class, listener)
                    .sheet()
                    .doRead();
        } catch (IOException e) {
            throw new RuntimeException("Excel读取失败", e);
        }
        return listener.getResult();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int batchAddCompanyCustomer() {
        // 1. 获取未加入到销售客户信息表的会员信息
        FsImportMember queryImportMember = new FsImportMember();
        queryImportMember.setStatus(0);
        List<FsImportMember> fsImportMembers = baseMapper.selectFsImportMemberList(queryImportMember);

        if (CollectionUtils.isEmpty(fsImportMembers)) {
            return 0;
        }
        Date nowDate = DateUtils.getNowDate();
        // 2. 将导入会员转换为销售客户对象，并初始化 claimStatus = 0（未认领）
        List<FsCompanyCustomer> importCustomers = fsImportMembers.stream().map(member -> {
            FsCompanyCustomer customer = new FsCompanyCustomer();
            customer.setCustomerName(member.getMemberName());
            customer.setPhone(member.getMemberPhone());
            customer.setAddress(member.getAddress());
            customer.setCreateTime(nowDate);
            customer.setImportMemberId(member.getId());
            customer.setPresentIllness(member.getPresentIllness());
            customer.setCurrentMedication(member.getCurrentMedication());
            customer.setAllergyHistory(member.getAllergyHistory());
            customer.setClaimStatus(0);  //未认领状态
            // 解析口袋助理JSON
            if (StringUtils.isNotBlank(member.getKdzlMemberJson())) {
                KdzlJsonParser.fillCustomerFromKdzlJson(customer, member.getKdzlMemberJson());
            }
            return customer;
        }).collect(Collectors.toList());

        // 3. 查询已存在的 import_member_id
        FsCompanyCustomer queryCondition = new FsCompanyCustomer();
        List<FsCompanyCustomer> originCustomerList = fsCompanyCustomerMapper.selectImportFsCompanyCustomerList(queryCondition);
        Set<Long> existedImportIds = originCustomerList.stream()
                .map(FsCompanyCustomer::getImportMemberId)
                .collect(Collectors.toSet());

        // 待更新：import_member_id 已存在
        List<FsCompanyCustomer> existCustomerList = importCustomers.stream()
                .filter(item -> existedImportIds.contains(item.getImportMemberId()))
                .collect(Collectors.toList());

        // 待新增：import_member_id 不存在
        List<FsCompanyCustomer> willAddCustomers = importCustomers.stream()
                .filter(item -> !existedImportIds.contains(item.getImportMemberId()))
                .collect(Collectors.toList());

        // 执行更新
        int batchUpdateSize = 500;
        int totalUpdateCount = 0; // 记录总共成功更新了多少条
        for (int i = 0; i < existCustomerList.size(); i += batchUpdateSize) {
            int end = Math.min(i + batchUpdateSize, existCustomerList.size());
            List<FsCompanyCustomer> subList = existCustomerList.subList(i, end);
            // updateBatchFsCompanyCustomer 批量更新返回该批次实际影响的行数(已存在的客户表信息数据不需要更新认领状态)
            int updatedInBatch = fsCompanyCustomerMapper.updateBatchFsCompanyCustomer(subList);
            totalUpdateCount += updatedInBatch;
        }
        log.info("定时同步会员信息表,批量更新了{}条数据", totalUpdateCount);
        // 执行新增
        int batchSize = 500;
        int totalAddCount = 0; // 记录总共成功新增了多少条

        for (int i = 0; i < willAddCustomers.size(); i += batchSize) {
            int end = Math.min(i + batchSize, willAddCustomers.size());
            List<FsCompanyCustomer> subList = willAddCustomers.subList(i, end);
            // insertBatchFsCompanyCustomer 返回该批次实际影响的行数
            int insertedInBatch = fsCompanyCustomerMapper.insertBatchFsCompanyCustomer(subList);
            totalAddCount += insertedInBatch;
        }
        log.info("定时同步会员信息表,批量新增了{}条数据", totalAddCount);
        // 4. 合并需要更新状态的ID
        List<Long> allProcessedIds = fsImportMembers.stream()
                .map(FsImportMember::getId)
                .collect(Collectors.toList());
        // 6. 批量修改导入会员状态
        return baseMapper.batchUpdateCompletionStatus(allProcessedIds);
    }

    /**
     * 解析每行json内容 获取客户加微状态、成交状态、通话状态
     * */

    @Override
    @Async
    public void syncKdzlMemberInfo() {
        logger.info("开始同步会员信息...");
        int totalCount = 0;

        while (true) {
            List<Custm> custms = kdzlService.exportCustomers();
            logger.info("本次获取会员信息数量：{}", custms.size());

            if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isEmpty(custms)) {
                logger.info("未获取到会员数据，同步结束");
                break;
            }

            totalCount += custms.size();
            logger.info("累计已同步会员数量：{}", totalCount);

            for (Custm custm : custms) {
                try {
                    FsImportMember member = importMemberMapper.selectFsImportMemberByMemberId(custm.getCustmid());
                    if (member == null) {
                        member = new FsImportMember();
                        member.setKdzlMemberId(custm.getCustmid());
                        member.setKdzlMemberJson(JSON.toJSONString(custm));
                        member.setMemberName(custm.getName());
                        member.setCreateTime(new Date());

                        if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(custm.getContacts())) {
                            com.fs.kdzl.dto.Contact contact = custm.getContacts().get(0);
                            if (contact != null && com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(contact.getMobiles())) {
                                member.setMemberPhone(contact.getMobiles().get(0));
                            }
                        }

                        member.setAddress(custm.getAddr());

                        if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(custm.getProperties())) {
                            for (Property property : custm.getProperties()) {
                                switch (property.getProp_name()) {
                                    case "现病史":
                                        member.setPresentIllness(property.getProp_value());
                                        break;
                                    case "现用药情况":
                                        member.setCurrentMedication(property.getProp_value());
                                        break;
                                    case "过敏史":
                                        member.setAllergyHistory(property.getProp_value());
                                        break;
                                }
                            }
                        }
                    } else {
                        member.setKdzlMemberJson(JSON.toJSONString(custm));
                        member.setUpdateTime(new Date());
                        member.setStatus(0);

                        if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(custm.getProperties())) {
                            for (Property property : custm.getProperties()) {
                                switch (property.getProp_name()) {
                                    case "现病史":
                                        member.setPresentIllness(property.getProp_value());
                                        break;
                                    case "现用药情况":
                                        member.setCurrentMedication(property.getProp_value());
                                        break;
                                    case "过敏史":
                                        member.setAllergyHistory(property.getProp_value());
                                        break;
                                }
                            }
                        }
                    }

                    if (member.getId() == null) {
                        importMemberMapper.insertFsImportMember(member);
                    } else {
                        importMemberMapper.updateFsImportMember(member);
                    }
                } catch (Exception e) {
                    log.error("同步会员信息失败，custmid: {}, 错误: {}", custm.getCustmid(), e.getMessage());
                }
            }

            if (custms.size() < 2000) {
                logger.info("本次获取数据量小于2000，所有会员数据已同步完毕");
                break;
            }

            logger.info("本次获取数据量等于2000，继续获取下一页数据...");
        }

        logger.info("会员信息同步完成，总共同步数量：{}", totalCount);
    }
}
