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

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.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.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.constants.BizConstant;
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.entity.IdxBizPvWeight;
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_pv_weight")
public class IdxBizPvWeightController extends BaseController {


    @Autowired
    IdxBizPvWeightMapper idxBizPvWeightMapper;
    @Autowired
    IdxBizFanWeightMapper idxBizFanWeightMapper;
    @Autowired
    UserEmpowerMapper userEmpowerMapper;
    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @GetMapping(value = "/queryPage")
    @ApiOperation(httpMethod = "GET",value = "场站列表",  notes = "场站列表")
    public ResponseModel<Page<IdxBizPvWeight>> queryForDealerReviewPage(@RequestParam(value = "current") int current, @RequestParam
            (value = "size") int size, IdxBizPvWeight 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<IdxBizPvWeight> qu=new LambdaQueryWrapper<>();
        qu.eq(!StringUtils.isEmpty(reviewDto.getType()),IdxBizPvWeight::getType,reviewDto.getType());
        qu.eq(!StringUtils.isEmpty(reviewDto.getArae()),IdxBizPvWeight::getArae,reviewDto.getArae());
        qu.eq(!StringUtils.isEmpty(reviewDto.getStation()),IdxBizPvWeight::getStation,reviewDto.getStation());
        qu.eq(!StringUtils.isEmpty(reviewDto.getSubarray()),IdxBizPvWeight::getSubarray,reviewDto.getSubarray());
        qu.eq(!StringUtils.isEmpty(reviewDto.getEquipmentName()),IdxBizPvWeight::getEquipmentName,reviewDto.getEquipmentName());
        qu.eq(!StringUtils.isEmpty(reviewDto.getPointName()),IdxBizPvWeight::getPointName,reviewDto.getPointName());
        qu.like(IdxBizPvWeight::getOrgCode,orgCode);
        Integer total = idxBizPvWeightMapper.selectCount(qu);
        qu.orderByAsc(IdxBizPvWeight::getType);
        qu.last(" limit "+ (current-1)*size+","+size);
       /// PageHelper.startPage(current, size);
        List<IdxBizPvWeight> list = idxBizPvWeightMapper.selectList(qu);
       // PageInfo<IdxBizPvWeight> page = new PageInfo(list);

        List<IdxBizPvWeight> 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());

