package cn.com.ctop.finance.payment.service.impl;

import cn.com.ctop.common.module.entity.Advertiser;
import cn.com.ctop.common.module.entity.Product;
import cn.com.ctop.common.module.service.IMessageTemplate;
import cn.com.ctop.common.module.service.IProductService;
import cn.com.ctop.common.module.service.ISendMessageService;
import cn.com.ctop.common.module.service.ISysUserService;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.finance.payment.entity.FinancePaymentApplication;
import cn.com.ctop.finance.payment.entity.FinancePaymentApplicationRecord;
import cn.com.ctop.finance.payment.mapper.FinancePaymentApplicationMapper;
import cn.com.ctop.finance.payment.mapper.FinancePaymentApplicationRecordMapper;
import cn.com.ctop.finance.payment.service.IFinancePaymentApplicationService;
import cn.com.ctop.finance.payment.service.IFinancePaymentPoolService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.entity.SysUser;
import org.jeecg.modules.ctop.service.IAdvertiserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 申请垫款表
 *
 * @author jeecg-boot
 * 2023-04-11
 * @version V1.0
 */
@Service
public class FinancePaymentApplicationServiceImpl extends ServiceImpl<FinancePaymentApplicationMapper, FinancePaymentApplication> implements IFinancePaymentApplicationService {

    @Autowired
    private FinancePaymentApplicationRecordMapper recordMapper;
    @Autowired
    private IProductService productService;
    @Autowired
    private IFinancePaymentPoolService poolService;

    @Autowired
    private IAdvertiserService advertiserService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISendMessageService sendMessageService;

    @Autowired
    private IMessageTemplate messageTemplate;

    //财务审核角色ID
    public static final String FINANCIAL_REVIEW_ROLE_ID = "32825ea6b43cb61bffa09bf05ad69cf2";
    //财务角色ID
    public static final String FINANCIAL_ROLE_ID = "5f3ee6bbd66cbd2df404cdec4ad7e5a3";

    @Override
    public void add(JSONObject request) throws InterruptedException {
        FinancePaymentApplication application = JSONObject.parseObject(JSONObject.toJSONString(request), FinancePaymentApplication.class);
        SysUser user = userService.getById(application.getApplicanterId());
        if (!Check.isNull(user)) {
            application.setApplicanter(user.getRealname());
        }
        Product product = productService.getById(application.getProductId());
        if (!Check.isNull(product)) {
            application.setProductName(product.getProductName());
        }

        List<String> advertiserIds = Arrays.asList(application.getAdvertiserId().split(","));
        Advertiser advertiser = advertiserService.getById(advertiserIds.get(0));
        if (!Check.isNull(advertiser)) {
            application.setAdvertiserName(advertiser.getName());
        }
        //获取审核人
        getRevieweder(application);
        Date createTime = new Date();
        Thread.sleep(2000);
        if ("0".equals(application.getRebateType())) {
            application.setRebateType("2");
        }
        //添加申请
        this.save(application);
        //消息通知内容
        //添加申请记录 0 创建
        insertRecord(application.getId(), application.getApplicanterId(), "0", null, application.getFiles(), createTime);
        String message = messageTemplate.getFinancePaymentApplicationMessage(application);
        //审核人为 财务审核角色
        if (application.getReviewederId().contains("financ")) {
            List<SysUser> users = userService.getUserListByRoleId(FINANCIAL_REVIEW_ROLE_ID);
            users.addAll(userService.getUserListByRoleId(FINANCIAL_ROLE_ID));
            for (SysUser u : users) {
                sendMessageService.sendMessage(u.getId(), message);
            }
        } else {
            sendMessageService.sendMessage(application.getReviewederId(), message);
        }
    }

    @Override
    public Result<Object> getAdvertisers(String mediaType) {
        if ("11".equals(mediaType)) {
            mediaType = null;
        }
        return Result.ok(baseMapper.getAdvertisers(mediaType));
    }

    @Override
    public Result<Object> getProductByAdvertiserIds(String ids) {
        List<String> advertiserIds = Arrays.asList(ids.split(","));
        return Result.ok(baseMapper.getProductByAdvertiserIds(advertiserIds));
    }

    @Override
    public Result<Object> updateStatus(FinancePaymentApplication application) {
        FinancePaymentApplication oldApplication = this.getById(application.getId());
        if (Check.isNull(oldApplication)) {
            return Result.error("未查询到申请");
        }
        String reviewederId = oldApplication.getReviewederId();
        String auditStatus = application.getAuditStatus();//1-待审核、3-审核通过、4-临时通过、5-审核拒绝
        if ("3".equals(auditStatus) || "4".equals(auditStatus)) {
            if (reviewederId.contains("financ")) {
                application.setReviewederId(application.getUserId());
                SysUser user = userService.getById(application.getUserId());
                if (!Check.isNull(user)) {
                    application.setRevieweder(user.getRealname());
                }
            }
            this.updateById(application);
            poolService.add(null, oldApplication);
        } else if ("5".equals(auditStatus)) {
            if ("4".equals(oldApplication.getAuditStatus())) {
                poolService.reduce(null, oldApplication);
            }
            application.setFiles(Check.isNull(application.getFiles()) ? "-" : application.getFiles());
            application.setReviewederId(application.getUserId());
            SysUser user = userService.getById(application.getUserId());
            if (!Check.isNull(user)) {
                application.setRevieweder(user.getRealname());
            }
            this.updateById(application);
            //添加记录
            insertRecord(application.getId(), application.getUserId(), oldApplication.getAuditStatus(), oldApplication.getApprovalContent(), oldApplication.getFiles(), oldApplication.getUpdateTime());
            String failMessage = messageTemplate.getFinancePaymentApplicationFailMessage(oldApplication);
            sendMessageService.sendMessage(oldApplication.getApplicanterId(), failMessage);
        }
        return Result.ok();
    }

