package com.project.zcustom.service.service.property.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.project.zcustom.controller.core.PageParamVo;
import com.project.zcustom.controller.core.StringUtils;
import com.project.zcustom.domain.property.PlatProperty;
import com.project.zcustom.domain.property.PlatPropertyList;
import com.project.zcustom.domain.property.PlatPropertyTools;

import com.project.zcustom.mapper.property.PlatPropertyMapper;
import com.project.zcustom.service.service.property.IPlatPropertyListService;
import com.project.zcustom.service.service.property.IPlatPropertyService;
import com.project.zcustom.service.service.property.IPlatPropertyToolsService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * 共享驿站Service业务层处理
 *
 * @author change
 * @date 2024-10-21
 */
@Service
public class PlatPropertyServiceImpl extends ServiceImpl<PlatPropertyMapper, PlatProperty> implements IPlatPropertyService {

    @Resource
    private IPlatPropertyListService platPropertyListService;
    @Resource
    private IPlatPropertyToolsService platPropertyToolsService;

    /**
     * 组装查询条件
     */
    private LambdaQueryWrapper<PlatProperty> getLambdaQueryWrapper(PlatProperty platProperty) {
        LambdaQueryWrapper<PlatProperty> lqw = new LambdaQueryWrapper<PlatProperty>();
        if (StringUtils.isNotBlank(platProperty.getAppOrg())) {
            lqw.eq(PlatProperty::getAppOrg, platProperty.getAppOrg());
        }
        if (StringUtils.isNotNull(platProperty.getConstructionQuantityNum())) {
            lqw.eq(PlatProperty::getConstructionQuantityNum, platProperty.getConstructionQuantityNum());
        }
        if (StringUtils.isNotNull(platProperty.getCompletedNum())) {
            lqw.eq(PlatProperty::getCompletedNum, platProperty.getCompletedNum());
        }
        if (StringUtils.isNotNull(platProperty.getParticipateProportionRate())) {
            lqw.eq(PlatProperty::getParticipateProportionRate, platProperty.getParticipateProportionRate());
        }
        return lqw;
    }

    /**
     * 分页查询共享驿站列表
     *
     * @param platProperty 共享驿站
     * @return 共享驿站集合
     */
    @Override
    public IPage<PlatProperty> pagingPlatPropertyList(PlatProperty platProperty) {
        IPage<PlatProperty> page = new Page<>(platProperty.getPageNum(), platProperty.getPageSize());
        LambdaQueryWrapper<PlatProperty> lqw = getLambdaQueryWrapper(platProperty);
        // 排序 默认时间倒序
        lqw.orderByDesc(PlatProperty::getCreateTime);
        return baseMapper.selectPage(page, lqw);
    }

    /**
     * 分页查询共享驿站列表
     *
     * @param lqw
     * @return 共享驿站集合
     */
    @Override
    public IPage<PlatProperty> pagingPlatPropertyList(PageParamVo pageParamVo, LambdaQueryWrapper<PlatProperty> lqw) {
        IPage<PlatProperty> page = new Page<>(pageParamVo.getPageNum(), pageParamVo.getPageSize());
        // 排序 默认时间倒序
        lqw.orderByDesc(PlatProperty::getCreateTime);
        return baseMapper.selectPage(page, lqw);
    }

    /**
     * 查询共享驿站列表
     *
     * @param platProperty 共享驿站
     * @return 共享驿站
     */
    @Override
    public List<PlatProperty> selectPlatPropertyList(PlatProperty platProperty) {
        LambdaQueryWrapper<PlatProperty> lqw = getLambdaQueryWrapper(platProperty);
        // 排序 默认时间倒序
        lqw.orderByDesc(PlatProperty::getCreateTime);
        return baseMapper.selectList(lqw);
    }

    /**
     * 查询共享驿站列表
     *
     * @param platProperty 共享驿站
     * @return 共享驿站
     */
    @Override
    public List<PlatProperty> selectPlatPropertyList(PlatProperty platProperty, Long limitNum) {
        LambdaQueryWrapper<PlatProperty> lqw = getLambdaQueryWrapper(platProperty);
        // 排序 默认时间倒序
        lqw.orderByDesc(PlatProperty::getCreateTime);
        lqw.last("limit " + limitNum);
        return baseMapper.selectList(lqw);
    }

