package com.unis.enterpriseCreditManagement.info.modular.ecmCreditData.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.unis.common.enums.CommonSortOrderEnum;
import com.unis.common.exception.CommonException;
import com.unis.common.page.CommonPageRequest;
import com.unis.common.pojo.CommonValidList;
import com.unis.enterpriseCreditManagement.info.modular.ecmCreditAssess.mapper.EcmCreditAssessMapper;
import com.unis.enterpriseCreditManagement.info.modular.ecmCreditData.entity.EcmCreditData;
import com.unis.enterpriseCreditManagement.info.modular.ecmCreditData.entity.vo.EcmCreditDataVo;
import com.unis.enterpriseCreditManagement.info.modular.ecmCreditData.enums.EcmCreditDataEnum;
import com.unis.enterpriseCreditManagement.info.modular.ecmCreditData.mapper.EcmCreditDataMapper;

import com.unis.enterpriseCreditManagement.info.modular.ecmCreditData.service.EcmCreditDataService;
import com.unis.policy.info.modular.alPolicyFileReport.entity.AlPolicyFileReport;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

import com.unis.enterpriseCreditManagement.info.modular.ecmCreditData.param.EcmCreditDataAddParam;
import com.unis.enterpriseCreditManagement.info.modular.ecmCreditData.param.EcmCreditDataEditParam;
import com.unis.enterpriseCreditManagement.info.modular.ecmCreditData.param.EcmCreditDataIdParam;
import com.unis.enterpriseCreditManagement.info.modular.ecmCreditData.param.EcmCreditDataPageParam;
import com.unis.enterpriseCreditManagement.info.modular.ecmCreditData.param.EcmCreditDataShareParam;

/**
 * 企业信用管理-信用数据管理表Service接口实现类
 *
 * @author TS
 * @date  2024/05/17 17:35
 **/
@Service
public class EcmCreditDataServiceImpl extends ServiceImpl<EcmCreditDataMapper, EcmCreditData> implements EcmCreditDataService {
    @Resource
    private   EcmCreditDataMapper ecmCreditDataMapper;
    @Resource
    private EcmCreditAssessMapper ecmCreditAssessMapper;

    @Override
    public Page<EcmCreditData> page(EcmCreditDataPageParam ecmCreditDataPageParam) {
        QueryWrapper<EcmCreditData> queryWrapper = new QueryWrapper<>();
        if(ObjectUtil.isAllNotEmpty(ecmCreditDataPageParam.getSortField(), ecmCreditDataPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(ecmCreditDataPageParam.getSortOrder());
            queryWrapper.orderBy(true, ecmCreditDataPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(ecmCreditDataPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(EcmCreditData::getId);
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(EcmCreditDataAddParam ecmCreditDataAddParam) {
        EcmCreditData ecmCreditData = BeanUtil.toBean(ecmCreditDataAddParam, EcmCreditData.class);
        this.save(ecmCreditData);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(EcmCreditDataEditParam ecmCreditDataEditParam) {
        EcmCreditData ecmCreditData = this.queryEntity(ecmCreditDataEditParam.getId());
        BeanUtil.copyProperties(ecmCreditDataEditParam, ecmCreditData);
        this.updateById(ecmCreditData);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<EcmCreditDataIdParam> ecmCreditDataIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(ecmCreditDataIdParamList, EcmCreditDataIdParam::getId));
    }

    @Override
    public EcmCreditDataVo detail(EcmCreditDataIdParam ecmCreditDataIdParam) {
        return ecmCreditDataMapper.detail(ecmCreditDataIdParam.getId());
    }

    @Override
    public EcmCreditData queryEntity(String id) {
        EcmCreditData ecmCreditData = this.getById(id);
        if(ObjectUtil.isEmpty(ecmCreditData)) {
            throw new CommonException("企业信用管理-信用数据管理表不存在，id值为：{}", id);
        }
        return ecmCreditData;
    }

    /**
     * 获取企业信用管理-信用数据管理表自定义分页
     *
     * @param pageParam
     * @return
     */
    @Override
    public IPage<EcmCreditDataVo> findPage(EcmCreditDataPageParam pageParam) {
            //条形查询器
            QueryWrapper<AlPolicyFileReport> queryWrapper = new QueryWrapper<>();
            //分页相关
            if(pageParam.getIsEntAppQuery() != null && pageParam.getIsEntAppQuery() == 1){
                queryWrapper.ne("  ifnull(a.assess_result_depict,'')  ","''" );
            }
            if(StringUtils.isNotBlank(pageParam.getUnitName())){
                queryWrapper.like("dwmc",pageParam.getUnitName() );
            }
            if(StringUtils.isNotBlank(pageParam.getFddbr())){
                queryWrapper.like("fddbr",pageParam.getFddbr() );
            }
            if(pageParam.getCreditLevel() != null){
                queryWrapper.eq("credit_level",pageParam.getCreditLevel() );
            }
            Page<EcmCreditDataVo> p =new Page<>(pageParam.getCurrent(),pageParam.getSize());
            IPage<EcmCreditDataVo> page = ecmCreditDataMapper.selectMyMapsPage(p,queryWrapper);
            return page;
    }

    /**
     * 获取未添加企业信用管理下拉列表
     *
     * @return
     */
    @Override
    public List<EcmCreditDataVo> getUnitList() {
        return ecmCreditDataMapper.getUnitList();
    }

    /**
     * 批量共享
     *
     * @param creditDataShareParamList
     */
    @Override
    public void shares(CommonValidList<EcmCreditDataShareParam> creditDataShareParamList) {
        for (int i = 0; i < creditDataShareParamList.size(); i++) {
            EcmCreditDataShareParam dataShareParam = creditDataShareParamList.get(i);
            EcmCreditData ecmCreditData = this.queryEntity(dataShareParam.getId());
            BeanUtil.copyProperties(dataShareParam, ecmCreditData);
            this.updateById(ecmCreditData);
        }
    }

    /**
     * 定时通过信用评价生成对信用数据的评价
     */
    @Override
    public void taskAction() {
        QueryWrapper<EcmCreditData> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().isNull(EcmCreditData::getAssessResult).isNull(EcmCreditData::getAssessResultDepict);
        List<EcmCreditData> list = this.list(queryWrapper);
        for (int i = 0; i < list.size(); i++) {
            EcmCreditData ecmCreditData = list.get(i);
           Map<String,Object> map = ecmCreditAssessMapper.getEcmCreditAssessByData(
                   ecmCreditData.getCreditScore(),
                   ecmCreditData.getCreditLevel(),
                   ecmCreditData.getFulfilmentTimes(),
                   ecmCreditData.getBreachTimes()
           );

           if (map != null){
               Integer  assessResult = Integer.parseInt(map.getOrDefault("assessResult","0").toString());
               if (assessResult > 0){
                   ecmCreditData.setAssessResult(assessResult);
                   //写评价结果描述，分析结果
                   if (assessResult == 1)
                       ecmCreditData.setAssessResultDepict(EcmCreditDataEnum.ONE.getValue());
                   if (assessResult == 2)
                       ecmCreditData.setAssessResultDepict(EcmCreditDataEnum.TWO.getValue());
                   if (assessResult == 3)
                       ecmCreditData.setAssessResultDepict(EcmCreditDataEnum.THREE.getValue());

                   this.updateById(ecmCreditData);
               }

           }
        }
    }
}
