package com.staffing.custom.service.impl;

import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.staffing.common.exception.ServiceException;
import com.staffing.common.utils.DateUtils;
import com.staffing.common.utils.OrderUtils;
import com.staffing.common.utils.StringUtils;
import com.staffing.custom.domain.*;
import com.staffing.custom.mapper.StEmployeeFundRecordMapper;
import com.staffing.custom.mapper.StEmployeeMapper;
import com.staffing.custom.mapper.StTaskSignMapper;
import com.staffing.custom.mapper.StTransferRecordMapper;
import com.staffing.custom.param.FxParam;
import com.staffing.custom.service.IStEmployeeFundRecordService;
import com.staffing.custom.service.IStTaskService;
import com.staffing.custom.service.TransferBatchService;
import com.staffing.system.service.impl.SysUserServiceImpl;
import com.wechat.pay.java.service.transferbatch.model.InitiateBatchTransferRequest;
import com.wechat.pay.java.service.transferbatch.model.TransferDetailInput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 员工资金流水Service业务层处理
 * 
 * @author staffing
 * @date 2024-08-27
 */
@Service
public class StEmployeeFundRecordServiceImpl implements IStEmployeeFundRecordService
{
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private StEmployeeFundRecordMapper stEmployeeFundRecordMapper;
    @Autowired
    private StEmployeeMapper stEmployeeMapper;
    @Autowired
    private StTaskSignMapper taskSignMapper;
    @Autowired
    private IStTaskService stTaskService;

    @Autowired
    private StTransferRecordMapper stTransferRecordMapper;

    @Autowired
    private TransferBatchService transferBatchService;
    /**
     * 查询员工资金流水
     * 
     * @param id 员工资金流水主键
     * @return 员工资金流水
     */
    @Override
    public StEmployeeFundRecord selectStEmployeeFundRecordById(Long id)
    {
        return stEmployeeFundRecordMapper.selectStEmployeeFundRecordById(id);
    }

    /**
     * 查询员工资金流水列表
     * 
     * @param stEmployeeFundRecord 员工资金流水
     * @return 员工资金流水
     */
    @Override
    public List<StEmployeeFundRecord> selectStEmployeeFundRecordList(StEmployeeFundRecord stEmployeeFundRecord)
    {
        List<StEmployeeFundRecord> fundRecords = stEmployeeFundRecordMapper.selectStEmployeeFundRecordList(stEmployeeFundRecord);
        for (StEmployeeFundRecord fundRecord : fundRecords) {
            StTaskSign stTaskSign = taskSignMapper.selectStTaskSignByTaskIdAndUserId(fundRecord.getTaskId(), fundRecord.getEmployeeId());
            fundRecord.setStTaskSign(stTaskSign);
        }
        return fundRecords;
    }

    /**
     * 新增员工资金流水
     * 
     * @param stEmployeeFundRecord 员工资金流水
     * @return 结果
     */
    @Override
    public int insertStEmployeeFundRecord(StEmployeeFundRecord stEmployeeFundRecord)
    {
        return stEmployeeFundRecordMapper.insertStEmployeeFundRecord(stEmployeeFundRecord);
    }

    /**
     * 修改员工资金流水
     * 
     * @param stEmployeeFundRecord 员工资金流水
     * @return 结果
     */
    @Override
    public int updateStEmployeeFundRecord(StEmployeeFundRecord stEmployeeFundRecord)
    {
        stEmployeeFundRecord.setUpdateTime(DateUtils.getNowDate());
        return stEmployeeFundRecordMapper.updateStEmployeeFundRecord(stEmployeeFundRecord);
    }

    /**
     * 批量删除员工资金流水
     * 
     * @param ids 需要删除的员工资金流水主键
     * @return 结果
     */
    @Override
    public int deleteStEmployeeFundRecordByIds(Long[] ids)
    {
        return stEmployeeFundRecordMapper.deleteStEmployeeFundRecordByIds(ids);
    }

    /**
     * 删除员工资金流水信息
     * 
     * @param id 员工资金流水主键
     * @return 结果
     */
    @Override
    public int deleteStEmployeeFundRecordById(Long id)
    {
        return stEmployeeFundRecordMapper.deleteStEmployeeFundRecordById(id);
    }


