package com.steerinfo.meterwork.meterworkcomparespot.controller;

import com.steerinfo.baseinfo.meterbaserailwaycarriageweight.model.MeterBaseRailwayCarriageWeight;
import com.steerinfo.framework.controller.BaseRESTfulController;
import com.steerinfo.framework.controller.RESTfulResult;
import com.steerinfo.framework.service.pagehelper.PageList;
import com.steerinfo.framework.user.UserPayload;
import com.steerinfo.framework.utils.collection.ListUtils;
import com.steerinfo.meterwork.meterworkcomparespot.model.MeterWorkCompareSpot;
import com.steerinfo.meterwork.meterworkcomparespot.service.IMeterWorkCompareSpotService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * MeterWorkCompareSpot RESTful接口：
 * @author generator
 * @version 1.0-SNAPSHORT 2022-05-06 06:28
 * 类描述
 * 修订历史：
 * 日期：2022-05-06
 * 作者：generator
 * 参考：
 * 描述：MeterWorkCompareSpot RESTful接口
 * @see null
 * @Copyright 湖南视拓信息技术股份有限公司. All rights reserved.
 */
@RestController
@RequestMapping("/${api.version}/meterworkcomparespots")
public class MeterWorkCompareSpotController extends BaseRESTfulController {

    @Autowired
    IMeterWorkCompareSpotService meterWorkCompareSpotService;

    @ApiOperation(value="获取列表", notes="分页查询")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
        @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    //@RequiresPermissions("meterworkcomparespot:view")
    @GetMapping(value = "/")
    public RESTfulResult list(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
        PageList<MeterWorkCompareSpot> list = meterWorkCompareSpotService.queryDESCForPage(parmas, pageNum, pageSize);
        return success(list);
    }

    @ApiOperation(value="获取列表", notes="分页模糊查询")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
        @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    //@RequiresPermissions("meterworkcomparespot:view")
    @GetMapping(value = "/like/")
    public RESTfulResult listLike(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
        PageList<MeterWorkCompareSpot> list = meterWorkCompareSpotService.queryLikeForPage(parmas, pageNum, pageSize);
        return success(list);
    }
    
    @ApiOperation(value="创建", notes="根据MeterWorkCompareSpot对象创建")
    @ApiImplicitParam(name = "meterWorkCompareSpot", value = "详细实体meterWorkCompareSpot", required = true, dataType = "MeterWorkCompareSpot")
    //@RequiresPermissions("meterworkcomparespot:create")
    @PostMapping(value = "/")
    public RESTfulResult add(@ModelAttribute MeterWorkCompareSpot model){
        MeterWorkCompareSpot meterWorkCompareSpot = meterWorkCompareSpotService.add(model);
        return success(meterWorkCompareSpot);
    }

    @ApiOperation(value="获取详细信息", notes="根据url的id来获取详细信息")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    //@RequiresPermissions("meterworkcomparespot:view")
    @GetMapping(value = "/{id}")
    public RESTfulResult get(@PathVariable String id){
        MeterWorkCompareSpot meterWorkCompareSpot = meterWorkCompareSpotService.getById(id);
        return success(meterWorkCompareSpot);
    }

