package com.ruixuan.salesLeads.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruixuan.common.core.domain.ResultResponse;
import com.ruixuan.common.core.page.TableDataInfo;
import com.ruixuan.common.utils.Check;
import com.ruixuan.common.utils.DateUtils;
import com.ruixuan.common.utils.PageUtils;
import com.ruixuan.salesLeads.mapper.SaleFinancePolicyApprovalLogMapper;
import com.ruixuan.salesLeads.mapper.SaleFinancePolicyInfoMapper;
import com.ruixuan.salesLeads.mapper.SaleFinancePolicyProductInfoMapper;
import com.ruixuan.salesLeads.mapper.SaleFinancePolicyRebateInfoMapper;
import com.ruixuan.salesLeads.pojo.SaleFinancePolicyApprovalLogPojo;
import com.ruixuan.salesLeads.pojo.SaleFinancePolicyInfoPojo;
import com.ruixuan.salesLeads.pojo.SaleFinancePolicyProductInfoPojo;
import com.ruixuan.salesLeads.pojo.SaleFinancePolicyRebateInfoPojo;
import com.ruixuan.salesLeads.pojo.vo.PolicyApprovalVo;
import com.ruixuan.salesLeads.pojo.vo.SaleFinancePolicyInfoVo;
import com.ruixuan.salesLeads.service.ISaleFinacePolicyService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * ***************************************************
 *
 * @Auther: zianY
 * @Descipion: 政策
 * @CreateDate: 2022-05-19
 * ****************************************************
 */
@Slf4j
@Service
public class SaleFinacePolicyServiceImpl implements ISaleFinacePolicyService {


    @Autowired
    private SaleFinancePolicyInfoMapper saleFinancePolicyInfoMapper;

    @Autowired
    private SaleFinancePolicyProductInfoMapper saleFinancePolicyProductInfoMapper;

    @Autowired
    private SaleFinancePolicyRebateInfoMapper saleFinancePolicyRebateInfoMapper;

    @Autowired
    private SaleFinancePolicyApprovalLogMapper saleFinancePolicyApprovalLogMapper;



    /**
     *
     * @description: 政策列表查询
     *
     * @param saleFinancePolicyInfoVo
     * @return: com.ruixuan.common.core.domain.ResultResponse
     * @author: zianY
     */
    @Override
    public ResultResponse selectPolicyList(SaleFinancePolicyInfoVo saleFinancePolicyInfoVo) {
        PageUtils.startPage();
        List<SaleFinancePolicyInfoPojo> list = saleFinancePolicyInfoMapper.selectPolicyList(saleFinancePolicyInfoVo);
        return ResultResponse.successMsg("政策信息查询成功",new TableDataInfo(list,list.size()));
    }


    /**
     *
     * @description: 政策详情查询
     *
     * @param policyId 政策id
     * @return: com.ruixuan.common.core.domain.ResultResponse
     * @author: zianY
     */
    @Override
    public ResultResponse selectPolicyInfoById(String policyId) {
        return ResultResponse.successMsg("政策详情查询成功", saleFinancePolicyInfoMapper.selectPolicyInfoById(policyId));
    }



    /**
     *
     * @description: 政策新增
     *
     * @param policyInfoPojo
     * @return: com.ruixuan.common.core.domain.ResultResponse
     * @author: zianY
     */
    @Override
    public ResultResponse addSaleFinancePolicyInfo(SaleFinancePolicyInfoPojo policyInfoPojo) {
        //0:草稿 1：待审核 2:审核中 3：审核通过4：审核拒绝
        policyInfoPojo.setApprovedStatus(1);

        //审核人
        String approvaluUser;
        //查询所有审核人
        List<JSONObject> approvalUserList = saleFinancePolicyInfoMapper.selectPolicyApprovalUser();
        //是否预付  0：否  1：是
        /**
         * 是否预付 0-否 需要法务(1级审核人)进行审核
         * 1-是 直接跨过法务 由上级(2级审核人)进行审核
         */
        if (StringUtils.equals(policyInfoPojo.getAdvancePay()+"","0")){
            approvaluUser = approvalUserList.get(0).getString("approval_user_id");
        }else {
            approvaluUser = approvalUserList.get(1).getString("approval_user_id");
        }

        //添加审核人
        policyInfoPojo.setApprovedProgress(approvaluUser);
        //保存政策
        saleFinancePolicyInfoMapper.addSaleFinancePolicyInfo(policyInfoPojo);

        //添加产品
        SaleFinancePolicyProductInfoPojo productInfoPojo = new SaleFinancePolicyProductInfoPojo(policyInfoPojo.getId(),
                policyInfoPojo.getProductName(),
                policyInfoPojo.getCreateUserId());
        saleFinancePolicyProductInfoMapper.addSaleFinancePolicyProductInfo(productInfoPojo);

        return ResultResponse.successMsg("政策添加成功",null);
    }



