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

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.controller.BaseController;
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.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.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.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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;

    @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) {

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


        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);
            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);
        }
        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.isNotNull(name);
        qu.groupBy(name);
        qu.orderByAsc(name);
        List<IdxBizPvWeight> list = idxBizPvWeightMapper.selectList(qu);
        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);
            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()+  idxBizFanWeight.getSubarray();

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

                            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()+  idxBizFanWeight.getSubarray())) {
                                throw new BadRequest( "配置权重必须是同一个层级的数据");
                            }
                            break;
                        case "4":
                            if (!flagtype.equals(idxBizFanWeight.getArae() + idxBizFanWeight.getStation() )) {
                                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());
                    qu.eq(!StringUtils.isEmpty(reviewDto.getSubarray()), IdxBizPvWeight::getSubarray, reviewDto.getSubarray());

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

                    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 num = listdata.size() - 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);
                    if (idxBizPvWeight.getSequenceNbr().equals(listdatum.getSequenceNbr())) {
                        listdatum.setValue(Float.valueOf(value.get("data").toString()));
                        break;
                    }
                }
                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<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);
//    }
}
