package com.fs.qw.service.impl;


import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
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.course.domain.FsUserCompanyUser;
import com.fs.course.domain.FsUserCompanyUserQw;
import com.fs.course.service.IFsUserCompanyUserQwService;
import com.fs.course.service.IFsUserCompanyUserService;
import com.fs.his.domain.FsUser;
import com.fs.qw.domain.CustomerTransferApproval;
import com.fs.qw.domain.CustomerTransferApprovalQw;
import com.fs.qw.dto.FsUserTransferParamDTO;
import com.fs.qw.dto.UserProjectDTO;
import com.fs.qw.mapper.CustomerTransferApprovalMapper;
import com.fs.qw.mapper.CustomerTransferApprovalQwMapper;
import com.fs.qw.service.ICustomerTransferApprovalQwService;
import com.fs.qw.service.ICustomerTransferApprovalService;
import com.fs.qw.vo.TransferCustomDTO;
import com.fs.store.service.cache.IFsUserCacheService;
import com.hc.openapi.tool.util.StringUtils;
import org.apache.hc.core5.util.Asserts;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 客户转移审批-企微的Service业务层处理
 *
 * @author fs
 * @date 2025-10-24
 */
@Service
public class CustomerTransferApprovalQwServiceImpl extends ServiceImpl<CustomerTransferApprovalQwMapper, CustomerTransferApprovalQw> implements ICustomerTransferApprovalQwService {


    @Autowired
    private CustomerTransferApprovalQwMapper transferApprovalQwMapper;

    @Autowired
    private ICompanyCacheService companyCacheService;

    @Autowired
    private ICompanyUserCacheService companyUserCacheService;

    @Autowired
    private IFsUserCacheService fsUserCacheService;

    @Autowired
    private IFsUserCompanyUserQwService userCompanyUserQwService;

    /**
     * 查询客户转移审批-企微的
     *
     * @param id 客户转移审批-企微的主键
     * @return 客户转移审批-企微的
     */
    @Override
    public CustomerTransferApprovalQw selectCustomerTransferApprovalQwById(Long id)
    {
        return baseMapper.selectCustomerTransferApprovalQwById(id);
    }

    /**
     * 查询客户转移审批-企微的列表
     *
     * @param customerTransferApprovalQw 客户转移审批-企微的
     * @return 客户转移审批-企微的
     */
    @Override
    public List<CustomerTransferApprovalQw> selectCustomerTransferApprovalQwList(CustomerTransferApprovalQw customerTransferApprovalQw)
    {
        List<CustomerTransferApprovalQw> list = transferApprovalQwMapper.selectCustomerTransferApprovalQwList(customerTransferApprovalQw);
        for (CustomerTransferApprovalQw 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 customerTransferApprovalQw 客户转移审批-企微的
     * @return 结果
     */
    @Override
    public int insertCustomerTransferApprovalQw(CustomerTransferApprovalQw customerTransferApprovalQw)
    {
        return baseMapper.insertCustomerTransferApprovalQw(customerTransferApprovalQw);
    }

    /**
     * 修改客户转移审批-企微的
     *
     * @param item 客户转移审批-企微的
     * @return 结果
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public int updateCustomerTransferApprovalQw(CustomerTransferApprovalQw item)
    {
        item.setProcessedAt(new Date());
//        审批状态: 0=待审批, 1=审批通过, 2=审批驳回, 3=已撤销
        // 如果审批通过 进行转移
        List<UserProjectDTO> customerIds1 = JSON.parseArray(item.getCustomerIds(), UserProjectDTO.class);
        List<TransferCustomDTO> customerList = getCustomerList(customerIds1, item);
        item.setTransferBefore(JSON.toJSONString(customerList));

        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<UserProjectDTO> customerIds = JSON.parseArray(item.getCustomerIds(), UserProjectDTO.class);
            transferParam.setUserIds(customerIds);
            transferParam.setSourceCompanyUserId(item.getOriginalUserId());

            for (UserProjectDTO customerId : customerIds) {
                CompanyUser companyUser = companyUserCacheService.selectCompanyUserById(item.getTargetUserId());
                userCompanyUserQwService.changeRelationship(customerId.getUserId(), customerId.getProjectId(), companyUser.getCompanyId(), companyUser.getUserId());
            }
        }


        return transferApprovalQwMapper.updateCustomerTransferApprovalQw(item);
    }

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

        for (UserProjectDTO customerId : customerIds) {

            FsUser fsUser = fsUserCacheService.selectFsUserById(customerId.getUserId());
            if(ObjectUtils.isNotNull(fsUser)){
                FsUserCompanyUserQw userCompanyUserQw = userCompanyUserQwService.selectByUserIdAndProjectId(customerId.getUserId(), customerId.getProjectId());
                if(Objects.nonNull(userCompanyUserQw)){
                    CompanyUser companyUser = companyUserCacheService.selectCompanyUserById(userCompanyUserQw.getCompanyUserId());
                    String companyUserName = String.format("%s_%d", companyUser.getUserName(), companyUser.getUserId());

                    CompanyUser afterCompanyUser = companyUserCacheService.selectCompanyUserById(item.getTargetUserId());
                    String afterCompanyUserName = String.format("%s_%d", afterCompanyUser.getUserName(), companyUser.getUserId());

                    customerList.add(TransferCustomDTO.builder()
                            .userName(String.format("%s_%d", fsUser.getNickName(), fsUser.getUserId()))
                            .userId(fsUser.getUserId())
                            .projectId(customerId.getProjectId())
                            .beforeCompanyUserName(companyUserName)
                            .beforeCompanyUserId(companyUser.getUserId())
                            .afterCompanyUserName(afterCompanyUserName)
                            .afterCompanyUserId(item.getTargetUserId())
                            .build());
                }
            }
        }
        return customerList;
    }

    /**
     * 批量删除客户转移审批-企微的
     *
     * @param ids 需要删除的客户转移审批-企微的主键
     * @return 结果
     */
    @Override
    public int deleteCustomerTransferApprovalQwByIds(Long[] ids)
    {
        return baseMapper.deleteCustomerTransferApprovalQwByIds(ids);
    }

    /**
     * 删除客户转移审批-企微的信息
     *
     * @param id 客户转移审批-企微的主键
     * @return 结果
     */
    @Override
    public int deleteCustomerTransferApprovalQwById(Long id)
    {
        return baseMapper.deleteCustomerTransferApprovalQwById(id);
    }

    @Override
    public void autoApprovePassQw() {
        List<CustomerTransferApprovalQw> customerTransferApprovalQws = transferApprovalQwMapper.queryPendingData();
        for (CustomerTransferApprovalQw approval : customerTransferApprovalQws) {
            approval.setApprovalStatus(1);
            approval.setApprovalRemark("自动审批");
            approval.setApproverUserId(1L);
            ICustomerTransferApprovalQwService service = (ICustomerTransferApprovalQwService) AopContext.currentProxy();
            service.updateCustomerTransferApprovalQw(approval);
        }
    }
}
