package com.yd.csf.service.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yd.common.enums.CommonEnum;
import com.yd.common.exception.BusinessException;
import com.yd.common.utils.RandomStringGenerator;
import com.yd.csf.service.common.ErrorCode;
import com.yd.csf.service.dao.CustomerMapper;
import com.yd.csf.service.dto.CustomerAddRequest;
import com.yd.csf.service.dto.CustomerQueryRequest;
import com.yd.csf.service.dto.CustomerUpdateRequest;
import com.yd.csf.service.model.Customer;
import com.yd.csf.service.model.CustomerExpand;
import com.yd.csf.service.service.CustomerExpandService;
import com.yd.csf.service.service.CustomerService;
import com.yd.csf.service.service.FnaService;
import com.yd.csf.service.utils.ValidateUtil;
import com.yd.csf.service.vo.AddressVO;
import com.yd.csf.service.vo.CustomerVO;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
* @author Zhang Jianan
* @description 针对表【customer(客户信息表)】的数据库操作Service实现
* @createDate 2025-08-29 17:38:23
*/
@Service
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer>
    implements CustomerService{

    private final static Gson GSON = new Gson();

    @Resource
    private CustomerExpandService customerExpandService;

    @Resource
    private CustomerService customerService;

    @Resource
    private FnaService fnaService;



    @Override
    public CustomerVO getCustomerVO(Customer customer) {
        CustomerVO customerVO = CustomerVO.objToVo(customer);

        // 1. 关联查询扩展信息
        CustomerExpand customerExpand = customerExpandService.getByCustomerBizId(customer.getCustomerBizId());
        if (customerExpand != null) {
            BeanUtils.copyProperties(customerExpand, customerVO);

            if (ObjectUtils.isNotEmpty(customerExpand.getAddressList())) {
                List<AddressVO> addressList = GSON.fromJson((String) customerExpand.getAddressList(), new TypeToken<List<AddressVO>>() {
                }.getType());
                customerVO.setAddressList(addressList);
            }
        }
        return customerVO;
    }

    @Override
    public Wrapper<Customer> getQueryWrapper(CustomerQueryRequest customerQueryRequest) {
        QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
        String name = customerQueryRequest.getName();
        String phone = customerQueryRequest.getPhone();
        String email = customerQueryRequest.getEmail();

        queryWrapper.like(StringUtils.isNotBlank(name), "name", name)
                .or().like(StringUtils.isNotBlank(name), "first_name_pinyin", name);

        queryWrapper.like(StringUtils.isNotBlank(phone), "phone", phone);
        queryWrapper.like(StringUtils.isNotBlank(email), "email", email);

        return queryWrapper;
    }

    @Override
    public CustomerExpand getCustomerExpand(CustomerAddRequest customerAddRequest) {
        CustomerExpand customerExpand = new CustomerExpand();
        BeanUtils.copyProperties(customerAddRequest, customerExpand, "addressList");
        List<AddressVO> addressList = customerAddRequest.getAddressList();
        if (CollUtil.isNotEmpty(addressList)) {
            customerExpand.setAddressList(GSON.toJson(addressList));
        }

        return customerExpand;
    }

    @Override
    public Page<CustomerVO> getCustomerVOPage(Page<Customer> customerPage) {
        List<Customer> customerList = customerPage.getRecords();
        Page<CustomerVO> customerVOPage = new Page<>(customerPage.getCurrent(), customerPage.getSize(), customerPage.getTotal());
        if (CollUtil.isEmpty(customerList)) {
            return customerVOPage;
        }
        // 对象列表 => 封装对象列表
        List<CustomerVO> customerVOList = customerList.stream().map(CustomerVO::objToVo).collect(Collectors.toList());

        // 1. 关联查询扩展信息
        Set<String> customerBizIdSet = customerList.stream().map(Customer::getCustomerBizId).collect(Collectors.toSet());

        QueryWrapper<CustomerExpand> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("customer_biz_id", customerBizIdSet);
        List<CustomerExpand> customerExpandList = customerExpandService.list(queryWrapper);
        Map<String, CustomerExpand> customerBizIdCustomerExpandListMap = customerExpandList.stream()
                .collect(Collectors.toMap(CustomerExpand::getCustomerBizId, customerExpand -> customerExpand));

        // 填充信息
        for (CustomerVO customerVO : customerVOList) {
            String customerBizId = customerVO.getCustomerBizId();
            CustomerExpand customerExpand = null;
            if (customerBizIdCustomerExpandListMap.containsKey(customerBizId)) {
                customerExpand = customerBizIdCustomerExpandListMap.get(customerBizId);
            }
            if (customerExpand != null) {
                BeanUtils.copyProperties(customerExpand, customerVO);

                if (ObjectUtils.isNotEmpty(customerExpand.getAddressList())) {
                    List<AddressVO> addressList = GSON.fromJson((String) customerExpand.getAddressList(), new TypeToken<List<AddressVO>>() {
                    }.getType());
                    customerVO.setAddressList(addressList);
                }
            }
        }

        customerVOPage.setRecords(customerVOList);
        return customerVOPage;
    }

    @Override
    public Customer getByCustomerBizId(String customerBizId) {
        return baseMapper.selectOne(new LambdaQueryWrapper<Customer>().eq(Customer::getCustomerBizId, customerBizId));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> addCustomer(CustomerAddRequest customerAddRequest) {
        // 校验 请求 对象中，参数是否全部为空
        if (ValidateUtil.isAllFieldsNull(customerAddRequest)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR.getCode(), ErrorCode.PARAMS_ERROR.getMessage());
        }
        // 客户主表信息
        Customer customer = new Customer();
        BeanUtils.copyProperties(customerAddRequest, customer);
        // 校验客户主表信息
        validCustomer(customer);

        // 客户扩展表信息
        CustomerExpand customerExpand = customerService.getCustomerExpand(customerAddRequest);

        // 获取 userBizId
//        SecurityUtil.getLoginUser();
//        customer.setUserBizId("");

        // 客户主表业务唯一id
        customer.setCustomerBizId(RandomStringGenerator.generateBizId16(CommonEnum.UID_TYPE_CUSTOMER.getCode()));
        boolean result = customerService.save(customer);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR.getCode(), ErrorCode.OPERATION_ERROR.getMessage());
        }

        // 客户扩展表信息，非空时，写入数据库
        if (!ValidateUtil.isAllFieldsNull(customerAddRequest)) {
            // 主表业务唯一id
            customerExpand.setCustomerBizId(customer.getCustomerBizId());
            // 客户扩展表业务唯一id
            customerExpand.setCustomerExpandBizId(RandomStringGenerator.generateBizId16("customer_expand"));
            // 写入数据库
            boolean resultExpand = customerExpandService.save(customerExpand);
            if (!resultExpand) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR.getCode(), ErrorCode.OPERATION_ERROR.getMessage());
            }
            // 更新客户主表
            Customer updateCustomer = new Customer();
            updateCustomer.setId(customer.getId());
            updateCustomer.setCustomerExpandBizId(customerExpand.getCustomerBizId());
            customerService.updateById(updateCustomer);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("customerBizId", customer.getCustomerBizId());
        return map;
    }

    @Override
    public void validCustomer(Customer customer) {
        String firstNamePinyin = customer.getFirstNamePinyin();
        if (StringUtils.isBlank(firstNamePinyin)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR.getCode(), "名字-英文不能为空");
        }
        String phone = customer.getPhone();
        if (StringUtils.isBlank(phone)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR.getCode(), "客户手机号不能为空");
        }
        String title = customer.getTitle();
        if (StringUtils.isBlank(title)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR.getCode(), "称谓不能为空");
        }
        String age = customer.getAge();
        if (StringUtils.isBlank(age)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR.getCode(), "年龄不能为空");
        }
        Object marriage = customer.getMarriage();
        if (marriage == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR.getCode(), "婚姻状况不能为空");
        }
        String country = customer.getCountry();
        if (StringUtils.isBlank(country)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR.getCode(), "国籍不能为空");
        }
        Object education = customer.getEducation();
        if (education == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR.getCode(), "教育程度不能为空");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateCustomer(CustomerUpdateRequest customerUpdateRequest) {

        // 判断是否存在
        String customerBizId = customerUpdateRequest.getCustomerBizId();
        Customer oldCustomer = customerService.getByCustomerBizId(customerBizId);
        if (oldCustomer == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR.getCode(), ErrorCode.NOT_FOUND_ERROR.getMessage());
        }

        BeanUtils.copyProperties(customerUpdateRequest, oldCustomer, "customerBizId");
        // 数据校验
        customerService.validCustomer(oldCustomer);
        // 更新主表
        boolean result = customerService.updateById(oldCustomer);
        if (StringUtils.isNotBlank(customerUpdateRequest.getFirstNamePinyin())) {
            fnaService.updateCustomerNameByCustomerBizId(customerUpdateRequest.getFirstNamePinyin(), customerBizId);
        }

        // 获取扩展表信息
        CustomerExpand customerExpand = customerExpandService.getByCustomerBizId(customerBizId);
        String addressListJSON = null;
        if (!CollectionUtils.isEmpty(customerUpdateRequest.getAddressList())) {
            addressListJSON = GSON.toJson(customerUpdateRequest.getAddressList());
        }
        if (customerExpand != null) {
            // 更新扩展表
            BeanUtils.copyProperties(customerUpdateRequest, customerExpand, "customerBizId, customerExpandBizId");
            customerExpand.setAddressList(addressListJSON);
            customerExpandService.updateById(customerExpand);
        } else {
            // 扩展表不存在，创建扩展表
            CustomerExpand newCustomerExpand = new CustomerExpand();
            BeanUtils.copyProperties(customerUpdateRequest, newCustomerExpand, "customerBizId");
            newCustomerExpand.setAddressList(addressListJSON);
            newCustomerExpand.setCustomerExpandBizId(RandomStringGenerator.generateBizId16("customer_expand"));
            newCustomerExpand.setCustomerBizId(customerBizId);
            customerExpandService.save(newCustomerExpand);
        }

        return true;
    }

}




