package com.fs.qw.service.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.fs.common.exception.CustomException;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.StringUtils;
import com.fs.company.domain.CompanyDept;
import com.fs.company.domain.CompanyUser;
import com.fs.company.mapper.CompanyDeptMapper;
import com.fs.his.domain.FsImportMember;
import com.fs.his.mapper.FsImportMemberMapper;
import com.fs.his.service.IFsUserAddressService;
import com.fs.hisStore.mapper.FsStoreOrderScrmMapper;
import com.fs.hisStore.param.FsCompanyCustomerOrderParam;
import com.fs.hisStore.vo.FsStoreOrderItemVO;
import com.fs.hisStore.vo.FsStoreOrderVO;
import com.fs.qw.domain.FsCompanyCustomer;
import com.fs.qw.domain.FsCompanyCustomerLog;
import com.fs.qw.mapper.FsCompanyCustomerLogMapper;
import com.fs.qw.mapper.FsCompanyCustomerMapper;
import com.fs.qw.mapper.FsCompanyExternalPayReceiptMapper;
import com.fs.qw.param.TransferCustomerParam;
import com.fs.qw.service.IFsCompanyCustomerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * 客户基础信息Service业务层处理
 *
 * @author yourname
 * @date 2026-04-30
 */
@Slf4j
@Service
public class FsCompanyCustomerServiceImpl implements IFsCompanyCustomerService {
    @Autowired
    private FsCompanyCustomerMapper fsCompanyCustomerMapper;

    @Autowired
    private FsCompanyCustomerLogMapper companyCustomerLogMapper;

    @Autowired
    private FsImportMemberMapper importMemberMapper;

    @Autowired
    private CompanyDeptMapper companyDeptMapper;

    @Autowired
    private FsStoreOrderScrmMapper fsStoreOrderScrmMapper;

    @Autowired
    private FsCompanyExternalPayReceiptMapper externalPayReceiptMapper;

    @Autowired
    private IFsUserAddressService fsUserAddressService;

    @Override
    public FsCompanyCustomer selectFsCompanyCustomerById(Long id) {
        return fsCompanyCustomerMapper.selectFsCompanyCustomerById(id);
    }

