package com.dsk.biz.service.impl;

import cn.hutool.core.bean.BeanException;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dsk.biz.domain.Customer;
import com.dsk.biz.domain.CustomerUser;
import com.dsk.biz.domain.bo.CustomerBusinessSearchDto;
import com.dsk.biz.domain.bo.CustomerSearchDto;
import com.dsk.biz.domain.vo.CustomerBusinessListVo;
import com.dsk.biz.domain.vo.CustomerListVo;
import com.dsk.biz.domain.vo.CustomerStatusListVo;
import com.dsk.biz.domain.vo.CustomerVo;
import com.dsk.jsk.service.EnterpriseCommonService;
import com.dsk.biz.mapper.CustomerMapper;
import com.dsk.biz.mapper.CustomerUserMapper;
import com.dsk.biz.service.IBusinessInfoService;
import com.dsk.biz.service.ICustomerService;
import com.dsk.common.core.domain.PageQuery;
import com.dsk.common.core.page.TableDataInfo;
import com.dsk.common.exception.ServiceException;
import com.dsk.common.helper.LoginHelper;
import com.dsk.common.utils.StringUtils;
import com.dsk.search.service.BusinessOpportunityRadarService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 客户信息表(Customer)表服务实现类
 *
 * @author makejava
 * @since 2023-05-16 09:27:57
 */
@Slf4j
@Service
public class CustomerServiceImpl implements ICustomerService {

    @Resource
    private CustomerMapper baseMapper;
    @Resource
    private CustomerUserMapper customerUserMapper;
    @Autowired
    private IBusinessInfoService businessInfoService;
    @Autowired
    private EnterpriseCommonService enterpriseCommonService;
    @Autowired
    private BusinessOpportunityRadarService opportunityRadarService;

    @Override
//    @DataScope(deptAlias = "d", userAlias = "u")
    public TableDataInfo<CustomerListVo> selectList(CustomerSearchDto dto, PageQuery pageQuery) {
        dto.setUserId(LoginHelper.getUserId());
        dto.setStatus(ObjectUtils.isEmpty(dto.getStatus()) ? 0 : dto.getStatus());
        final TableDataInfo<CustomerListVo> result = TableDataInfo.build(baseMapper.selectList(pageQuery.build(), dto));
        if (!ObjectUtils.isEmpty(result.getRows()) && !ObjectUtils.isEmpty(dto.getCompanyName())) {
            for (CustomerListVo vo : result.getRows()) {
                vo.setCompanyName(StringUtils.markInRed(vo.getCompanyName(), dto.getCompanyName()));
            }
        }
        return result;
    }