    /**
     *
     * @description: 政策返点比例查询
     *
     * @param
     * @return: com.ruixuan.common.core.domain.ResultResponse
     * @author: zianY
     */
    @Override
    public ResultResponse selectFinacePolicyRebateInfo() {
        SaleFinancePolicyRebateInfoPojo rebateInfoPojo = new SaleFinancePolicyRebateInfoPojo();
        rebateInfoPojo = saleFinancePolicyRebateInfoMapper.selectFinacePolicyRebateInfo();
        if (Check.isNull(rebateInfoPojo)){
            rebateInfoPojo.setOperationTime(new Date());
            rebateInfoPojo.setQuarter(DateUtils.getQuarter(new Date()));
            rebateInfoPojo.setRebateRate(0.00);
        }
        return ResultResponse.successMsg("政策返点比例查询成功",rebateInfoPojo);
    }


    /**
     *
     * @description: 新增政策的返点比例
     *
     * @param policyRebateInfoPojo
     * @return: com.ruixuan.common.core.domain.ResultResponse
     * @author: zianY
     */
    @Override
    public ResultResponse addSaleFinancePolicyRebateInfo(SaleFinancePolicyRebateInfoPojo policyRebateInfoPojo) {
        saleFinancePolicyRebateInfoMapper.addSaleFinancePolicyRebateInfo(policyRebateInfoPojo);
        return ResultResponse.successMsg("政策返点比例添加成功",null);
    }

