package com.github.wxiaoqi.security.admin.biz;


import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.wxiaoqi.security.admin.dto.CompanyApplyFindDTO;
import com.github.wxiaoqi.security.admin.entity.*;
import com.github.wxiaoqi.security.admin.mapper.CompanyInfoApplyMapper;
import com.github.wxiaoqi.security.admin.vo.CompanyApplyVo;
import com.github.wxiaoqi.security.admin.vo.CompanyInfoVo;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.exception.BaseException;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.util.BeanUtils;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.github.wxiaoqi.security.common.vo.PageDataVO;
import com.xxfc.platform.app.entity.Cofig;
import com.xxfc.platform.app.feign.ConfigFeign;
import com.xxfc.platform.universal.dto.SmsTemplateDTO;
import com.xxfc.platform.universal.feign.ThirdFeign;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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


@Service
@Slf4j
public class CompanyInfoApplyBiz extends BaseBiz<CompanyInfoApplyMapper, CompanyInfoApply>{

    @Autowired
    CompanyInfoBiz companyInfoBiz;

    @Autowired
    ConfigFeign  configFeign;


    @Autowired
    CompanyInfoOrderBiz companyInfoOrderBiz;

    @Autowired
    ThirdFeign thirdFeign;

    @Autowired
    AppUserLoginBiz appUserLoginBiz;


    @Transactional(rollbackFor = Exception.class)
    public  CompanyInfoApply  saveApply(CompanyInfo companyInfo){
        if (companyInfo == null || StringUtils.isBlank(companyInfo.getName())){
             throw  new BaseException("参数不能为空",ResultCode.FAILED_CODE);
        }
        Long id = companyInfo.getId() == null ? 0L : companyInfo.getId();
        List<CompanyInfo> list=companyInfoBiz.getListByExample(id,companyInfo.getName());
        if (list.size() > 0){
            throw  new BaseException("公司名称不能重复",ResultCode.FAILED_CODE);
        }

        BigDecimal platformAmount=BigDecimal.ZERO;
        BigDecimal margin=BigDecimal.ZERO;
        CompanyInfo companyInfo1=null;
        Integer formType=2;
        if (id > 0){
            if (checkStatus(id) > 0L){
                throw  new BaseException("已存在待审核记录",ResultCode.FAILED_CODE);
            }
            companyInfo1=companyInfoBiz.selectById(id);
            BeanUtils.copyPropertiesTargetIsEquals(companyInfo1,companyInfo);
        }else {
            if (checkApplyStatus(companyInfo.getAppUserId()) > 0L ){
                throw  new BaseException("已存在待审核记录",ResultCode.FAILED_CODE);
            }
            JSONObject jsonObject=getApplyOrder();
            if (jsonObject != null && jsonObject.getInteger("isPay") == 1){
                platformAmount=jsonObject.getBigDecimal("platformAmount") == null ? BigDecimal.ZERO :jsonObject.getBigDecimal("platformAmount")  ;
                margin=jsonObject.getBigDecimal("margin") == null ? BigDecimal.ZERO :jsonObject.getBigDecimal("margin")  ;
            }
            formType=1;
        }
        String detailJson= JSONObject.toJSONString(companyInfo);
        if (companyInfo1 != null){
            BeanUtils.copyPropertiesTargetIsNull(companyInfo1,companyInfo);
        }
        CompanyInfoApply companyInfoApply=new CompanyInfoApply();
        BeanUtils.copyProperties(companyInfo,companyInfoApply);
        companyInfoApply.setDetailJson(detailJson);
        BigDecimal payAmount=platformAmount.add(margin);
        companyInfoApply.setPayAmount(payAmount);
        companyInfoApply.setBranchId(id);
        companyInfoApply.setFormType(formType);
        companyInfoApply.setId(null);
        insertSelective(companyInfoApply);
        Long branchApplyId=companyInfoApply.getId();
        if (id == 0L  && branchApplyId  > 0L){
            CompanyInfoOrder companyInfoOrder=new CompanyInfoOrder();
            companyInfoOrder.setBranchApplyId(branchApplyId);
            companyInfoOrder.setRealAmount(platformAmount);
            companyInfoOrder.setOrderType(1);
            companyInfoOrderBiz.saveOrder(companyInfoOrder);
            CompanyInfoOrder companyInfoOrder1=new CompanyInfoOrder();
            companyInfoOrder1.setBranchApplyId(branchApplyId);
            companyInfoOrder1.setRealAmount(margin);
            companyInfoOrder1.setOrderType(2);
            companyInfoOrderBiz.saveOrder(companyInfoOrder1);
        }

        return  companyInfoApply;
    }



    public Long checkStatus(Long branchId){
        CompanyInfoApply companyInfoApply=new CompanyInfoApply();
        companyInfoApply.setBranchId(branchId);
        companyInfoApply.setStatus(0);
        return  selectCount(companyInfoApply);
    }

    public Long checkApplyStatus(Integer appUserId){
        CompanyInfoApply companyInfoApply=new CompanyInfoApply();
        companyInfoApply.setAppUserId(appUserId);
        companyInfoApply.setStatus(0);
        companyInfoApply.setFormType(1);
        return  selectCount(companyInfoApply);
    }