    @Override
    public CustomerVo info(String customerId) {
        CustomerVo vo = new CustomerVo();
        BeanUtil.copyProperties(baseMapper.selectById(customerId), vo);
        CustomerUser customerUser = customerUserMapper.selectOne(Wrappers.<CustomerUser>lambdaQuery()
                .eq(CustomerUser::getCustomerId, customerId));
        vo.setUserId(customerUser.getUserId());
        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean add(Customer customer) {
        Long userId = LoginHelper.getUserId();
        //查重
        Customer verifyCustomer = baseMapper.selectByCompanyNameAndUserId(customer.getCompanyName(), userId);
        if (!ObjectUtils.isEmpty(verifyCustomer)) {
            throw new ServiceException("当前客户信息已存在，请勿重复添加！");
        }
        dealWithcustomerData(customer);
        customer.setUipId(enterpriseCommonService.getUipIdByCompanyNameOrCompanyId(customer.getCompanyName(), customer.getCompanyId()));

        customer.setCreateId(userId);
        customer.setUpdateId(userId);
        customer.setTenantId(LoginHelper.getTenantId());

        int i = baseMapper.insert(customer);
        if (i == 0) throw new ServiceException("客户信息添加错误！");

        int ui = customerUserMapper.insert(new CustomerUser(customer.getCustomerId(), userId));
        if (ui == 0) throw new ServiceException("客户跟进人信息添加错误！");

        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean edit(Customer customer) {
        if (ObjectUtils.isEmpty(customer.getCustomerId())) throw new BeanException("客户id不能为空");
        customer.setUpdateId(LoginHelper.getUserId());
        int u = baseMapper.updateById(customer);
        return u != 0;
    }

    @Override
    public List<Customer> selectUserList() {
        return baseMapper.selectUserList(LoginHelper.getUserId());
    }

    @Override
    public TableDataInfo<CustomerBusinessListVo> selectBusinessList(CustomerBusinessSearchDto dto, PageQuery pageQuery) {
        if (ObjectUtils.isEmpty(dto.getCustomerId())) throw new BeanException("客户id不能为空");
        dto.setUserId(LoginHelper.getUserId());
        return businessInfoService.selectCustomerBusinessList(dto, pageQuery);
    }

    @Override
    public List<CustomerStatusListVo> selectStatusList(List<String> uipIds) {
        return baseMapper.selectStatusList(uipIds, LoginHelper.getUserId());
    }

    @Override
    public List<CustomerStatusListVo> selectStatusListByCompanyName(List<String> companyNames) {
        return baseMapper.selectStatusListByCompanyName(companyNames, LoginHelper.getUserId());
    }


//    @Override
//    public List<String> selectUipIdList(List<String> uipIds) {
//        return baseMapper.selectUipIdList(uipIds, LoginHelper.getUserId());
//    }

    @Override
    public Integer status(String companyName) {
        Customer cus = baseMapper.selectByCompanyNameAndUserId(companyName, LoginHelper.getUserId());
        if (ObjectUtils.isEmpty(cus)) {
            return null;
        }
        CustomerUser customerUser = customerUserMapper.selectByCustomerIdAndUserId(cus.getCustomerId(), LoginHelper.getUserId());
        if (ObjectUtils.isEmpty(customerUser)) {
            throw new ServiceException("数据错误！");
        }
        return customerUser.getStatus();
    }

    @Override
    public boolean cancelClaim(String companyName) {
        return updateClaimStatus(companyName, 1);
    }

    @Override
    public boolean historyClaim(String companyName) {
        return updateClaimStatus(companyName, 0);
    }

    @Override
    public Customer selectByCompanyNameAndUserId(String companyName) {
        return baseMapper.selectByCompanyNameAndUserId(companyName, LoginHelper.getUserId());
    }

    //修改客户认领状态
    private boolean updateClaimStatus(String companyName, Integer status) {
        Customer cus = baseMapper.selectByCompanyNameAndUserId(companyName, LoginHelper.getUserId());
        if (ObjectUtils.isEmpty(cus)) {
            throw new ServiceException("数据错误！");
        }
        CustomerUser customerUser = customerUserMapper.selectByCustomerIdAndUserId(cus.getCustomerId(), LoginHelper.getUserId());
        if (ObjectUtils.isEmpty(customerUser)) {
            throw new ServiceException("数据错误！");
        }
        customerUser.setStatus(status);
        return customerUserMapper.updateById(customerUser) == 1;
    }

    private void dealWithcustomerData(Customer customer) {
        if (ObjectUtils.isEmpty(customer.getCompanyName())) throw new BeanException("企业名称不能为空");
        try {
            Map<String, Object> map = opportunityRadarService.enterpriseByName(customer.getCompanyName());
            if (!ObjectUtils.isEmpty(map.get("data"))) {
                Map<String, Object> data = BeanUtil.beanToMap(map.get("data"));
                Integer companyId = MapUtil.getInt(data, "jskEid");
                if (ObjectUtil.isNotEmpty(customer.getCompanyId()) && !customer.getCompanyId().equals(companyId)) {
                    return;
                }
                customer.setCompanyId(companyId);
                if (ObjectUtils.isEmpty(customer.getLegalPerson())) {
                    customer.setLegalPerson(MapUtil.getStr(data, "legalPerson"));
                }
                if (ObjectUtils.isEmpty(customer.getRegisterCapital())) {
                    String registeredCapitalStr = MapUtil.getStr(data, "registeredCapitalStr");
                    if (!ObjectUtils.isEmpty(registeredCapitalStr)) {
                        int length = registeredCapitalStr.indexOf(".0");
                        if (length == registeredCapitalStr.length() - 2) {
                            registeredCapitalStr = registeredCapitalStr.replace(".0", "");
                        }
                    }
                    customer.setRegisterCapital(registeredCapitalStr);
                }
                if (ObjectUtils.isEmpty(customer.getProvinceId())) {
                    customer.setProvinceId(MapUtil.getInt(data, "provinceId"));
                }
                if (ObjectUtils.isEmpty(customer.getCityId())) {
                    customer.setCityId(MapUtil.getInt(data, "cityId"));
                }
                if (ObjectUtils.isEmpty(customer.getDistrictId())) {
                    customer.setDistrictId(MapUtil.getInt(data, "countyId"));
                }
                if (ObjectUtils.isEmpty(customer.getRegisterAddress())) {
                    if (ObjectUtil.isNotEmpty(MapUtil.getStr(data, "domicile"))) {
                        customer.setRegisterAddress(MapUtil.getStr(data, "domicile"));
                    } else {
                        String address = null;
                        if (!ObjectUtils.isEmpty(MapUtil.getStr(data, "province"))) {
                            address = MapUtil.getStr(data, "province");
                            if (!ObjectUtils.isEmpty(MapUtil.getStr(data, "city"))) {
                                address = address.concat("-").concat(MapUtil.getStr(data, "city"));
                                if (!ObjectUtils.isEmpty(MapUtil.getStr(data, "county"))) {
                                    address = address.concat("-").concat(MapUtil.getStr(data, "county"));
                                }
                            }
                        }
                        customer.setRegisterAddress(address);
                    }
                }
                if (ObjectUtils.isEmpty(customer.getCreditCode())) {
                    customer.setCreditCode(MapUtil.getStr(data, "creditCode"));
                }
            }
        } catch (Exception e) {
            log.debug("获取企业id错误！error：{}", e.getMessage());
        }
    }

}