    /**
     * 根据指定字段查询信息
     *
     * @param field      字段名称
     * @param filedValue 字段值
     * @return 共享驿站
     */
    @Override
    public PlatProperty getPlatPropertyByField(String field, String filedValue) {
        QueryWrapper<PlatProperty> lqw = new QueryWrapper<PlatProperty>();
        lqw.eq(field, filedValue);
        lqw.last("limit 1");
        return this.getOne(lqw, false);
    }

    /**
     * 根据指定字段查询信息
     *
     * @param field      字段名称
     * @param filedValue 字段值
     * @return 共享驿站
     */
    @Override
    public PlatProperty getPlatPropertyByField(String field, String filedValue,String fieldString) {
        QueryWrapper<PlatProperty> lqw = new QueryWrapper<PlatProperty>();
        if(!(Objects.equals(field,"app_org") && Objects.equals(filedValue,"0000"))){
            lqw.eq(field, filedValue);
        }
        lqw.select(fieldString);
        lqw.last("limit 1");
        return this.getOne(lqw, false);
    }

    /**
     * 根据指定字段查询信息列表
     *
     * @param field      字段名称
     * @param filedValue 字段值
     * @return 共享驿站
     */
    @Override
    public List<PlatProperty> selectPlatPropertyListByField(String field, String filedValue, Long limitNum) {
        QueryWrapper<PlatProperty> lqw = new QueryWrapper<PlatProperty>();
        lqw.eq(field, filedValue);
        lqw.last("limit " + limitNum);
        return this.list(lqw);
    }

    /**
     * 根据指定字段查询信息列表
     *
     * @param field      字段名称
     * @param filedValue 字段值
     * @return 共享驿站
     */
    @Override
    public List<PlatProperty> selectPlatPropertyListByField(String field, String filedValue) {
        QueryWrapper<PlatProperty> lqw = new QueryWrapper<PlatProperty>();
        lqw.eq(field, filedValue);
        return this.list(lqw);
    }

    /**
     * 判断指定字段值是否存在
     *
     * @param field      字段名称
     * @param filedValue 字段值
     */
    @Override
    public void checkFieldExist(String field, String filedValue, String tips, Long id) {
        QueryWrapper<PlatProperty> lqw = new QueryWrapper<PlatProperty>();
        lqw.eq(field, filedValue);
        lqw.ne("id", id);
        if (this.getOne(lqw, false) != null) {
            throw new RuntimeException(tips + "已存在");
        }
    }
    /**
     *  真删接口
     */
    @Override
    public void reallyDeletePlatProperty(LambdaQueryWrapper<PlatProperty> lqw){
        baseMapper.reallyDeleteByWrapper(lqw);
    }

