package com.ytpm.middle.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.ytpm.agent.model.YtPlatformAttach;
import com.ytpm.agent.param.AttachParam;
import com.ytpm.general.RepMessage;
import com.ytpm.general.Result;
import com.ytpm.general.ResultTable;
import com.ytpm.handle.CustomerException;
import com.ytpm.middle.dao.AgentMapper;
import com.ytpm.middle.dao.AttachMapper;
import com.ytpm.middle.dao.EnterpriseMapper;
import com.ytpm.middle.dao.FinanceMapper;
import com.ytpm.middle.model.YtFinancePayment;
import com.ytpm.middle.model.YtFinancePaymentItem;
import com.ytpm.middle.model.YtMiddleEnterprise;
import com.ytpm.middle.param.ConfirmReceiveParam;
import com.ytpm.middle.param.PaymentItemParam;
import com.ytpm.middle.param.PaymentListParam;
import com.ytpm.middle.service.FinanceService;
import com.ytpm.middle.util.RedisUtil;
import com.ytpm.middle.util.TencentSmsUtil;
import com.ytpm.middle.view.FinancePaymentVO;
import com.ytpm.middle.view.PaymentItemVO;
import com.ytpm.util.IDUtil;
import com.ytpm.util.RandomPasswordGenerator;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author Marx
 * @date 2025/8/6 13:31
 */
@Service
public class FinanceServiceImpl implements FinanceService {

    @Resource
    private FinanceMapper financeMapper;
    @Resource
    private EnterpriseMapper enterpriseMapper;
    @Resource
    private AgentMapper agentMapper;
    @Resource
    private AttachMapper attachMapper;

    @Resource
    private RedisUtil redisUtil;
    @Resource
    private TencentSmsUtil smsUtil;

    @Value("${tencent.sms.registryTemplateId}")
    private String registryTemplateId;

    /**
     * 查询缴费项目列表
     */
    @Override
    public ResultTable<PaymentItemVO> queryList(PaymentItemParam param) {
        PageHelper.startPage(param.getPage(), param.getLimit());
        return ResultTable.resultTableOk(new PageInfo<>(financeMapper.queryList(param)));
    }

    /**
     * 新增缴费项目
     */
    @Override
    public Result<String> addItem(PaymentItemParam param) {
        YtFinancePaymentItem item = new YtFinancePaymentItem();
        BeanUtils.copyProperties(param, item);
        item.setItemId(IDUtil.generateFlowID("item_"));
        financeMapper.addItem(item);
        return Result.resultOk(RepMessage.SAVE_SUCCESS);
    }

    /**
     * 修改缴费项目
     */
    @Override
    public Result<String> updateItem(PaymentItemParam param) {
        YtFinancePaymentItem old = financeMapper.selectItemOne(param.getItemId());
        if(Objects.isNull(old)){
            return Result.resultErr(RepMessage.OBJECT_NOT_EXIST);
        }
        YtFinancePaymentItem item = new YtFinancePaymentItem();
        BeanUtils.copyProperties(param, item);
        financeMapper.updateItem(item);
        return Result.resultOk(RepMessage.MODIFY_SUCCESS);
    }

    /**
     * 删除缴费项目
     */
    @Override
    public Result<String> delItem(String itemId, String userId) {
        YtFinancePaymentItem old = financeMapper.selectItemOne(itemId);
        if(Objects.isNull(old)){
            return Result.resultErr(RepMessage.OBJECT_NOT_EXIST);
        }
        YtFinancePaymentItem item = new YtFinancePaymentItem();
        item.setItemId(itemId);
        item.setUpdateParam(userId);
        item.setAvailable(0);
        financeMapper.updateItem(item);
        return Result.resultOk(RepMessage.DELETE_SUCCESS);
    }

    /**
     * 缴费单列表
     */
    @Override
    public ResultTable<FinancePaymentVO> paymentList(PaymentListParam param) {
        PageHelper.startPage(param.getPage(), param.getLimit());
        return ResultTable.resultTableOk(new PageInfo<>(financeMapper.paymentList(param)));
    }

    /**
     * 缴费单明细
     */
    @Override
    public Result<FinancePaymentVO> paymentDetail(String paymentId) {
        return Result.resultObjOk(financeMapper.getPaymentDetail(paymentId));
    }

    /**
     * 确认收款
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<String> confirmReceive(ConfirmReceiveParam param) {
        FinancePaymentVO detail = financeMapper.getPaymentDetail(param.getPaymentId());
        if(Objects.isNull(detail)){
            return Result.resultErr(RepMessage.OBJECT_NOT_EXIST);
        }
        if(CollUtil.isEmpty(param.getAttachList())){
            return Result.resultErr(RepMessage.PAYMENT_ATTACH_EMPTY);
        }
        changePaymentInfo(param);
        changeEnterpriseInfo(param);
        return Result.resultObjOk(RepMessage.CONFIRM_SUCCESS);
    }

    /**
     * 修改企业用户缴费单信息
     */
    private void changePaymentInfo(ConfirmReceiveParam param) {
        //修改缴费单状态、收款金额等
        YtFinancePayment payment = new YtFinancePayment();
        payment.setPaymentId(param.getPaymentId());
        payment.setPaymentStatus(1);
        payment.setFinishTime(new Date());
        payment.setUpdateParam(param.getUpdateUserId());
        financeMapper.updatePayment(payment);
        financeMapper.updatePaymentRecord(payment.getPaymentId());
        //增加缴费凭证信息
        List<YtPlatformAttach> dataList = new ArrayList<>();
        YtPlatformAttach attach;
        for (AttachParam attachParam : param.getAttachList()) {
            attach = new YtPlatformAttach();
            BeanUtils.copyProperties(attachParam, attach);
            attach.setTargetType(2);
            attach.setTargetId(payment.getPaymentId());
            attach.setUploadTime(new Date());
            attach.setAttachId(IdUtil.getSnowflakeNextIdStr());
            attach.setUploadUserId(param.getCreateUserId());
            dataList.add(attach);
        }
        attachMapper.batchInsert(dataList);
    }

    /**
     * 设置企业信息，并推送短信给客户
     */
    private void changeEnterpriseInfo(ConfirmReceiveParam param) {
        //设置企业的分成比例和出账日
        YtMiddleEnterprise old = enterpriseMapper.selectPrimary(param.getEnterpriseId());
        if(Objects.nonNull(old)){
            YtMiddleEnterprise enterprise = new YtMiddleEnterprise();
            enterprise.setEnterpriseId(old.getEnterpriseId());
            enterprise.setPaymentDate(param.getPaymentDate());
            enterprise.setSharingRatio(new BigDecimal(50));
            enterpriseMapper.updateById(enterprise);
        }
        //取出redis缓存的企业用户负责人手机号对应的密码，短信发送
        String pwd = "";
        if(Boolean.TRUE.equals(redisUtil.hasKey(old.getConcatPhone()))){
            pwd = redisUtil.getStr(old.getConcatPhone());
        }else {
            pwd = RandomPasswordGenerator.generatePassword(8);
            agentMapper.resetPwd(old.getUserId(),new BCryptPasswordEncoder().encode(pwd));
        }
        try {
            smsUtil.sendLoginPwd(old.getConcatPhone(), pwd,registryTemplateId);
            redisUtil.del(old.getConcatPhone());
        } catch (TencentCloudSDKException e) {
            throw new CustomerException(e.getMessage());
        }
    }
}