    /**
     *
     * @description: 政策审核
     *
     * @param policyApprovalVo
     * @return: com.ruixuan.common.core.domain.ResultResponse
     * @author: zianY
     */
    @Override
    public ResultResponse policyApproval(PolicyApprovalVo policyApprovalVo){

        /**
         * 审核人是否是终审 -- 老板 是：直接通过或拒绝  否：走审核流程
         * 审核是否通过  1-通过 2-拒绝
         * 政策状态 0:草稿 1：待审核 2:审核中 3：审核通过4：审核拒绝
         * 通过 - 是否有下一个审核人               无  则 符合条件的转审老板                                    或 结束
         *                               转审条件：1：账期不为0  2：类型为 预付 且 返点大于设定的值
         * 拒绝 -  流程返回创建人
         *
         */

        // 审核人是终审 -- 老板
        if (StringUtils.equals(policyApprovalVo.getCreateUserId()+"",SaleFinancePolicyInfoPojo.POLICY_APPROVAL_USER)){
            log.info("---当前审核人是老板---");
            //通过
            if (policyApprovalVo.getApprovalStatus() == 1){
                //政策修改下一步审核人和 政策状态 0:草稿 1：待审核 2:审核中 3：审核通过 4：审核拒绝
                saleFinancePolicyInfoMapper.updatePolicyStatus(policyApprovalVo.getPolicyId(),policyApprovalVo.getCreateUserId()+"",3);
                log.info("老板审核---通过---政策id-{}-------政策状态---{}",policyApprovalVo.getPolicyId(),3);
            }
            //拒绝
             if (policyApprovalVo.getApprovalStatus() == 2){
                 //查询所有审核人
                 List<JSONObject> approvalUserList = saleFinancePolicyInfoMapper.selectPolicyApprovalUser();
                 //下一步审核人
                 String nextApprovalUser = approvalUserList.get(1).getString("approval_user_id");
                 //政策修改下一步审核人和状态
                 saleFinancePolicyInfoMapper.updatePolicyStatus(policyApprovalVo.getPolicyId(),nextApprovalUser,4);
                 log.info("老板审核---拒绝---政策id-{}-------政策状态---{}---下一步审核人-----{}",policyApprovalVo.getPolicyId(),4,nextApprovalUser);
            }
            //保存审核意见
            SaleFinancePolicyApprovalLogPojo approvalLogPojo = new SaleFinancePolicyApprovalLogPojo(
                    policyApprovalVo.getPolicyId(),
                    policyApprovalVo.getApprovalStatus(),
                    policyApprovalVo.getApprovalContent(),
                    policyApprovalVo.getCreateUserId()
            );
            saleFinancePolicyApprovalLogMapper.addSaleFinancePolicyApprovalLog(approvalLogPojo);
            log.info("老板审核保存意见------->>>",approvalLogPojo);
            return ResultResponse.successMsg("终审成功。", null);
        }


        if (policyApprovalVo.getApprovalStatus() == 1){
            log.info("审核---通过---政策id-{}----审核人-{}---",policyApprovalVo.getPolicyId(),policyApprovalVo.getCreateUserId());
            //通过当前审核人 查询 下一级审核人信息
            JSONObject nextApprovalUser = saleFinancePolicyInfoMapper.selectNextApprovalUser(policyApprovalVo.getCreateUserId()+"");
            if (Check.isNull(nextApprovalUser)){
                //符合条件则自动转审 否-结束政策
                //政策详情
                SaleFinancePolicyInfoPojo policyInfoPojo = saleFinancePolicyInfoMapper.selectPolicyInfoById(String.valueOf(policyApprovalVo.getPolicyId()));
                //返点比例
                SaleFinancePolicyRebateInfoPojo rebateInfoPojo = saleFinancePolicyRebateInfoMapper.selectFinacePolicyRebateInfo();
                // 账期 > 0 ||  （预付 && 政策返点比例 > 配置的返点比例）
                if(Integer.valueOf(policyInfoPojo.getAccountingPeriod()) > 0
                        || (policyInfoPojo.getAdvancePay() == 1 && Check.isNotNull(rebateInfoPojo) && policyInfoPojo.getRebateRate().doubleValue() > rebateInfoPojo.getRebateRate())){
                    //自动转审
                    //政策修改下一步审核人和状态
                    //政策状态 0:草稿 1：待审核 2:审核中 3：审核通过4：审核拒绝
                    saleFinancePolicyInfoMapper.updatePolicyStatus(policyApprovalVo.getPolicyId(),SaleFinancePolicyInfoPojo.POLICY_APPROVAL_USER,2);
                    log.info("审核---通过---政策id-{}------自动转审给了老板---账期：{}--预付：{}----政策返点比例：{}---配置的最新比例：{}", policyApprovalVo.getPolicyId(),policyInfoPojo.getAccountingPeriod(),policyInfoPojo.getAdvancePay(),policyInfoPojo.getRebateRate(),rebateInfoPojo.getRebateRate());
                    //保存审核意见
                    SaleFinancePolicyApprovalLogPojo approvalLogPojo = new SaleFinancePolicyApprovalLogPojo(
                            policyApprovalVo.getPolicyId(),
                            4,
                            policyApprovalVo.getApprovalContent(),
                            policyApprovalVo.getCreateUserId()
                    );
                    saleFinancePolicyApprovalLogMapper.addSaleFinancePolicyApprovalLog(approvalLogPojo);
                    log.info("保存意见------政策自动转审->>>",approvalLogPojo);
                    return ResultResponse.successMsg("政策审核成功-自动转审。",null);
                }else {
                    saleFinancePolicyInfoMapper.updatePolicyStatus(policyApprovalVo.getPolicyId(),policyApprovalVo.getCreateUserId()+"",3);
                    log.info("审核---通过---政策id-{}----政策状态-{}---审核结束---",policyApprovalVo.getPolicyId(),3);
                }
            }else {
                //政策修改下一步审核人和状态
                saleFinancePolicyInfoMapper.updatePolicyStatus(policyApprovalVo.getPolicyId(),nextApprovalUser.getString("approval_user_id"),2);
                log.info("审核---通过---政策id-{}----政策状态-{}---设置下一步审核人---{}---",policyApprovalVo.getPolicyId(),2,nextApprovalUser);
            }

        }


        //拒绝
        if (policyApprovalVo.getApprovalStatus() == 2){
            //查询所有审核人
            List<JSONObject> approvalUserList = saleFinancePolicyInfoMapper.selectPolicyApprovalUser();
            //下一步审核人
            String nextApprovalUser = approvalUserList.get(1).getString("approval_user_id");
            //政策修改下一步审核人和状态
            saleFinancePolicyInfoMapper.updatePolicyStatus(policyApprovalVo.getPolicyId(),nextApprovalUser,4);
            log.info("审核---拒绝---政策id-{}----政策状态-{}---设置下一步审核人---{}---",policyApprovalVo.getPolicyId(),4,nextApprovalUser);
            return ResultResponse.successMsg("政策审核拒绝。",null);
        }

        //保存审核意见
        SaleFinancePolicyApprovalLogPojo approvalLogPojo = new SaleFinancePolicyApprovalLogPojo(
                policyApprovalVo.getPolicyId(),
                policyApprovalVo.getApprovalStatus(),
                policyApprovalVo.getApprovalContent(),
                policyApprovalVo.getCreateUserId()
        );
        saleFinancePolicyApprovalLogMapper.addSaleFinancePolicyApprovalLog(approvalLogPojo);
        log.info("保存意见------->>>",approvalLogPojo);
        return ResultResponse.successMsg("政策审核成功。",null);
    }