    //入驻规则管理
    public JSONObject getApplyOrder(){
        try {
            List<Cofig> list=configFeign.getAllByType(ConfigFeign.TYPE_COMPANY_APPLY+"").getData();
            if (list!=null && list.size()>0){
                String params=list.get(0).getParams();
                JSONObject object = JSONObject.parseObject(params);
                return  object;
            }
        }catch (Exception e){
            log.error(e.getMessage(), e);;
        }
        return  null;
    }



    public List<CompanyApplyVo> getList(CompanyApplyFindDTO companyApplyFindDTO){
        return  mapper.selectList(companyApplyFindDTO);
    }

    public ObjectRestResponse selectList(CompanyApplyFindDTO companyApplyFindDTO){
        PageHelper.startPage(companyApplyFindDTO.getPage(), companyApplyFindDTO.getLimit());
        PageInfo<CompanyApplyVo> pageInfo = new PageInfo<>(getList(companyApplyFindDTO));
        return ObjectRestResponse.succ(PageDataVO.pageInfo(pageInfo));
    }


    public CompanyInfoVo  getApplyInfo(Long id){
        CompanyInfoApply companyInfoApply = selectById(id);
        if (companyInfoApply == null ){
            throw  new BaseException("申请记录不存在",ResultCode.FAILED_CODE);
        }
        Long branchId = companyInfoApply.getBranchId() == null ? 0L : companyInfoApply.getBranchId();
        CompanyInfoVo companyInfoVo=new CompanyInfoVo();
        if (branchId != null  && companyInfoApply.getFormType() == 2 ){
            CompanyInfo companyInfo=companyInfoBiz.selectById(branchId);
            if (companyInfo != null ){
                BeanUtils.copyProperties(companyInfo,companyInfoVo);
            }
         }
        companyInfoVo.setCompanyInfoApply(companyInfoApply);
        companyInfoVo.setCompanyInfoOrderList(companyInfoOrderBiz.getList(id));
        return  companyInfoVo;
    }

    @Transactional(rollbackFor = Exception.class)
    public  void  audit(CompanyInfoApply companyInfoApply) {
        Integer status=companyInfoApply.getStatus();
        if (status == 2 && StringUtils.isBlank(companyInfoApply.getReason())){
            throw  new BaseException("驳回原因不能为空",ResultCode.FAILED_CODE);
        }
        updateSelectiveById(companyInfoApply);
        if (status == 1){
            companyInfoApply=selectById(companyInfoApply.getId());
            if (companyInfoApply == null ){
                throw  new BaseException("申请记录不存在",ResultCode.FAILED_CODE);
            }
           Long id =companyInfoBiz.addOrUpd(companyInfoApply);
            if (id > 0L){
                CompanyInfoApply companyInfoApply1=new CompanyInfoApply();
                companyInfoApply1.setId(companyInfoApply.getId());
                companyInfoApply1.setBranchId(id);
                updateSelectiveById(companyInfoApply1);
            }
        }
        sendSms(companyInfoApply);

    }


    public void  sendSms(CompanyInfoApply companyInfoApply){
        try {
            //发送短信通知用户
            companyInfoApply=selectById(companyInfoApply.getId());
            List<String> smsParams = new ArrayList<>();
            String name = StringUtils.isBlank(companyInfoApply.getName()) ? "" : companyInfoApply.getName();
            smsParams.add(name);
            Integer userId = companyInfoApply.getAppUserId() == null ? 0 : companyInfoApply.getAppUserId();
            AppUserLogin userLogin = appUserLoginBiz.selectById(userId);
            if (userLogin == null){
                return;
            }
            Integer type=companyInfoApply.getStatus() == 1 ? SmsTemplateDTO.COMPANY_S : SmsTemplateDTO.COMPANY_F;
            thirdFeign.sendTemplate(new SmsTemplateDTO(){{
                setPhoneNumbers(userLogin.getUsername());
                setType(type);
                setParams(smsParams.toArray(new String[smsParams.size()]));
            }});
        }catch (Exception e){
            log.error(e.getMessage(), e);
            return;
        }

    }


    public CompanyInfoVo  getCompanyInfo(CompanyInfo companyInfo){
        Long branchId = companyInfo.getId() == null ? 0L : companyInfo.getId();
        CompanyInfoVo companyInfoVo=new CompanyInfoVo();
        BeanUtils.copyProperties(companyInfo,companyInfoVo);
        if (branchId != null  ){
            CompanyInfoApply companyInfoApply=mapper.getOneByOrderUpdTime(branchId);
            companyInfoVo.setCompanyInfoApply(companyInfoApply);
        }
        return  companyInfoVo;
    }

    //自动审核
    public  void authAudit(){
        List<CompanyInfoApply> list = mapper.getListByDay();
        if (list != null && list.size() > 0 ){
            for (CompanyInfoApply companyInfoApply : list){
                CompanyInfoApply companyInfoApply1 = new CompanyInfoApply();
                companyInfoApply1.setStatus(1);
                companyInfoApply1.setId(companyInfoApply.getId());
                try {
                    log.info("-----自动审核---id=="+companyInfoApply1.getId());
                    audit(companyInfoApply1);
                }catch (Exception e){
                    log.error(e.getMessage(),e);
                    companyInfoApply1.setStatus(2);
                    JSONObject reson = new JSONObject();
                    reson.put("content",e.getMessage());
                    companyInfoApply1.setReason(reson.toJSONString());
                    audit(companyInfoApply1);
                    continue;
                }
            }
        }
    }










}
