package com.yeejoin.amos.boot.module.jxiop.biz.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.module.jxiop.biz.amosprojectentity.StdUserEmpower;
import com.yeejoin.amos.boot.module.jxiop.biz.amosprojectmapper.UserEmpowerMapper;
import com.yeejoin.amos.boot.module.jxiop.biz.dto.IdxBiz3yudDto;
import com.yeejoin.amos.boot.module.jxiop.biz.entity.IdxBizFanWeight;
import com.yeejoin.amos.boot.module.jxiop.biz.entity.IdxBizPvWeight;
import com.yeejoin.amos.boot.module.jxiop.biz.mapper2.IdxBizFanWeightMapper;
import com.yeejoin.amos.boot.module.jxiop.biz.mapper2.IdxBizPvWeightMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.foundation.exception.BaseException;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

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

/**
 * @description:
 * @author: tw
 * @createDate: 2023/10/23
 */
@RestController
@Api(tags = "Api")
@RequestMapping(value = "/idx_biz_fan_weight")
public class IdxBizFanWeightController extends BaseController {

    @Autowired
    IdxBizFanWeightMapper idxBizFanWeightMapper;
    @Autowired
    IdxBizPvWeightMapper idxBizPvWeightMapper;

    @Autowired
    UserEmpowerMapper userEmpowerMapper;
    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @GetMapping(value = "/queryPage")
    @ApiOperation(httpMethod = "GET",value = "场站列表",  notes = "场站列表")
    public ResponseModel<com.baomidou.mybatisplus.extension.plugins.pagination.Page<IdxBizFanWeight>> queryForDealerReviewPage(@RequestParam(value = "current") int current, @RequestParam
            (value = "size") int size, IdxBizFanWeight reviewDto) {
        ReginParams reginParams = getSelectedOrgInfo();
        String userId = reginParams.getUserModel().getUserId();
        StdUserEmpower stdUserEmpower = userEmpowerMapper.selectOne(new QueryWrapper<StdUserEmpower>().eq("amos_user_id", userId).eq("permission_type", "YTH"));
        String orgCode = "86";
        if (!ObjectUtils.isEmpty(stdUserEmpower)) {
            orgCode = stdUserEmpower.getAmosOrgCode().get(0);
        }
        LambdaQueryWrapper<IdxBizFanWeight> qu=new LambdaQueryWrapper<>();
        qu.eq(!StringUtils.isEmpty(reviewDto.getType()),IdxBizFanWeight::getType,reviewDto.getType());
        qu.eq(!StringUtils.isEmpty(reviewDto.getArae()),IdxBizFanWeight::getArae,reviewDto.getArae());
        qu.eq(!StringUtils.isEmpty(reviewDto.getStation()), IdxBizFanWeight::getStation,reviewDto.getStation());
        qu.eq(!StringUtils.isEmpty(reviewDto.getSubarray()),IdxBizFanWeight::getSubarray,reviewDto.getSubarray());
        qu.eq(!StringUtils.isEmpty(reviewDto.getEquipmentName()),IdxBizFanWeight::getEquipmentName,reviewDto.getEquipmentName());
        qu.eq(!StringUtils.isEmpty(reviewDto.getPointName()),IdxBizFanWeight::getPointName,reviewDto.getPointName());
        qu.like(IdxBizFanWeight::getOrgCode,orgCode);

        Integer total = idxBizFanWeightMapper.selectCount(qu);
        qu.orderByAsc(IdxBizFanWeight::getType);
        qu.last(" limit "+ (current-1)*size+","+size);
        //PageHelper.startPage(current, size);
        List<IdxBizFanWeight> list = idxBizFanWeightMapper.selectList(qu);

        List<IdxBizFanWeight> formattedDates =  list.stream().map(e-> {
            e.setValue(e.getValue()!=null?Float.parseFloat(new DecimalFormat("0.000").format(e.getValue())):null);
            e.setValueS(e.getValue()!=null?new DecimalFormat("0.000").format(e.getValue()):null);
                    switch(e.getType()){
                        case "1":
                            e.setType("片区");
                            break;
                        case "2":
                            e.setType("场站");
                            break;
                        case "3":
                            e.setType("设备");
                            break;
                        case "4":
                            e.setType("子系统");
                            break;
                        case "5":
                            e.setType("变量");
                            break;
                    }
                    return e;
                }
        ).collect(Collectors.toList());

        //PageInfo<IdxBizFanWeight> page = new PageInfo(list);
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<IdxBizFanWeight> pagenew = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<IdxBizFanWeight>();
        pagenew.setCurrent(current);
        pagenew.setTotal(total);
        pagenew.setSize(size);
        pagenew.setRecords(formattedDates);
        return ResponseHelper.buildResponse(pagenew);
    }
    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @GetMapping(value = "/drop_down")
    @ApiOperation(httpMethod = "GET",value = "场站列表",  notes = "场站列表")
    public ResponseModel<List<IdxBizFanWeight>> queryForDealerReviewPage(String type
//            ,String arae
//            ,String station
//            ,String equipmentName
//            ,String subarray
//            ,String pointName
    ) {

        ReginParams reginParams = getSelectedOrgInfo();
        String userId = reginParams.getUserModel().getUserId();
        StdUserEmpower stdUserEmpower = userEmpowerMapper.selectOne(new QueryWrapper<StdUserEmpower>().eq("amos_user_id", userId).eq("permission_type", "YTH"));
        String orgCode = "86";
        if (!ObjectUtils.isEmpty(stdUserEmpower)) {
            orgCode = stdUserEmpower.getAmosOrgCode().get(0);
        }
//        QueryWrapper< IdxBizFanWeight> qu=new QueryWrapper<>();
        String name="";
        switch(type){
            case "1":
                name="ARAE";
//                qu.eq("ARAE",arae);
                break;
            case "2":
                name="STATION";
//                qu.eq("ARAE",arae);
//                qu.eq("STATION",station);
                break;
            case "3":
                name="EQUIPMENT_NAME";
//                qu.eq("ARAE",arae);
//                qu.eq("STATION",station);
//                qu.eq("EQUIPMENT_NAME",equipmentName);
                break;
            case "4":
                name="SUBARRAY";
//                qu.eq("ARAE",arae);
//                qu.eq("STATION",station);
//                qu.eq("EQUIPMENT_NAME",equipmentName);
//                qu.eq("SUBARRAY",subarray);
                break;
            case "5":
                name="POINT_NAME";
//                qu.eq("ARAE",arae);
//                qu.eq("STATION",station);
//                qu.eq("EQUIPMENT_NAME",equipmentName);
//                qu.eq("SUBARRAY",subarray);
//                qu.eq("POINT_NAME",pointName);
                break;
        }
//        qu.like("ORG_CODE",orgCode);
//        qu.isNotNull(name);
//        qu.groupBy(name);
//        qu.orderByAsc(name);
//        List<IdxBizFanWeight> list = idxBizFanWeightMapper.selectList(qu);
        List<IdxBizFanWeight> list = idxBizFanWeightMapper.selectAllByParams(name,"%"+orgCode+"%");
        return ResponseHelper.buildResponse(list);
    }