    @Override
    public List<FsCompanyCustomer> selectFsCompanyCustomerList(FsCompanyCustomer fsCompanyCustomer) {
        return fsCompanyCustomerMapper.selectFsCompanyCustomerList(fsCompanyCustomer);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertFsCompanyCustomer(FsCompanyCustomer customer,CompanyUser companyUser) {
        try {
            CompanyDept companyDept = companyDeptMapper.selectCompanyDeptById(companyUser.getDeptId());
            customer.setClaimStatus(BigDecimal.ONE.intValue());
            customer.setDeptId(companyUser.getDeptId());
            if (companyDept!=null&&companyDept.getDeptName()!=null){
                customer.setDeptName(companyDept.getDeptName());
            }
            setCompleteStatus(customer);
            int result=fsCompanyCustomerMapper.insertFsCompanyCustomer(customer);
            //单独新增也需要增加认领日志
            FsCompanyCustomerLog claimLog = new FsCompanyCustomerLog();
            claimLog.setCompanyCustomerId(customer.getId());
            claimLog.setCompanyUserId(companyUser.getUserId());
            claimLog.setCompanyUserName(companyUser.getNickName());
            claimLog.setDeptId(companyUser.getDeptId());
            claimLog.setClaimTime(DateUtils.getNowDate());
            if (companyDept!=null&&companyDept.getDeptName()!=null){
                claimLog.setDeptName(companyDept.getDeptName());
            }
            //增加认领记录
            companyCustomerLogMapper.insertFsCompanyCustomerLog(claimLog);
            return result;
        } catch (Exception e) {
            // 判断是否为唯一键冲突（电话号码重复）
            if (isDuplicatePhoneException(e)) {
                throw new CustomException("电话号码已存在");
            }
            // 其他异常统一提示
            log.error("添加客户失败", e);
            throw new CustomException("添加失败，请联系管理员");
        }
    }

    /**
     * 根据异常判断是否为“电话号码重复”导致的唯一键冲突
     */
    private boolean isDuplicatePhoneException(Exception e) {
        Throwable cause = e;
        while (cause != null) {
            if (cause instanceof java.sql.SQLIntegrityConstraintViolationException) {
                String msg = cause.getMessage();
                // 根据实际约束名判断，约束名为 'fs_company_customer.uk_phone'
                if (msg != null && (msg.contains("Duplicate entry") && msg.contains("uk_phone"))) {
                    return true;
                }
            }
            cause = cause.getCause();
        }
        return false;
    }

    /**
     * 根据填写内容设置客户信息表的完善状态
     */
    private void setCompleteStatus(FsCompanyCustomer customer) {
        // 获取用户填写内容
        String allergyHistory = customer.getAllergyHistory();
        String presentIllness = customer.getPresentIllness();
        String currentMedication = customer.getCurrentMedication();
        Date appointmentTime = customer.getAppointmentTime();
        //只要有一个为空或空字符串，就设置completeStatus为0
        if (allergyHistory == null || allergyHistory.isEmpty()
                || presentIllness == null || presentIllness.isEmpty()
                || currentMedication == null || currentMedication.isEmpty()
                || appointmentTime == null
        ) {
            customer.setCompleteStatus(BigDecimal.ZERO.intValue());//完善状态,0:未完善
            return;
        }
        customer.setCompleteStatus(BigDecimal.ONE.intValue());//完善状态,1:完善
    }

    @Override
    public int updateFsCompanyCustomer(FsCompanyCustomer fsCompanyCustomer) {
        if (fsCompanyCustomer.getPhone()!=null&&fsCompanyCustomer.getPhone().contains("*")){
            //若提交的号码是脱敏的号码，则不需要更新号码
            fsCompanyCustomer.setPhone(null);
        }
        setCompleteStatus(fsCompanyCustomer);
        return fsCompanyCustomerMapper.updateFsCompanyCustomer(fsCompanyCustomer);
    }

    @Override
    public int deleteFsCompanyCustomerByIds(Long[] ids) {
        return fsCompanyCustomerMapper.deleteFsCompanyCustomerByIds(ids);
    }

    @Override
    public List<FsCompanyCustomer> selectFsCompanyCustomerListByCompanyUserIds(FsCompanyCustomer fsCompanyCustomer) {
        if (CollectionUtils.isEmpty(fsCompanyCustomer.getCompanyUserIds())){
            return Collections.emptyList();
        }
        List<FsCompanyCustomer> list =fsCompanyCustomerMapper.selectFsCompanyCustomerListByCompanyUserIds(fsCompanyCustomer);
        if (CollectionUtils.isEmpty(list)){
            return Collections.emptyList();
        }
        return list;
    }

    @Override
    public int transferCustomer(TransferCustomerParam param) {
        if (CollectionUtils.isEmpty(param.getCustomerIds())){
            throw new CustomException("客户信息不存在");
        }
        //修改客户的归属销售id
        return fsCompanyCustomerMapper.updateCompanyUserIdByIds(param);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int claimCustomer(FsCompanyCustomer fsCompanyCustomer, CompanyUser companyUser) {
        // 使用行锁查询客户信息（阻塞直到获得锁）
        FsCompanyCustomer oldCustomer = fsCompanyCustomerMapper.selectByIdForUpdate(fsCompanyCustomer.getId());
        //校验认领号码与客户号码是否一致
        if (!fsCompanyCustomer.getClaimPhone().equals(oldCustomer.getPhone())){
            log.error("认领号码:{},客户号码:{}",fsCompanyCustomer.getClaimPhone(),oldCustomer.getPhone());
            throw new CustomException("认领号码与客户号码不一致,请重试");
        }
        FsImportMember fsImportMember=new FsImportMember();
        fsImportMember.setId(oldCustomer.getImportMemberId());
        fsImportMember.setCompanyId(companyUser.getCompanyId());
        fsImportMember.setCompanyUserId(companyUser.getUserId());
        //更新关联的导入会员表信息
        importMemberMapper.updateFsImportMember(fsImportMember);

        FsCompanyCustomerLog claimLog = new FsCompanyCustomerLog();
        claimLog.setCompanyCustomerId(fsCompanyCustomer.getId());
        claimLog.setCompanyUserId(companyUser.getUserId());
        claimLog.setCompanyUserName(companyUser.getNickName());
        claimLog.setDeptId(companyUser.getDeptId());
        claimLog.setClaimTime(DateUtils.getNowDate());
        CompanyDept companyDept = companyDeptMapper.selectCompanyDeptById(companyUser.getDeptId());
        if (companyDept!=null&&companyDept.getDeptName()!=null){
            claimLog.setDeptName(companyDept.getDeptName());
            fsCompanyCustomer.setDeptName(companyDept.getDeptName());
        }
        //增加认领记录
        companyCustomerLogMapper.insertFsCompanyCustomerLog(claimLog);
        //认领的同时修改销售相关信息
        fsCompanyCustomer.setDeptId(companyUser.getDeptId());
        fsCompanyCustomer.setCompanyUserId(companyUser.getUserId());
        fsCompanyCustomer.setCompanyUserName(companyUser.getNickName());
        fsCompanyCustomer.setClaimStatus(BigDecimal.ONE.intValue());//已认领
        return fsCompanyCustomerMapper.updateFsCompanyCustomer(fsCompanyCustomer);
    }

    @Override
    public List<FsStoreOrderVO> selectStoreOrderScrmByCompanyCustomerParam(FsCompanyCustomerOrderParam param) {
        List<FsStoreOrderVO> fsStoreOrderVOS = fsStoreOrderScrmMapper.selectStoreOrderScrmByCompanyCustomerParam(param);
        if (CollectionUtils.isEmpty(fsStoreOrderVOS)){
            return Collections.emptyList();
        }
        for (FsStoreOrderVO vo : fsStoreOrderVOS) {
            String maskedNumber = vo.getUserPhone().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2");
            vo.setPhone(maskedNumber);
            vo.setUserPhone(maskedNumber);
            if (StringUtils.isNotEmpty(vo.getItemJson())) {
                JSONArray jsonArray = JSONUtil.parseArray(vo.getItemJson());
                List<FsStoreOrderItemVO> items = JSONUtil.toList(jsonArray, FsStoreOrderItemVO.class);
                if (!items.isEmpty()) {
                    vo.setItems(items);
                }
            }
        }
        return fsStoreOrderVOS;
    }

    @Override
    public String getKdnAddress(String address) {
        return fsUserAddressService.getKdnAddress(address);
    }

    @Override
    public int addBuyTimes(Long id) {
        FsCompanyCustomer fsCompanyCustomer = fsCompanyCustomerMapper.selectFsCompanyCustomerById(id);
        if (fsCompanyCustomer!=null&&fsCompanyCustomer.getBuyCount()!=null){
            fsCompanyCustomer.setBuyCount(fsCompanyCustomer.getBuyCount()+1);
            return fsCompanyCustomerMapper.updateFsCompanyCustomer(fsCompanyCustomer);
        }
        return 0;
    }
}