package com.fs.qw.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

import cn.hutool.core.lang.Pair;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.fs.common.utils.DictUtils;
import com.fs.company.cache.ICompanyCacheService;
import com.fs.company.cache.ICompanyUserCacheService;
import com.fs.company.domain.Company;
import com.fs.company.domain.CompanyUser;
import com.fs.qw.domain.CustomerTransferApproval;
import com.fs.qw.mapper.CustomerTransferApprovalMapper;
import com.fs.qw.service.ICustomerTransferApprovalService;
import com.fs.qw.vo.TransferCustomDTO;
import com.fs.store.domain.FsUser;
import com.fs.store.dto.FsUserTransferParamDTO;
import com.fs.store.service.IFsUserService;
import com.fs.store.service.cache.IFsUserCacheService;
import com.hc.openapi.tool.util.StringUtils;
import org.apache.http.util.Asserts;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * 客户转移审批Service业务层处理
 *
 * @author fs
 * @date 2025-04-01
 */
@Service
@EnableAspectJAutoProxy(proxyTargetClass = true,exposeProxy = true)
public class CustomerTransferApprovalServiceImpl implements ICustomerTransferApprovalService
{
    @Autowired
    private CustomerTransferApprovalMapper customerTransferApprovalMapper;

    @Autowired
    private ICompanyUserCacheService companyUserCacheService;

    @Autowired
    private ICompanyCacheService companyCacheService;

    @Autowired
    private IFsUserCacheService fsUserCacheService;

    @Autowired
    private IFsUserService fsUserService;

    /**
     * 查询客户转移审批
     *
     * @param id 客户转移审批ID
     * @return 客户转移审批
     */
    @Override
    public CustomerTransferApproval selectCustomerTransferApprovalById(Long id)
    {
        CustomerTransferApproval item = customerTransferApprovalMapper.selectCustomerTransferApprovalById(id);

        if(ObjectUtils.isNotNull(item.getCorpId())){
            Company company = companyCacheService.selectCompanyById(Long.valueOf(item.getCorpId()));
            if(ObjectUtils.isNotNull(company)){
                item.setCompanyName(String.format("%s_%s",company.getCompanyName(),company.getCompanyId()));
            }
        }
        if(ObjectUtils.isNotNull(item.getTransferType())){
            String transferType = DictUtils.getDictLabel("transfer_type", String.valueOf(item.getTransferType()));
            if(ObjectUtils.isNotEmpty(transferType)){
                item.setTransferTypeText(transferType);
            }
        }
        if(ObjectUtils.isNotNull(item.getApprovalStatus())){
            String approvalStatus = DictUtils.getDictLabel("transfer_approval_status", String.valueOf(item.getApprovalStatus()));
            if(ObjectUtils.isNotEmpty(approvalStatus)){
                item.setApprovalStatusText(approvalStatus);
            }
        }

        if(ObjectUtils.isNotNull(item.getOriginalUserId())){
            CompanyUser companyUser = companyUserCacheService.selectCompanyUserById(item.getOriginalUserId());
            if(ObjectUtils.isNotNull(companyUser)){
                item.setOriginalUserName(String.format("%s_%d",companyUser.getUserName(),companyUser.getUserId()));
            }
        }

        // 目标接收销售用户
        if(ObjectUtils.isNotNull(item.getTargetUserId())){
            CompanyUser companyUser = companyUserCacheService.selectCompanyUserById(item.getTargetUserId());
            if(ObjectUtils.isNotNull(companyUser)){
                item.setTargetUserName(String.format("%s_%d", companyUser.getUserName(), companyUser.getUserId()));
            }
        }

        // 发起此转移请求的用户
        if(ObjectUtils.isNotNull(item.getInitiatorUserId())){
            CompanyUser companyUser = companyUserCacheService.selectCompanyUserById(item.getInitiatorUserId());
            if(ObjectUtils.isNotNull(companyUser)){
                item.setInitiatorUserName(String.format("%s_%d", companyUser.getUserName(), companyUser.getUserId()));
            }
        }

        if(StringUtils.isBlank(item.getTransferBefore()) && StringUtils.isNotBlank(item.getCustomerIds())){
            List<Long> customerIds = JSON.parseArray(item.getCustomerIds(), Long.class);
            List<TransferCustomDTO> customerList = getCustomerList(customerIds, item);
            item.setCustomerList(customerList);
        } else {
            List<TransferCustomDTO> customerList = JSON.parseArray(item.getTransferBefore(), TransferCustomDTO.class);
            item.setCustomerList(customerList);
        }
        return item;
    }

    private List<TransferCustomDTO> getCustomerList(List<Long> customerIds, CustomerTransferApproval item) {
        List<TransferCustomDTO> customerList = new ArrayList<>();

        for (Long customerId : customerIds) {

            FsUser fsUser = fsUserCacheService.selectFsUserById(customerId);
            if(ObjectUtils.isNotNull(fsUser)){
                String companyUserName = "无";
                if(ObjectUtils.isNotNull(fsUser.getCompanyUserId())){
                    CompanyUser companyUser = companyUserCacheService.selectCompanyUserById(fsUser.getCompanyUserId());
                    companyUserName = String.format("%s_%d", companyUser.getUserName(), companyUser.getUserId());
                }

                customerList.add(TransferCustomDTO.builder()
                        .userName(String.format("%s_%d", fsUser.getNickname(), fsUser.getUserId()))
                        .userId(fsUser.getUserId())
                        .beforeCompanyUserName(companyUserName)
                        .beforeCompanyUserId(fsUser.getCompanyUserId())
                        .afterCompanyUserName(item.getTargetUserName())
                        .afterCompanyUserId(item.getTargetUserId())
                        .build());
            }
        }
        return customerList;
    }

