package com.steerinfo.meterwork.meterworkcomparespotscale.controller;

import com.steerinfo.framework.controller.BaseRESTfulController;
import com.steerinfo.framework.controller.RESTfulResult;
import com.steerinfo.framework.service.pagehelper.PageList;
import com.steerinfo.framework.utils.base.StringUtils;
import com.steerinfo.framework.utils.base.annotation.NotNull;
import com.steerinfo.framework.utils.collection.ListUtils;
import com.steerinfo.meterwork.meterworkcomparespot.model.MeterWorkCompareSpot;
import com.steerinfo.meterwork.meterworkcomparespot.service.IMeterWorkCompareSpotService;
import com.steerinfo.meterwork.meterworkcomparespotscale.model.MeterWorkCompareSpotScale;
import com.steerinfo.meterwork.meterworkcomparespotscale.service.IMeterWorkCompareSpotScaleService;
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.*;

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

    @Autowired
    IMeterWorkCompareSpotScaleService meterWorkCompareSpotScaleService;
    @Autowired
    IMeterWorkCompareSpotService meterWorkCompareSpotService;


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

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

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

    @ApiOperation(value="删除", notes="根据url的id来指定删除对象")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    //@RequiresPermissions("meterworkcomparespotscale: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);
			  meterWorkCompareSpotScaleService.delete(ids);
    	}
      return success();
    }

    @ApiOperation(value="提交预约", notes="新增比对预约")
    @PostMapping(value = "/makeAnAppointment" ,produces  = "application/json;charset=UTF-8")
    public RESTfulResult makeAnAppointment(@RequestBody HashMap<String,Object> map){

        //车号
        String carNo = null;
        //重量
        Long weight = 0L;
        //操作人姓名
        String name = null;
        //秤点名
        String spotName = null;
        //秤点编号
        String spotNo = null;
        //预约次数
        Long num = 0L;

        //获取参数
        //当参数缺少时会向返回 “参数不全或错误“
        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();
            num = Long.valueOf(map.get("num").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");
        }

        //提交预约时，最大预约次数为4
        //提交预约的同时也会向METER_WORK_COMPARE_SPOT表插入一条数据
        //最大存储数据量(5) - 已存储量(1) = 4
        //提示：”预约次数不允许超过最大值4“
        if (num>4){
            return failed(null,"预约次数不允许超过最大值4");
        }

        if (num < 1){
            return failed(null,"预约次数不允许小于最小值1");
        }

        //1、判断该车号在过去一天内是否存在未使用的预约
        String compareSpotScaleId = meterWorkCompareSpotScaleService.isExistWithinOneDay(carNo);

        if (compareSpotScaleId == null){//不存在未使用的预约 创建预约
            //向METER_WORK_COMPARE_SPOT插入数据
            MeterWorkCompareSpot spot = new MeterWorkCompareSpot();
            //主键
            spot.setCompareSpotId(meterWorkCompareSpotService.creatCompareSpotId());
            //车号
            spot.setCarNo(carNo);
            //称重日期
            spot.setWeightDate1(date);
            //重量
            spot.setWeightNum1(weight);
            //秤点名称
            spot.setBaseSpotName1(spotName);
            //秤点编号
            spot.setBaseSpotNo1(spotNo);
            //类型 较秤：2
            spot.setCompareType("2");
            //创建时间
            spot.setCreateTime(date);
            //创建人
            spot.setCreateManName(name);
            //状态 默认为2 即使5条数据满了以后也不改变其状态
            spot.setValueFlag("2");

            //向METER_WORK_COMPARE_SPOT_SCALE插入数据
            MeterWorkCompareSpotScale scale = new MeterWorkCompareSpotScale();
            //预约主键
            scale.setCompareSpotScaleId(meterWorkCompareSpotScaleService.creatCompareSpotScaleId());
            //预约次数
            scale.setNum(num);
            //已使用的次数
            scale.setUsedNum(0L);
            //创建时状态为：未使用：1
            //注意与上面的状态区别
            //当使用次数与预约次数相等时，该状态会变成 已使用：2
            scale.setValueFlag("1");
            //创建时间
            scale.setCreateTime(date);
            //车号
            scale.setCarNo(carNo);
            //创建人姓名
            scale.setCreateManName(name);
            //添加预约主键
            spot.setScaleNo(scale.getCompareSpotScaleId());
            //存入数据库
            meterWorkCompareSpotScaleService.creatSpotAndScale(spot,scale);

        }else {//存在未使用的预约 提示：”不允许存在重复比对预约“
            return success(null,"不允许存在重复比对预约");
        }

        //执行完成后，提示：”预约成功“
        return success(null,"预约成功");
    }

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

        //车号
        String carNo = null;
        //重量
        Long weight = 0L;
        //姓名
        String name = null;
        //秤点名
        String spotName = null;
        //秤点编号
        String spotNo = null;
        //预约编号
        String scaleNo = 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();
            scaleNo = map.get("scaleNo").toString();
        }catch (Exception e){
            return failed(null,"参数不全或错误");
        }
        Date date = new Date();

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

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

        //查看预约号是否可用
        MeterWorkCompareSpotScale scale = null;
        try {
            scale = meterWorkCompareSpotScaleService.queryByProperty("compareSpotScaleId", scaleNo).get(0);
            //System.out.println(scale);
        }catch (Exception e){
            return failed("预约号错误或不存在");
        }

        //查看该预约是否已经用完，用完：返回：”比对次数已经用完，请重新比对预约“
        if (scale.getValueFlag().equals("2")){
            return failed(null,"比对次数已经用完，请重新比对预约");
        }

        //防止预约的车号与传过来的车号不一致
        if (!scale.getCarNo().equals(carNo)){
            return failed(null,"预约号与车号不匹配，请检查");
        }

        //使用次数 + 1
        scale.setUsedNum(scale.getUsedNum() + 1);
        //判断是不是最后一次
        if (scale.getUsedNum() == scale.getNum()){
            //状态 已用完：2
            scale.setValueFlag("2");
        }

        //通过预约号去METER_WORK_COMPARE_SPOT中查询
        //正常来说，预约号与METER_WORK_COMPARE_SPOT表是一一对应的
        MeterWorkCompareSpot spot = null;
        try {
            spot = meterWorkCompareSpotService.queryByProperty("scaleNo", scaleNo).get(0);
        }catch (Exception e){
            return failed(null,"METER_WORK_COMPARE_SPOT表中没有该预约号");
        }
        //判断该数据填到哪里
        if (spot.getWeightNum2() == null||spot.getBaseSpotName2() == null){
            //重量
            spot.setWeightNum2(weight);
            //秤点编号
            spot.setBaseSpotNo2(spotNo);
            //称重时间
            spot.setWeightDate2(date);
            //称点名
            spot.setBaseSpotName2(spotName);
        }else if (spot.getWeightNum3() == null||spot.getBaseSpotName3() == null){
            spot.setWeightNum3(weight);
            spot.setBaseSpotNo3(spotNo);
            spot.setWeightDate3(date);
            spot.setBaseSpotName3(spotName);
        }else if (spot.getWeightNum4() == null||spot.getBaseSpotName4() == null){
            spot.setWeightNum4(weight);
            spot.setBaseSpotNo4(spotNo);
            spot.setWeightDate4(date);
            spot.setBaseSpotName4(spotName);
        }else if (spot.getWeightNum5() == null||spot.getBaseSpotName5() == null){
            spot.setWeightNum5(weight);
            spot.setBaseSpotNo5(spotNo);
            spot.setWeightDate5(date);
            spot.setBaseSpotName5(spotName);
        }
        //更新时间
        spot.setUpdateTime(date);
        //更新操作人
        spot.setUpdateManName(name);
        //更新
        meterWorkCompareSpotService.updateSpotAndScale(scale,spot);

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

        //返回：”添加成功“
        return success(null,"添加成功");
    }

    @ApiOperation(value = "查询预约号",notes = "通过车号查询24小时以内未使用完的预约号")
    @GetMapping(value = "/getScaleNo" )
    public RESTfulResult getScaleNo(@RequestParam String carNo){
        String scaleId = meterWorkCompareSpotScaleService.isExistWithinOneDay(carNo);
        if (scaleId == null){
            return success(null,"不存在24小时内未使用的预约");
        }else{
            return success((Object) scaleId,"存在24小小时内未使用得到预约");
        }

    }

    @ApiOperation(value = "查询预约",notes = "查询24以内所有预约")
    @GetMapping(value = "/getALLScaleNo")
    public RESTfulResult getAllScaleNo(){
        List<MeterWorkCompareSpotScale> allScaleNo = meterWorkCompareSpotScaleService.getAllScaleNo();
        return success(allScaleNo,"查询成功");
    }

    @ApiOperation(value = "强制取消预约",notes = "通过预约号将未完成的预约强制取消")
    @PostMapping(value = "/cancelByScaleNo")
    public RESTfulResult cancelByScaleNo(@RequestBody MeterWorkCompareSpotScale model){
        String scaleNo = model.getCompareSpotScaleId();
        if(StringUtils.isEmpty(scaleNo)) {
            return failed(null,"预约编号为空，不允许操作");
        }
        //通过主键查询相应预约
        //按理来说 主键 与 预约 一一对应 不会存在两个
        MeterWorkCompareSpotScale scale = meterWorkCompareSpotScaleService.queryByProperty("compareSpotScaleId", scaleNo).get(0);
        if (scale == null){
            return failed(null,"未查询到该预约");
        }

        //状态 1 -> 未完成
        //状态 2 -> 完成
        if ("1".equals(scale.getValueFlag())){ //如果该预约 显示的状态是 未完成 状态
            //将该预约修改成 已完成 状态
            //不会修改使用的次数，保持原有次数，只修改状态
            scale.setValueFlag("2");
            meterWorkCompareSpotScaleService.updateByPrimaryKey(scale);
        }else{
            return failed(null,"该预约已使用完");
        }

        return success("强制取消成功");
    }
}
