package com.dsk.system.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.common.annotation.DataScope;
import com.dsk.common.core.domain.R;
import com.dsk.common.exception.ServiceException;
import com.dsk.common.utils.SecurityUtils;
import com.dsk.common.utils.StringUtils;
import com.dsk.system.domain.customer.Customer;
import com.dsk.system.domain.customer.CustomerUser;
import com.dsk.system.domain.customer.dto.CustomerBusinessSearchDto;
import com.dsk.system.domain.customer.dto.CustomerSearchDto;
import com.dsk.system.domain.customer.vo.*;
import com.dsk.system.dskService.EnterpriseService;
import com.dsk.system.mapper.CustomerMapper;
import com.dsk.system.mapper.CustomerUserMapper;
import com.dsk.system.searchService.BusinessOpportunityRadarService;
import com.dsk.system.service.IBusinessInfoService;
import com.dsk.system.service.ICustomerService;
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.ArrayList;
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 EnterpriseService enterpriseService;
    @Autowired
    private BusinessOpportunityRadarService opportunityRadarService;

    @Override
//    @DataScope(deptAlias = "d", userAlias = "u")
    public List<CustomerListVo> selectList(CustomerSearchDto dto) {
        dto.setUserId(SecurityUtils.getUserId());
        dto.setStatus(ObjectUtils.isEmpty(dto.getStatus()) ? 0 : dto.getStatus());
        return baseMapper.selectList(dto);
    }

    @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) {
        dealWithcustomerData(customer);
        if (ObjectUtils.isEmpty(customer.getUipId())) {
            try {
                List<Integer> list=new ArrayList<>();
                list.add(customer.getCompanyId());
                R res = enterpriseService.getUipIdByCid(list);
                if (!ObjectUtils.isEmpty(res.getData())){
                    List<Map<String,Object>> data = (List<Map<String, Object>>) res.getData();
                    customer.setUipId(MapUtil.getStr(BeanUtil.beanToMap(data.get((0))), "uipId"));
                }
                if(ObjectUtils.isEmpty(customer.getUipId())){
                    res = enterpriseService.getUipId(customer.getCompanyName());
                    if (!ObjectUtils.isEmpty(res.getData())) {
                        customer.setUipId(MapUtil.getStr(BeanUtil.beanToMap(res.getData()), "uipId"));
                    }
                }
            } catch (Exception e) {
                log.error("获取城投平台企业id错误！error：{}", e.getMessage());
            }
        }
        Long userId = SecurityUtils.getUserId();
        customer.setCreateId(userId);
        customer.setUpdateId(userId);
        //查重
        Customer verifyCustomer = baseMapper.selectByCompanyNameAndUserId(customer.getCompanyName(), userId);
        if (!ObjectUtils.isEmpty(verifyCustomer)) {
            throw new ServiceException("当前客户信息已存在，请勿重复添加！");
        }

        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(SecurityUtils.getUserId());
        int u = baseMapper.updateById(customer);
        return u != 0;
    }

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

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

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

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


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

    @Override
    public Integer status(String companyName) {
        Customer cus = baseMapper.selectByCompanyNameAndUserId(companyName, SecurityUtils.getUserId());
        if (ObjectUtils.isEmpty(cus)) {
            return null;
        }
        CustomerUser customerUser = customerUserMapper.selectByCustomerIdAndUserId(cus.getCustomerId(), SecurityUtils.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, SecurityUtils.getUserId());
    }

    //修改客户认领状态
    private boolean updateClaimStatus(String companyName, Integer status) {
        Customer cus = baseMapper.selectByCompanyNameAndUserId(companyName, SecurityUtils.getUserId());
        if (ObjectUtils.isEmpty(cus)) {
            throw new ServiceException("数据错误！");
        }
        CustomerUser customerUser = customerUserMapper.selectByCustomerIdAndUserId(cus.getCustomerId(), SecurityUtils.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())) {
                    customer.setRegisterCapital(MapUtil.getStr(data, "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());
        }
    }

}
