package com.ozs.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
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.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ozs.base.domain.BaseExpert;
import com.ozs.base.domain.BaseUnitInformation;
import com.ozs.base.domain.vo.BaseExpertVo;
import com.ozs.base.mapper.BaseExpertMapper;
import com.ozs.base.service.BaseExpertService;
import com.ozs.common.core.domain.AjaxResult;
import com.ozs.common.enums.*;
import com.ozs.common.utils.StringUtils;
import com.ozs.common.utils.bean.BeanUtils;
import com.ozs.plan.doman.PlanQuarter;
import com.ozs.plan.doman.ProvisionalPlan;
import com.ozs.pm.doman.PmDemand;
import com.ozs.pm.doman.PmDemandExpertRef;
import com.ozs.pm.doman.vo.responseVo.PmDemandResVo;
import com.ozs.pm.service.IPmDemandService;
import com.ozs.pm.service.PmDemandExpertRefService;
import com.ozs.system.domain.vo.responseVo.SysDeptResponseVo;
import com.ozs.system.service.ISysDeptService;
import com.ozs.system.service.ISysDictDataService;
import com.ozs.system.service.ISysDictTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class BaseExpertServiceImpl extends ServiceImpl<BaseExpertMapper, BaseExpert> implements BaseExpertService {

    @Autowired
    private BaseExpertMapper baseExpertMapper;
    @Autowired
    private PmDemandExpertRefService pmDemandExpertRefService;
    @Autowired
    private IPmDemandService pmDemandService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private ISysDictDataService dictDataService;
    @Autowired
    private ISysDictTypeService dictTypeService;

    @Override
    public int insertExpert(BaseExpertVo baseExpertVo) {
        // base_unit_information 单位信息表
        if (StringUtils.isNotNull(baseExpertVo.getUnitInformation())) {
            List<BaseUnitInformation> baseUnitInformationList = baseExpertMapper.selectByUnitInformation(baseExpertVo.getUnitInformation());
            if (baseUnitInformationList.size() <= 0) {
                BaseUnitInformation baseUnitInformation = new BaseUnitInformation();
                baseUnitInformation.setUnitName(baseExpertVo.getUnitInformation());
                baseUnitInformation.setCreated(baseExpertVo.getExpertName());
                baseUnitInformation.setCreateTime(new Date());
                Integer i = baseExpertMapper.insertBaseUnitInformation(baseUnitInformation);
            }
        }
        // 区域list转字符串
        if (StringUtils.isNotNull(baseExpertVo.getLocalAreaList())) {
//            String stringFromList = String.join(",", baseExpertVo.getLocalAreaList());
            baseExpertVo.setLocalArea(baseExpertVo.getLocalAreaList().get(baseExpertVo.getLocalAreaList().size() - 1));
        }
        return baseExpertMapper.insertExpert(baseExpertVo);
    }

    @Override
    public int updateSupplierType(BaseExpert baseExpert) {
        LambdaUpdateWrapper<BaseExpert> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        //eq是指你查询的条件，set是指你修改的值
        lambdaUpdateWrapper
                .eq(BaseExpert::getId, baseExpert.getId())
                .set(BaseExpert::getStatus, baseExpert.getStatus());
        return baseExpertMapper.update(null, lambdaUpdateWrapper);
    }

    @Override
    public AjaxResult selectReviewProject(BaseExpertVo baseExpertVo) {
        // 通过专家ID查询 与专家库关联的采购执行管理ID
        List<Integer> demandIdList = pmDemandExpertRefService.selectByExpertId(baseExpertVo.getId());
        if (ObjectUtils.isEmpty(demandIdList)) {
            return AjaxResult.success(new PageInfo<>(demandIdList));
        }
        List<PmDemand> pmDemandList = pmDemandService.selectByDemandIdList(demandIdList);
        List<PmDemandResVo> pmDemandResponseVoList = changTo(pmDemandList);
        PageHelper.startPage(baseExpertVo.getPageNum().intValue(), baseExpertVo.getPageSize().intValue());
        PageInfo<PmDemandResVo> pageInfo = new PageInfo<>(pmDemandResponseVoList);
        return AjaxResult.success(pageInfo);
    }

    @Override
    public AjaxResult selectExtractionExpert(BaseExpertVo baseExpertVo) {
        // 查询抽取过专家的项目列表
        List<PmDemand> pmDemandList = pmDemandService.selectExtractionExpert(baseExpertVo);
        List<PmDemandResVo> pmDemandResponseVoList = changTo(pmDemandList);
        // 遍历项目 查询专家姓名
        if (!ObjectUtils.isEmpty(pmDemandResponseVoList) && pmDemandResponseVoList.size() > 0) {
            for (PmDemandResVo pmDemandResVo : pmDemandResponseVoList) {
                Long demandId = pmDemandResVo.getDemandId();
                // 查询项目专家关联表 专家ID，关联时间
                List<PmDemandExpertRef> pmDemandExpertRefList = baseExpertMapper.getExpertIdList(demandId);
                // 专家ID列表
                List<Long> expertList = pmDemandExpertRefList.stream().map(PmDemandExpertRef::getExpertId).collect(Collectors.toList());
                // 获取抽取时间（列表中取其中一个时间）
                Date accessTime = pmDemandExpertRefList.get(0).getAccessTime();
                Map<String, String> map = baseExpertMapper.getExpertNameList(expertList);
                if (!ObjectUtils.isEmpty(map)) {
                    // 专家名称
                    String expertNameStr = map.get("expertName");
                    // 采购品种
                    String varietyPurchaseStr = map.get("varietyPurchase");
                    List<String> list = Arrays.stream(varietyPurchaseStr.split(",")).map(s -> String.valueOf(s.trim())).collect(Collectors.toList());
                    List<String> newList = method(list);
                    // 查询采购品种 中文
                    String varietyPurchaseName = "";
                    for (String i : newList) {
                        String name = PurchaseType.getCodeToInfo(i);
                        if ("".equals(varietyPurchaseName)) {
                            varietyPurchaseName = name;
                        } else {
                            varietyPurchaseName = "," + name;
                        }
                    }
                    pmDemandResVo.setExpertNameStr(expertNameStr);
                    pmDemandResVo.setVarietyPurchaseStr(varietyPurchaseName);
                }
                pmDemandResVo.setAccessTime(accessTime);
            }
        }
        PageHelper.startPage(baseExpertVo.getPageNum().intValue(), baseExpertVo.getPageSize().intValue());
        PageInfo<PmDemandResVo> pageInfo = new PageInfo<>(pmDemandResponseVoList);
        return AjaxResult.success(pageInfo);
    }

    /**
     * 自定义去重
     *
     * @param list
     */
    public static List<String> method(List<String> list) {
        // 新集合
        List<String> newList = new ArrayList<>(list.size());
        list.forEach(i -> {
            // 如果新集合中不存在则插入
            if (!newList.contains(i)) {
                newList.add(i);
            }
        });
        return newList;
    }

    @Override
    public List<BaseUnitInformation> getBaseUnitInformationList() {
        List<BaseUnitInformation> baseUnitInformationList = baseExpertMapper.selectByUnitInformation(null);
        return baseUnitInformationList;
    }

    private List<PmDemandResVo> changTo(List<PmDemand> pmDemandList) {
        List<PmDemandResVo> pmDemandResponseVoList = new ArrayList<>();
        //获取字典数据
        HashMap<String, HashMap<String, String>> planEnums = dictTypeService.getAboutEnums();
        HashMap<String, String> projectAttributes = planEnums.get("projectAttributes");

        if (pmDemandList != null && pmDemandList.size() > 0) {
            for (PmDemand pmDemand1 : pmDemandList) {
                PmDemandResVo vo = new PmDemandResVo();
                BeanUtils.copyProperties(pmDemand1, vo);
                if (vo.getPurchaseDeptId() != null) {
                    Map<String, Object> deptMap = deptService.selectDeptById(vo.getPurchaseDeptId());
                    if (deptMap != null) {
                        SysDeptResponseVo sysDeptResponseVo = (SysDeptResponseVo) deptMap.get("sysDept");
                        if (sysDeptResponseVo != null) {
                            vo.setPurchaseDeptName(sysDeptResponseVo.getDeptName());
                        }
                    }
                }
                String purchaseServicesName = dictDataService.selectDictLabel("purchase_services", vo.getPurchaseServices());
                if (StringUtils.isNotEmpty(purchaseServicesName)) {
                    vo.setPurchaseServicesName(purchaseServicesName);
                }
                //项目类型
                for (ProjectTypes value : ProjectTypes.values()) {
                    if (vo.getProjectType() != null && vo.getProjectType().equals(value.getCode())) {
                        vo.setProjectTypeName(value.getInfo());
                        break;
                    }
                }
                //是否为超限额计划
                for (IsExcess value : IsExcess.values()) {
                    if (vo.getIsExcess() != null && vo.getIsExcess().equals(value.getCode())) {
                        vo.setIsExcessName(value.getInfo());
                        break;
                    }
                }
                //采购方式
                for (PlanPurchaseMode value : PlanPurchaseMode.values()) {
                    if (vo.getPurchaseMode() != null && vo.getPurchaseMode().equals(value.getCode())) {
                        vo.setPurchaseModeName(value.getInfo());
                        break;
                    }
                }
                //项目属性是拼接的
                if (!ObjectUtils.isEmpty(vo.getProjectAttr())) {
                    if (vo.getProjectAttr().length() > 1) {
                        StringBuilder builder = new StringBuilder();
                        String[] split = vo.getProjectAttr().split(",");
                        for (String s : split) {
                            for (Map.Entry<String, String> entry : projectAttributes.entrySet()) {
                                if (s.equals(entry.getValue())) {
                                    if (!vo.getProjectAttr().endsWith(s)) {
                                        builder.append(entry.getKey() + ",");
                                    } else {
                                        builder.append(entry.getKey());
                                    }
                                    break;
                                }
                            }
                        }
                        vo.setProjectAttrName(builder.toString());
                    } else {
                        for (Map.Entry<String, String> entry : projectAttributes.entrySet()) {
                            if (vo.getProjectAttr().equals(entry.getValue())) {
                                vo.setProjectAttrName(entry.getKey());
                                break;
                            }
                        }
                    }
                }
                //预警状态
                for (WarnStatus value : WarnStatus.values()) {
                    if (vo.getWarnStatus() != null && vo.getWarnStatus().equals(value.getCode())) {
                        vo.setWarnStatusName(value.getInfo());
                        break;
                    }
                }
                //项目状态
                for (PmProjectStatus value : PmProjectStatus.values()) {
                    if (vo.getProjectStatus() != null && vo.getProjectStatus().equals(value.getCode())) {
                        vo.setProjectStatusName(value.getInfo());
                        break;
                    }
                }
                pmDemandResponseVoList.add(vo);
            }
        }
        return pmDemandResponseVoList;
    }
}