    /**
     * 添加共享驿站
     */
    @Override
    public void addPlatProperty(String appOrg,Map<String, Object> mapField){
        PlatProperty platProperty = this.getPlatPropertyByField("app_org", appOrg);
        try {
            if(StringUtils.isNotNull(platProperty)){
                this.setPlatProperty(mapField,platProperty);
                this.updateById(platProperty);
            }else{
                platProperty = new PlatProperty();
                this.setPlatProperty(mapField,platProperty);
                platProperty.setAppOrg(appOrg);
                this.save(platProperty);
            }
            this.handlePlatPropertyListData(appOrg,mapField);// 处理驿站数据
            this.handlePlatPropertyToolsData(appOrg,mapField);// 处理工具箱数据
        }catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 设置数据
     * @param mapField
     * @param platProperty
     */
    private void setPlatProperty(Map<String, Object> mapField,PlatProperty platProperty){
        List<String> keyList = Arrays.asList("constructionQuantity","completed","participateProportion");
        StringUtils.setFieldValue(platProperty,mapField,keyList,0, PlatProperty::setConstructionQuantityNum,Long.class);
        StringUtils.setFieldValue(platProperty,mapField,keyList,1, PlatProperty::setCompletedNum,Long.class);
        StringUtils.setFieldValue(platProperty,mapField,keyList,2, PlatProperty::setParticipateProportionRate,BigDecimal.class);
    }

    /**
     *  处理驿站数据
     */
    private void handlePlatPropertyListData(String appOrg,Map<String, Object> mapField){
        //先删除驿站数据
        LambdaQueryWrapper<PlatPropertyList> lqw = new LambdaQueryWrapper<>();
        lqw.eq(PlatPropertyList::getAppOrg, appOrg);
        platPropertyListService.reallyDeletePlatPropertyList(lqw);
       // 在添加
        if(mapField.containsKey("unitList")){
            JSONArray unitList = JSONArray.parseArray(mapField.get("unitList").toString());
            List<PlatPropertyList> addList = new ArrayList<>();
            for (Object o : unitList) {
                Map<String, Object> temp = JSONObject.parseObject(o.toString(), Map.class);
                PlatPropertyList platPropertyList = new PlatPropertyList();
                platPropertyList.setAppOrg(appOrg);
                platPropertyList.setStationName(temp.get("stationName").toString());
                platPropertyList.setStationAddress(temp.get("stationAddress").toString());
                platPropertyList.setStationNum(Long.valueOf(temp.get("stationNum").toString()));
                addList.add(platPropertyList);
            }
            platPropertyListService.saveBatch(addList);
        }
    }

    /**
     * 处理工具箱数据
     */
    private void handlePlatPropertyToolsData(String appOrg,Map<String, Object> mapField){
        PlatPropertyTools platPropertyTools = platPropertyToolsService.getPlatPropertyToolsByField("app_org", appOrg);
        if(StringUtils.isNotNull(platPropertyTools)){
            this.setPlatPropertyTools(mapField,platPropertyTools);
            platPropertyToolsService.updateById(platPropertyTools);
        }else{
            platPropertyTools = new PlatPropertyTools();
            this.setPlatPropertyTools(mapField,platPropertyTools);
            platPropertyTools.setAppOrg(appOrg);
            platPropertyToolsService.save(platPropertyTools);
        }
    }

    /**
     * 设置工具值 服务内容
     * @param mapField
     * @param platPropertyTools
     */
    private void setPlatPropertyTools(Map<String, Object> mapField,PlatPropertyTools platPropertyTools){
        List<String> keyList = Arrays.asList("selfTest","consultation");
        StringUtils.setFieldValue(platPropertyTools,mapField,keyList,0, PlatPropertyTools::setSelfTest,Long.class);
        StringUtils.setFieldValue(platPropertyTools,mapField,keyList,1, PlatPropertyTools::setConsultation,Long.class);
    }


    /**
     * 建设完成达标率
     * @param appOrg
     * @return
     */
    public Map<String, Object> getOverviewData(String appOrg){
        String fieldString = "construction_quantity_num,completed_num";
        if(Objects.equals(appOrg,"0000")){
            fieldString = "sum(construction_quantity_num) as construction_quantity_num,sum(completed_num) as completed_num";
        }
        PlatProperty platProperty = this.getPlatPropertyByField("app_org", appOrg,fieldString);
        Map<String, Object> tempMap = new HashMap<>();
        if (StringUtils.isNull(platProperty)) {
            StringUtils.getMapData("计划建设数量", "constructionQuantityNum", 0, tempMap);
            StringUtils.getMapData("已完成建设数量", "completedNum", 0, tempMap);
            StringUtils.getMapData("完成达标率", "participateProportionRate", 0, tempMap);
        }else{
            StringUtils.getMapData("计划建设数量", "constructionQuantityNum", platProperty.getConstructionQuantityNum(), tempMap);
            StringUtils.getMapData("已完成建设数量", "completedNum", platProperty.getCompletedNum(), tempMap);
            StringUtils.getMapData("完成达标率", "participateProportionRate", StringUtils.sumPercentage(platProperty.getCompletedNum(),platProperty.getConstructionQuantityNum()), tempMap);
        }
        return tempMap;
    }
}
