package com.chushang.loan.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chushang.common.core.constant.SecurityConstants;
import com.chushang.common.core.web.AjaxResult;
import com.chushang.common.core.web.Result;
import com.chushang.common.mybatis.page.CommonParam;
import com.chushang.common.mybatis.utils.PageResult;
import com.chushang.common.mybatis.utils.WrapperUtils;
import com.chushang.datascope.annotation.DataScope;
import com.chushang.loan.domin.dto.LoanApproval;
import com.chushang.loan.domin.dto.LoanFormData;
import com.chushang.loan.domin.entity.LoanAduitEntity;
import com.chushang.loan.domin.entity.LoanEntity;
import com.chushang.loan.domin.query.LoanFormQuery;
import com.chushang.loan.domin.vo.LoanData;
import com.chushang.loan.domin.vo.LoanVO;
import com.chushang.loan.service.ILoanService;
import com.chushang.loan.mapper.LoanMapper;
import com.chushang.oss.feign.RemoteOssService;
import com.chushang.security.entity.po.SysUser;
import com.chushang.security.utils.SecurityUtils;
import com.chushang.loan.service.ILoanAduitService;
import com.chushang.system.entity.dto.UserQcCodeDTO;
import com.chushang.system.entity.po.SysUserQcCode;
import com.chushang.system.feign.RemoteUserQcCodeService;
import com.chushang.system.feign.RemoteUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Slf4j
@Service
public class LoanServiceImpl extends ServiceImpl<LoanMapper, LoanEntity> implements ILoanService {


    @Autowired
    ILoanAduitService iLoanAduitService;


    @Autowired
    RemoteUserQcCodeService remoteUserQcCodeService;


    @Autowired
    private RemoteOssService remoteOssService;


    @Autowired
    RemoteUserService remoteUserService;


    @Override
    public void submitFormData(LoanFormData formData) {
        // 通过用户id查询用户id
        LoanEntity loan = new LoanEntity();
        BeanUtil.copyProperties(formData,loan);
        Result<SysUser> infoById = remoteUserService.getInfoById(formData.getUserId(), SecurityConstants.INNER);
        if(infoById.getCode() == 200 && !Objects.isNull(infoById.getData())){
            SysUser data = infoById.getData();
            loan.setDeptId(data.getDeptId());
        }
        baseMapper.insert(BeanUtil.copyProperties(formData,LoanEntity.class));
    }

    @Override
    public String qcCode(LoanFormQuery formData) throws Exception{
        String codeUrl = "";
        Result<SysUserQcCode> userInfo = remoteUserQcCodeService.getUserInfo(new UserQcCodeDTO() {{
            setUserId(SecurityUtils.getUserId());
        }});
        if(userInfo.isSuccess()){
            codeUrl = userInfo.getData().getLoanCode();
        }else{

            Result<String> stringResult = remoteOssService.uploadQcCode(SecurityConstants.INNER);
            if(stringResult.isSuccess()){
                codeUrl = stringResult.getData();
                remoteUserQcCodeService.save(new UserQcCodeDTO() {{
                    setUrl(stringResult.getData());
                    setUserId(SecurityUtils.getUserId());
                }});
            }

        }
        return codeUrl;
    }


    @Override
    @DataScope
    public PageResult queryLoan(LoanEntity query) {
        CommonParam commonParam = CommonParam.buildPageRequest();
        LambdaQueryWrapper<LoanEntity> queryWrapper = WrapperUtils.builder(query, commonParam);
        Page<LoanEntity> page = this.page(
                new Page<>(commonParam.getPage(), commonParam.getLimit()),
                queryWrapper
        );
        return new PageResult(page);
    }

    @Override
    @DataScope(deptAlias = "l")
    public PageResult queryData(LoanEntity query) {
        CommonParam commonParam = CommonParam.buildPageRequest();
        Page<LoanEntity> page = new Page<>(commonParam.getPage(),commonParam.getLimit());
        List<LoanData> loanVOSList = baseMapper.queryDataList(query,page);
        List<LoanVO> resultList = new ArrayList<>();
        for (LoanData loanData:loanVOSList){
            LoanVO loanVO  = new LoanVO();
            BeanUtils.copyProperties(loanData,loanVO);
            loanVO.setTotalTransactionAmount(String.valueOf(loanData.getTotalTransactionAmount()));
            loanVO.setTotalLoanAmount(String.valueOf(loanData.getTotalLoanAmount()));
            resultList.add(loanVO);
        }
        return new PageResult(
                resultList,
                page.getTotal(),
                page.getPages(),
                page.getCurrent());
    }



    @Override
    @Transactional
    public int approval(LoanApproval approval) {
        boolean flag = false;
        if (approval.getStatus().equals(3) && StrUtil.isEmpty(approval.getDenialReason())) {
            Assert.isTrue(false, "审批拒绝请注明原因");
        } else if (approval.getStatus() == 2 && approval.getLoanAmount() == null) {
            Assert.isTrue(false, "审批通过请填写通过额度");
        }
        LoanEntity loan = baseMapper.selectById(approval.getId());
        Assert.isTrue(loan != null && loan.getStatus() == 1, "表单不存在或已经审批过");
        loan.setDenialReason(approval.getDenialReason());
        loan.setStatus(approval.getStatus());
        loan.setLoanAmount(approval.getLoanAmount());


        LoanAduitEntity loanAduitEntity = new LoanAduitEntity();
        loanAduitEntity.setStatus(approval.getStatus());
        loanAduitEntity.setLoadId(loan.getId());
        loanAduitEntity.setApproverId(SecurityUtils.getUserId());
        loanAduitEntity.setApproverName(SecurityUtils.getUsername());
        loanAduitEntity.setDenialReason(approval.getDenialReason());
        iLoanAduitService.insertAduit(loanAduitEntity);
        return baseMapper.updateById(loan);
    }
}