    @ApiOperation(value="更新详细信息", notes="根据url的id来指定更新对象，并根据传过来的meterWorkCompareSpot信息来更新详细信息")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String"),
        @ApiImplicitParam(name = "meterWorkCompareSpot", value = "详细实体meterWorkCompareSpot", required = true, dataType = "MeterWorkCompareSpot")
    })
    //@RequiresPermissions("meterworkcomparespot:update")
    @PutMapping(value = "/{id}", produces  = "application/json;charset=UTF-8")
    public RESTfulResult update(@PathVariable String id, @RequestBody MeterWorkCompareSpot model){
        model.setId(id);
        MeterWorkCompareSpot meterWorkCompareSpot = meterWorkCompareSpotService.modify(model);
        return success(meterWorkCompareSpot);
    }

    @ApiOperation(value="更新详细信息", notes="根据url的id来指定更新对象，并根据传过来的meterWorkCompareSpot信息来更新详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String"),
            @ApiImplicitParam(name = "meterWorkCompareSpot", value = "详细实体meterWorkCompareSpot", required = true, dataType = "MeterWorkCompareSpot")
    })
    //@RequiresPermissions("meterworkcomparespot:update")
    @PostMapping(value = "/updateModel", produces  = "application/json;charset=UTF-8")
    public RESTfulResult update(@RequestBody MeterWorkCompareSpot model){
        String userName = "";
        try {
            UserPayload payload = UserPayload.getCurrUser();
            userName = payload.getUserName();
        } catch (Exception ex) {
            userName = "admins";
        }
        model.setUpdateManName(userName);
        model.setUpdateTime(new Date());
        MeterWorkCompareSpot meterWorkCompareSpot = meterWorkCompareSpotService.modify(model);
        return success(meterWorkCompareSpot.getCompareSpotId());
    }

    @ApiOperation(value="删除", notes="根据url的id来指定删除对象")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    //@RequiresPermissions("meterworkcomparespot:delete")
    @DeleteMapping(value = "/{id}")//String
    public RESTfulResult delete(@PathVariable String id){
    	List<String> list = Arrays.asList(id.split(","));
    	if(ListUtils.isNotEmpty(list)) {
	    	List<String> ids = ListUtils.convertList(list);
			  meterWorkCompareSpotService.delete(ids);
    	}
      return success();
    }

    @ApiOperation(value="提交结果", notes="提交断差结果")
    @PutMapping(value = "/submitBreakResult" ,produces  = "application/json;charset=UTF-8")
    public RESTfulResult submitBreakResult(@RequestBody HashMap<String,Object> map){

        //车号
        String carNo = null;
        //重量
        Long weight = 0L;
        //操作人姓名
        String name = null;
        //站点名
        String spotName = null;
        //站点编号
        String spotNo = null;

        //获取参数
        //当参数缺少时会向返回 “参数不全或错误“
        try {
            carNo = map.get("carNo").toString();
            weight = Long.valueOf(map.get("weight").toString());
            name = map.get("name").toString();
            spotName = map.get("spotName").toString();
            spotNo = map.get("spotNo").toString();
        }catch (Exception e){
            return failed(null,"参数不全或错误");
        }
        //日期
        Date date = new Date();

        //防止传过来的参数为空字符串
        if(carNo.equals("")||name.equals("")||spotName.equals("")||spotNo.equals("")){
            return failed(null,"传过来的参数存在空字符串");
        }

        //重量不能小于0
        if(weight < 0){
            return failed(null,"重量不能小于0");
        }

        //取出车号为carNo的一个小时以内的较秤类型为断差（即数据库中标识为1）的数据主键
        String COMPARE_SPOT_ID = meterWorkCompareSpotService.isExistWithinOneHour(carNo);
//        System.out.println("---------------");
//        System.out.println(COMPARE_SPOT_ID);
//        System.out.println("---------------");

        if (COMPARE_SPOT_ID == null){//没有查询到相应的主键 创建一条新数据
            //创建数据
            MeterWorkCompareSpot spot = new MeterWorkCompareSpot();
            //设置主键
            spot.setCompareSpotId(meterWorkCompareSpotService.creatCompareSpotId());
            //设置车号
            spot.setCarNo(carNo);
            //设置创建人
            spot.setCreateManName(name);
            //设置创建时间
            spot.setCreateTime(date);
            //创建一条新数据时，默认将传过来的重量、站点等参数保存到1号（一共有5个数据）
            //设置重量
            spot.setWeightNum1(weight);
            //设置秤点称量时间
            spot.setWeightDate1(date);
            //设置秤点名
            spot.setBaseSpotName1(spotName);
            //设置秤点编号
            spot.setBaseSpotNo1(spotNo);
            //类型 断差:1
            spot.setCompareType("1");
            //将状态设置成 2：正使用
            spot.setValueFlag("2");
            //创建
            meterWorkCompareSpotService.insert(spot);

        }else{//有查询到相应的主键
            //通过主键查询该条数据
            List<MeterWorkCompareSpot> list = meterWorkCompareSpotService.queryByProperty("compareSpotId", COMPARE_SPOT_ID);
            //System.out.println(list);

            //正常情况下一个主键只能查询到一条数据，这里为了防止出现多条数据的情况，所以在此加入一个判断条件 出现错误，返回”数据库数据错误“
            if (list.size()>1||list == null||list.size()==0){
                return failed(null,"数据库数据错误");
            }

            //获取第一条数据（实际上也只有一条）
            MeterWorkCompareSpot spot = list.get(0);

            //提交类型为断差的数据时，必须保持所有秤点是一致的 通过秤点名和秤点编号判断 出错，返回”称重秤点与之前的秤点不一样“
            if (!spot.getBaseSpotNo1().equals(spotNo)||!spot.getBaseSpotName1().equals(spotName)){
                return failed(null,"称重秤点与之前的秤点不一样");
            }


            if (spot.getWeightNum5() == null||spot.getBaseSpotName5()==null){//第5个重量为空，表示在该条数据内还可以继续存储重量
                //设置更新时间
                spot.setUpdateTime(date);
                //设置更新操作人们姓名
                spot.setUpdateManName(name);
                //通过重量和站点名来判断
                if (spot.getWeightNum2()==null||spot.getBaseSpotName2()==null) {
                    //重量
                    spot.setWeightNum2(weight);
                    //称重时间
                    spot.setWeightDate2(date);
                    //秤点名
                    spot.setBaseSpotName2(spotName);
                    //秤点编号
                    spot.setBaseSpotNo2(spotNo);
                }else if (spot.getWeightNum3()==null||spot.getBaseSpotName3()==null){
                    spot.setWeightNum3(weight);
                    spot.setWeightDate3(date);
                    spot.setBaseSpotName3(spotName);
                    spot.setBaseSpotNo3(spotNo);
                }else if (spot.getWeightNum4()==null||spot.getBaseSpotName4()==null){
                    spot.setWeightNum4(weight);
                    spot.setWeightDate4(date);
                    spot.setBaseSpotName4(spotName);
                    spot.setBaseSpotNo4(spotNo);
                }else{
                    //注意即使存满了5条数据也没有修改VALUE_FLAG的值，仍保持为 2：正使用
                    //如果后期有需求再修改
                    spot.setWeightNum5(weight);
                    spot.setWeightDate5(date);
                    spot.setBaseSpotName5(spotName);
                    spot.setBaseSpotNo5(spotNo);
                }
                //更新数据
                meterWorkCompareSpotService.updateByPrimaryKey(spot);
            }else{//第5个重量不为空，表示在该条数据内已经存储了5条数据，不能在继续存储，返回”一个小时以内，已存在5条重量数据“
                return failed(null,"一个小时以内，已存在5条重量数据");
            }
        }

        if (weight == 0L){
            return success(null,"提交成功，请注意：传过来的重量为0");
        }

        //所有都没问题 返回提交成功
        return success(null,"提交成功");
    }

    @ApiOperation(value="查询结果", notes="查询断差结果")
    @GetMapping(value = "/queryByComparetype/{type}")
    public RESTfulResult queryByComparetype(@PathVariable String type){
        if ("0".equals(type)){
            List<MeterWorkCompareSpot> list = meterWorkCompareSpotService.queryAll();
            return success(list,"查询成功");
        }else if ("1".equals(type)){
            List<MeterWorkCompareSpot> list = meterWorkCompareSpotService.queryByCompareType(type);
            return success(list,"查询成功");
        }else if ("2".equals(type)){
            List<MeterWorkCompareSpot> list = meterWorkCompareSpotService.queryByCompareType(type);
            return success(list,"查询成功");
        }else{
            return failed("","参数传递错误");
        }

    }

}