    /**
     * 查询客户转移审批列表
     *
     * @param customerTransferApproval 客户转移审批
     * @return 客户转移审批
     */
    @Override
    public List<CustomerTransferApproval> selectCustomerTransferApprovalList(CustomerTransferApproval customerTransferApproval)
    {
        List<CustomerTransferApproval> list = customerTransferApprovalMapper.selectCustomerTransferApprovalList(customerTransferApproval);
        for (CustomerTransferApproval item : list) {
            if(ObjectUtils.isNotNull(item.getCorpId())){
                Company company = companyCacheService.selectCompanyById(Long.valueOf(item.getCorpId()));
                if(ObjectUtils.isNotNull(company)){
                    item.setCompanyName(String.format("%s_%s",company.getCompanyName(),company.getCompanyId()));
                }
            }
            if(ObjectUtils.isNotNull(item.getTransferType())){
                String transferType = DictUtils.getDictLabel("transfer_type", String.valueOf(item.getTransferType()));
                if(ObjectUtils.isNotEmpty(transferType)){
                    item.setTransferTypeText(transferType);
                }
            }
            if(ObjectUtils.isNotNull(item.getApprovalStatus())){
                String approvalStatus = DictUtils.getDictLabel("transfer_approval_status", String.valueOf(item.getApprovalStatus()));
                if(ObjectUtils.isNotEmpty(approvalStatus)){
                    item.setApprovalStatusText(approvalStatus);
                }
            }

            if(ObjectUtils.isNotNull(item.getOriginalUserId())){
                CompanyUser companyUser = companyUserCacheService.selectCompanyUserById(item.getOriginalUserId());
                if(ObjectUtils.isNotNull(companyUser)){
                    item.setOriginalUserName(String.format("%s_%d",companyUser.getUserName(),companyUser.getUserId()));
                }
            }

            if(ObjectUtils.isNotNull(item.getTargetUserId())){
                CompanyUser companyUser = companyUserCacheService.selectCompanyUserById(item.getTargetUserId());
                if(ObjectUtils.isNotNull(companyUser)){
                    item.setTargetUserName(String.format("%s_%d", companyUser.getUserName(), companyUser.getUserId()));
                }
            }

            if(ObjectUtils.isNotNull(item.getInitiatorUserId())){
                CompanyUser companyUser = companyUserCacheService.selectCompanyUserById(item.getInitiatorUserId());
                if(ObjectUtils.isNotNull(companyUser)){
                    item.setInitiatorUserName(String.format("%s_%d", companyUser.getUserName(), companyUser.getUserId()));
                }
            }
        }
        return list;
    }

    /**
     * 新增客户转移审批
     *
     * @param customerTransferApproval 客户转移审批
     * @return 结果
     */
    @Override
    public int insertCustomerTransferApproval(CustomerTransferApproval customerTransferApproval)
    {
        return customerTransferApprovalMapper.insertCustomerTransferApproval(customerTransferApproval);
    }

    /**
     * 修改客户转移审批
     *
     * @param item 客户转移审批
     * @return 结果
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public int updateCustomerTransferApproval(CustomerTransferApproval item)
    {
        item.setProcessedAt(new Date());
//        审批状态: 0=待审批, 1=审批通过, 2=审批驳回, 3=已撤销
        // 如果审批通过 进行转移
        if(ObjectUtil.equal(1,item.getApprovalStatus())){
            FsUserTransferParamDTO transferParam = new FsUserTransferParamDTO();
            transferParam.setContent(item.getContent());
            transferParam.setTargetCompanyUserId(item.getTargetUserId());

            Asserts.check(StringUtils.isNotBlank(item.getCustomerIds()),"转移客户不能为空!");
            List<Long> customerIds = JSON.parseArray(item.getCustomerIds(), Long.class);
            transferParam.setUserIds(customerIds);
            transferParam.setSourceCompanyUserId(item.getOriginalUserId());

            fsUserService.transfer(transferParam);
        }
        List<Long> customerIds = JSON.parseArray(item.getCustomerIds(), Long.class);
        List<TransferCustomDTO> customerList = getCustomerList(customerIds, item);
        item.setTransferBefore(JSON.toJSONString(customerList));
        return customerTransferApprovalMapper.updateCustomerTransferApproval(item);
    }

    /**
     * 批量删除客户转移审批
     *
     * @param ids 需要删除的客户转移审批ID
     * @return 结果
     */
    @Override
    public int deleteCustomerTransferApprovalByIds(Long[] ids)
    {
        return customerTransferApprovalMapper.deleteCustomerTransferApprovalByIds(ids);
    }

    /**
     * 删除客户转移审批信息
     *
     * @param id 客户转移审批ID
     * @return 结果
     */
    @Override
    public int deleteCustomerTransferApprovalById(Long id)
    {
        return customerTransferApprovalMapper.deleteCustomerTransferApprovalById(id);
    }
}