        com.baomidou.mybatisplus.extension.plugins.pagination.Page<IdxBizPvWeight> pagenew = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<IdxBizPvWeight>();
        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<IdxBizPvWeight>> queryForDealerReviewPage(String type
//            ,String arae
//            ,String station
//            ,String equipmentName
//            ,String subarray
//            ,String pointName
    ) {
        if(type==null){
            return ResponseHelper.buildResponse(null);
        }
        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< IdxBizPvWeight> qu=new QueryWrapper<>();
        String name="";
        IdxBizPvWeight qt=new IdxBizPvWeight();
        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<IdxBizPvWeight> list = idxBizPvWeightMapper.selectList(qu);
        List<IdxBizPvWeight> list = idxBizPvWeightMapper.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<IdxBizPvWeight> update(@RequestBody Map<String,Object> value) {
        if (value != null) {
            List<String> list1 = Arrays.asList(value.get("ids").toString().split(","));
            LambdaQueryWrapper<IdxBizPvWeight> qu1 = new LambdaQueryWrapper<>();
            qu1.in(!list1.isEmpty(), IdxBizPvWeight::getSequenceNbr, list1);
            List<IdxBizPvWeight> list = idxBizPvWeightMapper.selectList(qu1);
            //如果区域为一个，则权重只能为1
            Integer araeCount = idxBizPvWeightMapper.selectCount(new LambdaQueryWrapper<IdxBizPvWeight>().eq(IdxBizPvWeight::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");
                }
            }
            IdxBizPvWeight reviewDto = list.get(0);
            LambdaQueryWrapper<IdxBizPvWeight> qu = new LambdaQueryWrapper<>();
            //获取所属，同类指标

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

            //判断是否同一层级
            String flagtype = null;
            for (IdxBizPvWeight 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.getSubarray();

                            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.getSubarray())) {
                                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()), IdxBizPvWeight::getType, reviewDto.getType());


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

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

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

                    break;
                case "5":
                    qu.eq(!StringUtils.isEmpty(reviewDto.getType()), IdxBizPvWeight::getType, reviewDto.getType());
                    qu.eq(!StringUtils.isEmpty(reviewDto.getArae()), IdxBizPvWeight::getArae, reviewDto.getArae());
                    qu.eq(!StringUtils.isEmpty(reviewDto.getStation()), IdxBizPvWeight::getStation, reviewDto.getStation());
                    qu.eq(!StringUtils.isEmpty(reviewDto.getSubarray()), IdxBizPvWeight::getSubarray, reviewDto.getSubarray());
                    qu.eq(!StringUtils.isEmpty(reviewDto.getEquipmentName()), IdxBizPvWeight::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<IdxBizPvWeight> listdata = idxBizPvWeightMapper.selectList(qu);
            //处理场站级别 包括风电
            int  allDataSize = listdata.size();
            List<IdxBizFanWeight> fanData = new ArrayList<>();
            if("2".equals(reviewDto.getType())){
                LambdaQueryWrapper<IdxBizFanWeight> fanWrapper = new LambdaQueryWrapper<>();
                fanWrapper.eq(IdxBizFanWeight::getType, reviewDto.getType());
                fanWrapper.eq(IdxBizFanWeight::getArae, reviewDto.getArae());
                fanData = idxBizFanWeightMapper.selectList(fanWrapper);
                allDataSize= allDataSize + fanData.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 (IdxBizPvWeight listdatum : listdata) {
                for (IdxBizPvWeight 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;
                    }
                }
                idxBizPvWeightMapper.updateById(listdatum);
            }
            if(CollectionUtil.isNotEmpty(fanData)){
                for (IdxBizFanWeight listdatum : fanData) {
                    listdatum.setValue(formattedNum);
                    listdatum.setFlag(null);
                    idxBizFanWeightMapper.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<IdxBizPvWeight> update(@RequestBody Map<String,List<IdxBizPvWeight>> map) {
//        //获取所属，同类指标
//        if(map!=null){
//            List<IdxBizPvWeight> list= map.get("data");
//            //判断是否同一层级
//            String flagtype=null;
//            for (IdxBizPvWeight idxBizPvWeight : list) {
//                if(flagtype==null){
//
//                    flagtype=  idxBizPvWeight.getArae()+idxBizPvWeight.getStation()+idxBizPvWeight.getEquipmentName()+idxBizPvWeight.getSubarray()+idxBizPvWeight.getPointName()+idxBizPvWeight.getType();
//                }else{
//                    if(!flagtype.equals(idxBizPvWeight.getArae()+idxBizPvWeight.getStation()+idxBizPvWeight.getEquipmentName()+idxBizPvWeight.getSubarray()+idxBizPvWeight.getPointName()+idxBizPvWeight.getType())){
//                        throw new BadRequest("配置权重必须是同一个层级的数据");
//                    }
//                }
//            }
//            Float  value= list.stream().map(e->e.getValue()).reduce(Float::sum).get();
//            IdxBizPvWeight reviewDto= list.get(0);
//            LambdaQueryWrapper<IdxBizPvWeight> qu=new LambdaQueryWrapper<>();
//            qu.eq(!StringUtils.isEmpty(reviewDto.getType()),IdxBizPvWeight::getType,reviewDto.getType());
//            qu.eq(!StringUtils.isEmpty(reviewDto.getArae()),IdxBizPvWeight::getArae,reviewDto.getArae());
//            qu.eq(!StringUtils.isEmpty(reviewDto.getStation()), IdxBizPvWeight::getStation,reviewDto.getStation());
//            qu.eq(!StringUtils.isEmpty(reviewDto.getSubarray()),IdxBizPvWeight::getSubarray,reviewDto.getSubarray());
//            qu.eq(!StringUtils.isEmpty(reviewDto.getEquipmentName()),IdxBizPvWeight::getEquipmentName,reviewDto.getEquipmentName());
//            qu.eq(!StringUtils.isEmpty(reviewDto.getPointName()),IdxBizPvWeight::getPointName,reviewDto.getPointName());
//            List<IdxBizPvWeight> listdata = idxBizPvWeightMapper.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.0000").format((1-value)/num)):0;
//
//            for (IdxBizPvWeight listdatum : listdata) {
//                for (IdxBizPvWeight idxBizPvWeight : list) {
//                    if(idxBizPvWeight.getSequenceNbr().equals(listdatum.getSequenceNbr())){
//                        listdatum.setValue(idxBizPvWeight.getValue());
//                        break;
//                    }else{
//                        listdatum.setValue(formattedNum);
//                        break;
//                    }
//                }
//                idxBizPvWeightMapper.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<IdxBizPvWeight> qu=new LambdaQueryWrapper<>();
//        qu.in(!list.isEmpty(),IdxBizPvWeight::getSequenceNbr,list);
//        List<IdxBizPvWeight> listdata = idxBizPvWeightMapper.selectList(qu);
//        Map<String,Object> data=new HashMap<>();
//
//        data.put("data",listdata);
//        return ResponseHelper.buildResponse(data);
//    }
}