    /**
     *
     * @description: 手动转审
     *
     * @param policyApprovalVo
     * @return: com.ruixuan.common.core.domain.ResultResponse
     * @author: zianY
     */
    @Override
    public ResultResponse policyApprovalManual(PolicyApprovalVo policyApprovalVo) {
        //政策修改下一步审核人和状态
        //政策状态 0:草稿 1：待审核 2:审核中 3：审核通过4：审核拒绝
        saleFinancePolicyInfoMapper.updatePolicyStatus(policyApprovalVo.getPolicyId(),SaleFinancePolicyInfoPojo.POLICY_APPROVAL_USER,2);
        log.info("政策手动转审---政策id-{}------手动转审给了老板---", policyApprovalVo.getPolicyId());
        //保存审核意见
        SaleFinancePolicyApprovalLogPojo approvalLogPojo = new SaleFinancePolicyApprovalLogPojo(
                policyApprovalVo.getPolicyId(),
                policyApprovalVo.getApprovalStatus(),
                policyApprovalVo.getApprovalContent(),
                policyApprovalVo.getCreateUserId()
        );
        saleFinancePolicyApprovalLogMapper.addSaleFinancePolicyApprovalLog(approvalLogPojo);
        return ResultResponse.successMsg("政策手动转审成功。",null);
    }

    /**
     *
     * @description:查询快手账户以及公司和资质
     *
     * @param
     * @return: com.ruixuan.common.core.domain.ResultResponse
     * @author: zianY
     */
    @Override
    public ResultResponse selectPolicyCustomerList() {
        return ResultResponse.successMsg("查询所有客户广告主名称成功。",saleFinancePolicyInfoMapper.selectPolicyCustomerList());
    }

    /**
     *
     * @description:查询公司主体列表
     *
     * @param
     * @return: com.ruixuan.common.core.domain.ResultResponse
     * @author: zianY
     */
    @Override
    public ResultResponse selectCompanySubjectInfoList() {
        return ResultResponse.successMsg("查询公司主体列表成功。",saleFinancePolicyInfoMapper.selectCompanySubjectInfoList());
    }


}