    @Transactional
    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @PostMapping(value = "/update")
    @ApiOperation(httpMethod = "POST", value = "根据sequenceNbr更新", notes = "根据sequenceNbr更新")
    public ResponseModel<IdxBizFanWeight> update(@RequestBody Map<String,Object> value) {
        if (value != null) {
            List<String> list1 = Arrays.asList(value.get("ids").toString().split(","));
            LambdaQueryWrapper<IdxBizFanWeight> qu1 = new LambdaQueryWrapper<>();
            qu1.in(!list1.isEmpty(), IdxBizFanWeight::getSequenceNbr, list1);
            List<IdxBizFanWeight> list = idxBizFanWeightMapper.selectList(qu1);
            //如果区域为一个，则权重只能为1
            Integer araeCount = idxBizFanWeightMapper.selectCount(new LambdaQueryWrapper<IdxBizFanWeight>().eq(IdxBizFanWeight::getType, "1"));
            if(araeCount == 1 && CollectionUtil.isNotEmpty(list) && list.size()==1 && list.get(0).getType().equals("1")){
                if(!"1.0000".equals(value.get("data").toString())){
                    throw new BadRequest("该区域权重只能配置为1");
                }
            }
            IdxBizFanWeight reviewDto = list.get(0);
            LambdaQueryWrapper<IdxBizFanWeight> qu = new LambdaQueryWrapper<>();
            //获取所属，同类指标

//            Float list= map.get("data");

            //判断是否同一层级
            String flagtype = null;
            for (IdxBizFanWeight idxBizFanWeight : list) {
                if (flagtype == null) {

                    switch (reviewDto.getType()) {
                        case "1":
//                            flagtype = idxBizFanWeight.getArae() ;

                            break;
                        case "2":
                            flagtype = idxBizFanWeight.getArae();

                            break;
                        case "3":
                            flagtype = idxBizFanWeight.getArae() + idxBizFanWeight.getStation();

                            break;
                        case "4":
                            flagtype = idxBizFanWeight.getArae() + idxBizFanWeight.getStation() + idxBizFanWeight.getEquipmentName();

                            break;
                        case "5":
                            flagtype = idxBizFanWeight.getArae() + idxBizFanWeight.getStation() + idxBizFanWeight.getEquipmentName() + idxBizFanWeight.getSubarray();
                            break;
                    }
                } else {
                    switch (reviewDto.getType()) {
                        case "1":
//                            if (!flagtype.equals(idxBizFanWeight.getArae() )) {
//                                throw new BadRequest("配置权重必须是同一个层级的数据");
//                            }
                            break;
                        case "2":
                            if (!flagtype.equals(idxBizFanWeight.getArae())) {
                                throw new BadRequest("配置权重必须是同一个层级的数据");
                            }
                            break;
                        case "3":
                            if (!flagtype.equals(idxBizFanWeight.getArae() + idxBizFanWeight.getStation())) {
                                throw new BadRequest("配置权重必须是同一个层级的数据");
                            }
                            break;
                        case "4":
                            if (!flagtype.equals(idxBizFanWeight.getArae() + idxBizFanWeight.getStation() + idxBizFanWeight.getEquipmentName())) {
                                throw new BadRequest("配置权重必须是同一个层级的数据");
                            }
                            break;
                        case "5":
                            if (!flagtype.equals(idxBizFanWeight.getArae() + idxBizFanWeight.getStation() + idxBizFanWeight.getEquipmentName() + idxBizFanWeight.getSubarray())) {

                                throw new BadRequest("配置权重必须是同一个层级的数据");

                            }
                            break;
                    }
                }
            }
                Float valued = list.size() * Float.valueOf(value.get("data").toString());


            switch (reviewDto.getType()) {
                case "1":
                    qu.eq(!StringUtils.isEmpty(reviewDto.getType()), IdxBizFanWeight::getType, reviewDto.getType());


                    break;
                case "2":
                    qu.eq(!StringUtils.isEmpty(reviewDto.getType()), IdxBizFanWeight::getType, reviewDto.getType());
                    qu.eq(!StringUtils.isEmpty(reviewDto.getArae()), IdxBizFanWeight::getArae, reviewDto.getArae());

                    break;
                case "3":
                    qu.eq(!StringUtils.isEmpty(reviewDto.getType()), IdxBizFanWeight::getType, reviewDto.getType());
                    qu.eq(!StringUtils.isEmpty(reviewDto.getArae()), IdxBizFanWeight::getArae, reviewDto.getArae());
                    qu.eq(!StringUtils.isEmpty(reviewDto.getStation()), IdxBizFanWeight::getStation, reviewDto.getStation());

                    break;
                case "4":
                    qu.eq(!StringUtils.isEmpty(reviewDto.getType()), IdxBizFanWeight::getType, reviewDto.getType());
                    qu.eq(!StringUtils.isEmpty(reviewDto.getArae()), IdxBizFanWeight::getArae, reviewDto.getArae());
                    qu.eq(!StringUtils.isEmpty(reviewDto.getStation()), IdxBizFanWeight::getStation, reviewDto.getStation());
                    qu.eq(!StringUtils.isEmpty(reviewDto.getEquipmentName()), IdxBizFanWeight::getEquipmentName, reviewDto.getEquipmentName());

                    break;
                case "5":
                    qu.eq(!StringUtils.isEmpty(reviewDto.getType()), IdxBizFanWeight::getType, reviewDto.getType());
                    qu.eq(!StringUtils.isEmpty(reviewDto.getArae()), IdxBizFanWeight::getArae, reviewDto.getArae());
                    qu.eq(!StringUtils.isEmpty(reviewDto.getStation()), IdxBizFanWeight::getStation, reviewDto.getStation());
                    qu.eq(!StringUtils.isEmpty(reviewDto.getSubarray()), IdxBizFanWeight::getSubarray, reviewDto.getSubarray());
                    qu.eq(!StringUtils.isEmpty(reviewDto.getEquipmentName()), IdxBizFanWeight::getEquipmentName, reviewDto.getEquipmentName());
                    break;
            }

//                qu.eq(!StringUtils.isEmpty(reviewDto.getType()), IdxBizFanWeight::getType, reviewDto.getType());
//                qu.eq(!StringUtils.isEmpty(reviewDto.getArae()), IdxBizFanWeight::getArae, reviewDto.getArae());
//                qu.eq(!StringUtils.isEmpty(reviewDto.getStation()), IdxBizFanWeight::getStation, reviewDto.getStation());
//                qu.eq(!StringUtils.isEmpty(reviewDto.getSubarray()), IdxBizFanWeight::getSubarray, reviewDto.getSubarray());
//                qu.eq(!StringUtils.isEmpty(reviewDto.getEquipmentName()), IdxBizFanWeight::getEquipmentName, reviewDto.getEquipmentName());
//                qu.eq(!StringUtils.isEmpty(reviewDto.getPointName()), IdxBizFanWeight::getPointName, reviewDto.getPointName());
                List<IdxBizFanWeight> listdata = idxBizFanWeightMapper.selectList(qu);

            //场站级别包括风电
            int  allDataSize = listdata.size();
            List<IdxBizPvWeight> pvData = new ArrayList<>();
            if("2".equals(reviewDto.getType())){
                LambdaQueryWrapper<IdxBizPvWeight> pvWrapper = new LambdaQueryWrapper<>();
                pvWrapper.eq(IdxBizPvWeight::getType, reviewDto.getType());
                pvWrapper.eq(IdxBizPvWeight::getArae, reviewDto.getArae());
                pvData = idxBizPvWeightMapper.selectList(pvWrapper);
                allDataSize= allDataSize + pvData.size();
            }
                //设置权重值，
                int num = allDataSize - list.size();
                if (num == 0) {
                    if (valued != 1) {
                        throw new BadRequest("超出权重最大值限制，层级下权重等级总和为1");

                    }
                }


                //值不能大于1
                if (valued > 1) {
                    throw new BadRequest("超出权重最大值限制，层级下权重等级总和为1");

                }
                if (valued == 1 && num != 0) {
                    throw new BadRequest("超出权重最大值限制，层级下权重等级总和为1");

                }

                //剩余权重值
                float formattedNum = num != 0 ? Float.parseFloat(new DecimalFormat("0.0000000000").format((1 - valued) / num)) : 0;

                for (IdxBizFanWeight listdatum : listdata) {
                    for (IdxBizFanWeight idxBizPvWeight : list) {
                        listdatum.setValue(formattedNum);
                        listdatum.setFlag(null);
                        if (idxBizPvWeight.getSequenceNbr().equals(listdatum.getSequenceNbr())) {
                            listdatum.setValue(Float.valueOf(value.get("data").toString()));
                            listdatum.setFlag("是");
                            break;
                        }
                    }
                    idxBizFanWeightMapper.updateById(listdatum);
                }

            if(CollectionUtil.isNotEmpty(pvData)){
                for (IdxBizPvWeight listdatum : pvData) {
                    listdatum.setValue(formattedNum);
                    listdatum.setFlag(null);
                    idxBizPvWeightMapper.updateById(listdatum);
                }
            }
            }

            return ResponseHelper.buildResponse(null);
        }


//    @Transactional
//    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
//    @PostMapping(value = "/update")
//    @ApiOperation(httpMethod = "POST", value = "根据sequenceNbr更新", notes = "根据sequenceNbr更新")
//    public ResponseModel<IdxBizFanWeight> update(@RequestBody Map<String,List<IdxBizFanWeight>> map) {
//        //获取所属，同类指标
//        if(map!=null){
//            List<IdxBizFanWeight> list= map.get("data");
//            //判断是否同一层级
//            String flagtype=null;
//            for (IdxBizFanWeight idxBizFanWeight : list) {
//                if(flagtype==null){
//
//                    flagtype=  idxBizFanWeight.getArae()+idxBizFanWeight.getStation()+idxBizFanWeight.getEquipmentName()+idxBizFanWeight.getSubarray()+idxBizFanWeight.getPointName()+idxBizFanWeight.getType();
//                }else{
//                    if(!flagtype.equals(idxBizFanWeight.getArae()+idxBizFanWeight.getStation()+idxBizFanWeight.getEquipmentName()+idxBizFanWeight.getSubarray()+idxBizFanWeight.getPointName()+idxBizFanWeight.getType())){
//                        throw new BadRequest("配置权重必须是同一个层级的数据");
//                    }
//                }
//            }
//            Float  value= list.stream().map(e->e.getValue()).reduce(Float::sum).get();
//            IdxBizFanWeight reviewDto= list.get(0);
//            LambdaQueryWrapper<IdxBizFanWeight> qu=new LambdaQueryWrapper<>();
//            qu.eq(!StringUtils.isEmpty(reviewDto.getType()),IdxBizFanWeight::getType,reviewDto.getType());
//            qu.eq(!StringUtils.isEmpty(reviewDto.getArae()),IdxBizFanWeight::getArae,reviewDto.getArae());
//            qu.eq(!StringUtils.isEmpty(reviewDto.getStation()), IdxBizFanWeight::getStation,reviewDto.getStation());
//            qu.eq(!StringUtils.isEmpty(reviewDto.getSubarray()),IdxBizFanWeight::getSubarray,reviewDto.getSubarray());
//            qu.eq(!StringUtils.isEmpty(reviewDto.getEquipmentName()),IdxBizFanWeight::getEquipmentName,reviewDto.getEquipmentName());
//            qu.eq(!StringUtils.isEmpty(reviewDto.getPointName()),IdxBizFanWeight::getPointName,reviewDto.getPointName());
//            List<IdxBizFanWeight> listdata = idxBizFanWeightMapper.selectList(qu);
//
//            //设置权重值，
//            int num= listdata.size()-list.size();
//
//            //值不能大于1
//                if(value>1){
//                    throw new BadRequest("超出权重最大值限制，层级下权重等级总和为1");
//                }
//                if(value!=1&&num!=0){
//                    throw new BadRequest("超出权重最大值限制，层级下权重等级总和为1");
//                }
//
//
//
//
//            //剩余权重值
//            float formattedNum =num!=0? Float.parseFloat(new DecimalFormat("0.0000000000").format((1-value)/num)):0;
//
//            for (IdxBizFanWeight listdatum : listdata) {
//                for (IdxBizFanWeight idxBizPvWeight : list) {
//                    if(idxBizPvWeight.getSequenceNbr().equals(listdatum.getSequenceNbr())){
//                        listdatum.setValue(idxBizPvWeight.getValue());
//                        break;
//                    }else{
//                        listdatum.setValue(formattedNum);
//                        break;
//                    }
//                }
//                idxBizFanWeightMapper.updateById(listdatum);
//            }
//
//
//        }
//
//        return ResponseHelper.buildResponse(null);
//    }
        @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
        @GetMapping (value = "/list")
        @ApiOperation(httpMethod = "get", value = "根据sequenceNbr更新", notes = "根据sequenceNbr更新")
        public ResponseModel<Map<String,Object>> list( String ids) {
            Map<String,Object> data=new HashMap<>();

            data.put("ids",ids);
            return ResponseHelper.buildResponse(data);
        }

//    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
//    @GetMapping (value = "/list")
//    @ApiOperation(httpMethod = "get", value = "根据sequenceNbr更新", notes = "根据sequenceNbr更新")
//    public ResponseModel<Map<String,Object>> list( String ids
//    ) {
//        List<String> list= Arrays.asList(ids.split(","));
//        LambdaQueryWrapper<IdxBizFanWeight> qu=new LambdaQueryWrapper<>();
//        qu.in(!list.isEmpty(),IdxBizFanWeight::getSequenceNbr,list);
//        List<IdxBizFanWeight> listdata = idxBizFanWeightMapper.selectList(qu);
//        Map<String,Object> data=new HashMap<>();
//
//        data.put("data",listdata);
//        return ResponseHelper.buildResponse(data);
//    }

}