    @Override
    public Result<Object> edit(FinancePaymentApplication application) throws InterruptedException {
        FinancePaymentApplication oldApplication = this.getById(application.getId());
        if (Check.isNull(oldApplication)) {
            return Result.error("未查询到申请");
        }
        application.setAuditStatus("1");//待审核
        Product product = productService.getById(application.getProductId());
        if (!Check.isNull(product)) {
            application.setProductName(product.getProductName());
        }
        List<String> advertiserIds = Arrays.asList(application.getAdvertiserId().split(","));
        Advertiser advertiser = advertiserService.getById(advertiserIds.get(0));
        if (!Check.isNull(advertiser)) {
            application.setAdvertiserName(advertiser.getName());
        }
        //添加拒绝记录
        insertRecord(application.getId(), oldApplication.getReviewederId(), oldApplication.getAuditStatus(), oldApplication.getApprovalContent(), oldApplication.getFiles(), oldApplication.getUpdateTime());
        //添加修改记录
        insertRecord(application.getId(), application.getApplicanterId(), "-1", null, application.getFiles(), new Date());
        Thread.sleep(2000);
        //获取审核人
        getRevieweder(application);
        if ("0".equals(application.getRebateType())) {
            application.setRebateType("2");
        }
        this.updateById(application);
        //消息通知内容
        String message = messageTemplate.getFinancePaymentApplicationMessage(application);
        //审核人为 财务审核角色
        if (application.getReviewederId().contains("financ")) {
            List<SysUser> users = userService.getUserListByRoleId(FINANCIAL_REVIEW_ROLE_ID);
            users.addAll(userService.getUserListByRoleId(FINANCIAL_ROLE_ID));
            for (SysUser u : users) {
                sendMessageService.sendMessage(u.getId(), message);
            }
        } else {
            sendMessageService.sendMessage(application.getReviewederId(), message);
        }
        return Result.ok();
    }

    @Override
    public Result<Object> queryPoolInfo(String advertiserId, String productId, String type) {
        return Result.ok(baseMapper.queryPoolInfo(advertiserId, productId, type));
    }

    @Override
    public Result<Object> updateTemporaryFiles(FinancePaymentApplication application) {
        FinancePaymentApplication oldApplication = this.getById(application.getId());
        if (Check.isNull(oldApplication)) {
            return Result.error("未查询到申请");
        }
        String auditStatus = oldApplication.getAuditStatus();//4-临时通过
        if ("4".equals(auditStatus)) {
            application.setAuditStatus("3");
            application.setApprovalContent(Check.isNull(application.getApprovalContent()) ? "-" : application.getApprovalContent());
            application.setReviewederId(application.getUserId());
            SysUser user = userService.getById(application.getUserId());
            if (!Check.isNull(user)) {
                application.setRevieweder(user.getRealname());
            }
            this.updateById(application);
            //添加审核记录
            insertRecord(application.getId(), oldApplication.getReviewederId(), auditStatus, oldApplication.getApprovalContent(), oldApplication.getFiles(), oldApplication.getUpdateTime());
        }
        return Result.ok();
    }

    @Override
    public Result<Object> queryAuditProcess(Long id) {
        return Result.ok(baseMapper.queryAuditProcess(id));
    }

    @Override
    public Result<Object> queryInfo(String advertiserId, String productId, String type) {
        return Result.ok(baseMapper.queryInfo(advertiserId, productId, type));
    }

    @Override
    public Result<Object> queryCwjsPolicyInfo(String advertiserName, String productName, String type) {
        return Result.ok(baseMapper.queryCwjsPolicyInfo(advertiserName, productName, type));
    }

    /**
     * 获取审核人
     * 1、磁力金牛    垫款        审核人 --吴睿刚(4aba62011120ac565c7f2b9f8f4aa96b)
     * 2、非磁力金牛  垫款        审核人 --赵旺(00d630a129e4487cba5427788a1f08ce)
     * 3、非磁力金牛 （临时）垫款  审核人 --丁兆明(b161b7d9793942f980dbfe8c931cd1b0)
     * 4、所有媒体   预付款      审核人 --财务角色
     */
    private void getRevieweder(FinancePaymentApplication application) {
        String rebateType = application.getPaymentType();//类型：1-预付款、2-垫款
        if ("1".equals(rebateType)) {
            //返回财务
            application.setReviewederId("financ");
            application.setRevieweder("-");
        } else {
            String paymentMedia = application.getPaymentMedia();//媒体类型 1-头条、2-快手、7-磁力金牛、9-广点通
            if ("7".equals(paymentMedia)) {
                //吴睿刚(4aba62011120ac565c7f2b9f8f4aa96b)
                application.setReviewederId("4aba62011120ac565c7f2b9f8f4aa96b");
                application.setRevieweder("吴睿刚");
            } else {
                //临时垫款
                if ("1".equals(application.getTemporaryAdvances())) {
                    application.setReviewederId("b161b7d9793942f980dbfe8c931cd1b0");
                    application.setRevieweder("丁兆明");
                } else {
                    application.setReviewederId("00d630a129e4487cba5427788a1f08ce");
                    application.setRevieweder("赵旺");
                }
            }
        }
    }

    private void insertRecord(Long applicationId, String operatorId, String status, String txt, String files, Date time) {
        if ("1".equals(status)) {
            return;
        }
        FinancePaymentApplicationRecord record = new FinancePaymentApplicationRecord();
        record.setApplicationId(applicationId);
        record.setReviewederId(operatorId);
        record.setAuditStatus(status);
        record.setApprovalContent(txt);
        record.setFiles(files);
        record.setCreateTime(time);
        recordMapper.insert(record);
    }

}