    @Override
    public String importRecord(List<StEmployeeFundRecord> records)
    {
        if (StringUtils.isNull(records) || records.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (StEmployeeFundRecord record : records)
        {
            try
            {
                StEmployeeFundRecord update = new StEmployeeFundRecord();
                update.setRealPrice(record.getRealPrice());
                update.setEmployeeId(record.getEmployeeId());
                update.setTaskId(record.getTaskId());
                update.setUpdateTime(new Date());
                // 验证是否存在这条数据,不支持追加数据，所以注释掉下边代码
//                StEmployeeFundRecord stEmployeeFundRecords = stEmployeeFundRecordMapper.selectStEmployeeFundRecordByUidAndTaskId(record.getTaskId(), record.getEmployeeId());
//                if (stEmployeeFundRecords == null) {
//                    stEmployeeFundRecordMapper.insertStEmployeeFundRecord(record);
//                    successNum++;
//                    successMsg.append("<br/>" + successNum + "、数据导入成功");
//                } else{
                    int i = stEmployeeFundRecordMapper.updateStEmployeeFundRecordByTaskAndUid(update);
                    if (i > 0){
                        successNum++;
                        successMsg.append("<br/>" + successNum + "、数据导入修改成功");
                    }
//                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、数据导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }


    public String faxin(FxParam fxParam){

        StTask stTask = stTaskService.selectStTaskById(fxParam.getTaskId(), true);
        Map<Long, StTaskSign> taskSignMap = stTask.getListSign().stream()
                .collect(Collectors.toMap(StTaskSign::getEmployeeId, Function.identity()));

        for (Long employeeId : fxParam.getEmployeeIds()) {
            StTaskSign stTaskSign = taskSignMap.get(employeeId);
            if (stTaskSign == null){
                return "发薪失败, 员工id:" + employeeId + "没有签到，不能发薪";
            }
            StEmployeeFundRecord stEmployeeFundRecord = stTaskSign.getStEmployeeFundRecord();
            if (stEmployeeFundRecord == null){
                continue;
            }
            if (stEmployeeFundRecord.getPayStatus() == 1){
                return "发薪失败, 员工id:" + employeeId + "已经发放，请刷新发薪页面";
            }
        }
        List<StEmployee> stEmployees = stEmployeeMapper.selectStEmployeeByIds(fxParam.getEmployeeIds());
        Map<Long, StEmployee> stEmployeeHashMap = stEmployees.stream()
                .collect(Collectors.toMap(StEmployee::getId, Function.identity()));

        InitiateBatchTransferRequest request = new InitiateBatchTransferRequest();
        request.setAppid(TransferBatchService.appId);
        request.setOutBatchNo(OrderUtils.genOrderId("B"));
        request.setBatchName("工资");
        request.setBatchRemark(stTask.getTaskName() + "的工资");
        request.setTotalNum(fxParam.getEmployeeIds().size());//总笔数
        BigDecimal sumAmount = new BigDecimal(0);
        for (Long employeeId : fxParam.getEmployeeIds()) {
            StTaskSign stTaskSign = taskSignMap.get(employeeId);
            sumAmount = sumAmount.add(new BigDecimal(stTaskSign.getStEmployeeFundRecord().getRealPrice()));


            TransferDetailInput transferDetailInput = new TransferDetailInput();
            transferDetailInput.setOutDetailNo(stTaskSign.getStEmployeeFundRecord().getTransferNo());
            StEmployee stEmployee = stEmployeeHashMap.get(employeeId);
            if (stEmployee == null){
                return "系统错误，发薪失败, 员工id:" + employeeId + "没有找到对应数据，联系开发者";
            }
            transferDetailInput.setOpenid(stEmployee.getOpenId());
            transferDetailInput.setTransferAmount(new BigDecimal(stTaskSign.getStEmployeeFundRecord().getRealPrice()).multiply(new BigDecimal("100")).longValue());
            transferDetailInput.setTransferRemark(stTask.getTaskName() + "的工资");
            transferDetailInput.setUserName(stEmployee.getRealName());
            request.getTransferDetailList().add(transferDetailInput);
        }


        StTransferRecord stTransferRecord = new StTransferRecord();
        stTransferRecord.setCreateTime(new Date());
        stTransferRecord.setTaskId(fxParam.getTaskId());
        stTransferRecord.setTaskName(stTask.getTaskName());
        stTransferRecord.setPayStatus(0);
        stTransferRecord.setCountPrice(sumAmount.toString());
        stTransferRecord.setTransferNo(request.getOutBatchNo());
        stTransferRecord.setEmployeeIds(fxParam.getEmployeeIds().stream().map(String::valueOf).collect(Collectors.joining(",")));
        stTransferRecordMapper.insertStTransferRecord(stTransferRecord);


        request.setTotalAmount(sumAmount.multiply(new BigDecimal("100")).longValue());//总金额
        request.setTransferSceneId(null);
//        request.setNotifyUrl("https://192.168.18.122:8080/merchant/fund/fxResult");
        transferBatchService.initiateBatchTransfer(request);

        return "success";
    }
}
