package com.steerinfo.ems.trmunit.controller;

import com.steerinfo.auth.utils.JwtUtil;
import com.steerinfo.ems.Utils.DateUtils;
import com.steerinfo.ems.Utils.StrUtils;
import com.steerinfo.ems.trmactitem.service.ITRmActItemService;
import com.steerinfo.ems.trmcalpoint.service.ITRmCalpointService;
import com.steerinfo.ems.trmenergy.service.ITRmEnergyService;
import com.steerinfo.ems.trmunit.model.TRmUnit;
import com.steerinfo.ems.trmunit.service.ITRmUnitService;
import com.steerinfo.ems.trmworkprocmaterial.service.ITRmWorkprocMaterialService;
import com.steerinfo.ems.trmworkprocproduct.service.ITRmWorkprocProductService;
import com.steerinfo.framework.controller.BaseRESTfulController;
import com.steerinfo.framework.controller.RESTfulResult;
import com.steerinfo.framework.service.pagehelper.PageList;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * TRmUnit RESTful接口：
 * @author 王金涛
 * @version 1.0-SNAPSHORT 2019-10-11
 * 类描述
 * 修订历史：
 * 日期：2019-10-11
 * 作者：王金涛
 * 参考：
 * 描述：TRmUnit RESTful接口
 * @see null
 * @Copyright 湖南视拓信息技术股份有限公司. All rights reserved.
 */
@RestController
@RequestMapping("/${api.version}/trmunits")
public class TRmUnitController extends BaseRESTfulController {


    private static final Logger LOGGER = LoggerFactory.getLogger(TRmUnitController.class);

    @Autowired
    ITRmUnitService tRmUnitService;
    @Autowired
    ITRmWorkprocMaterialService tRmWorkprocMaterialService;
    @Autowired
    ITRmWorkprocProductService tRmWorkprocProductService;
    @Autowired
    ITRmEnergyService tRmEnergyService;
    @Autowired
    ITRmCalpointService tRmCalpointService;
    @Autowired
    ITRmActItemService tRmActItemService;

    @ApiOperation(value="获取列表", notes="分页查询")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
        @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    //@RequiresPermissions("trmunit:view")
    @GetMapping(value = "/")
    public RESTfulResult list(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
        PageList<TRmUnit> list = tRmUnitService.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("trmunit:view")
    @GetMapping(value = "/like/")
    public RESTfulResult listLike(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
        PageList<TRmUnit> list = tRmUnitService.queryLikeForPage(parmas, pageNum, pageSize);
        return success(list);
    }
    
    @ApiOperation(value="创建", notes="根据TRmUnit对象创建")
    @ApiImplicitParam(name = "tRmUnit", value = "详细实体tRmUnit", required = true, dataType = "TRmUnit")
    //@RequiresPermissions("trmunit:create")
    @PostMapping(value = "/")
    public RESTfulResult add(@ModelAttribute TRmUnit model){
        if(model.getId() == null || "".equals(model.getId())){
            return failed(null, "id不能为空！");
            //int maxid = tRmUnitService.getMaxId() == null ? 0 : Integer.parseInt(tRmUnitService.getMaxId());
            //model.setId(String.format("%03d", maxid + 1));
        }
        if(tRmUnitService.getById(model.getId()) != null){
            return failed(null, "id已存在，不能新增！");
        }
//        if("1".equals(model.getIsstd())){
//            model.setStdid(model.getId());
//        }
//        if(model.getStdid() == null || "".equals(model.getStdid())){
//            return failed(null, "公式标准id不能为空！");
//        }
//        if(model.getStdexp() == null || "".equals(model.getStdexp())){
//            model.setStdexp("1");
//        }
//        if(!StringUtils.isNumeric(model.getStdexp())){
//            return failed(null,"单位的折算公式只能输入正数！");
//        }
//        if(Double.parseDouble(model.getStdexp()) == 0){
//            return failed(null,"单位的折算公式不能为零！");
//        }
        model.setCreateman(JwtUtil.getUseridByToken());
        model.setCreatetime(DateUtils.getCurrentTimetoDate("yyyy-MM-dd HH:mm:ss"));
        TRmUnit tRmUnit = tRmUnitService.add(model);
        return success(tRmUnit);
    }

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

    @ApiOperation(value="更新详细信息", notes="根据url的id来指定更新对象，并根据传过来的tRmUnit信息来更新详细信息")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String"),
        @ApiImplicitParam(name = "tRmUnit", value = "详细实体tRmUnit", required = true, dataType = "TRmUnit")
    })
    //@RequiresPermissions("trmunit:update")
    @PutMapping(value = "/{id}", produces  = "application/json;charset=UTF-8")
    public RESTfulResult update(@PathVariable String id, @RequestBody TRmUnit model){
//        if("1".equals(model.getIsstd())){
//            model.setStdid(model.getId());
//        }
//        if(model.getStdid() == null || "".equals(model.getStdid())){
//            return failed(null, "公式标准id不能为空！");
//        }
//        if(model.getStdexp() == null || "".equals(model.getStdexp())){
//            model.setStdexp("1");
//        }
//        if(!StringUtils.isNumeric(model.getStdexp())){
//            return failed(null,"单位的折算公式只能输入正数！");
//        }
//        if(Double.parseDouble(model.getStdexp()) == 0){
//            return failed(null,"单位的折算公式不能为零！");
//        }
        LOGGER.info("计量单位维护表修改前数据是" + tRmUnitService.getById(id).toString());
        model.setId(id);
        TRmUnit tRmUnit = tRmUnitService.modify(model);
        LOGGER.info("计量单位维护表修改后数据是" + tRmUnit.toString());
        return success(tRmUnit);
    }

    @ApiOperation(value="删除", notes="根据用户ID来指定删除对象")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    //@RequiresPermissions("trmunit:delete")
    @DeleteMapping(value = "/{id}")
    public RESTfulResult delete(@PathVariable String id){
        int failnum = 0;
        String failmsg = "";
        List<String> Ids = Arrays.asList(id.split(","));
        for(int i = 0;i < Ids.size();i++) {
            if(tRmEnergyService.queryByProperty("unitid", Ids.get(i)).size() != 0){
                failnum++;
                failmsg += Ids.get(i) + "在能介信息维护界面存在关系，请先删除对应关系！";
                continue;
            }
            if(tRmCalpointService.queryByProperty("unitid", Ids.get(i)).size() != 0){failnum++;
                failmsg += Ids.get(i) + "在计量点信息维护界面存在关系，请先删除对应关系！";
                continue;
            }
            if(tRmWorkprocMaterialService.queryByProperty("unitid", Ids.get(i)).size() != 0){
                failnum++;
                failmsg += Ids.get(i) + "在工序与原材料关联维护界面存在关系，请先删除对应关系！";
                continue;
            }
            if(tRmWorkprocProductService.queryByProperty("unitid", Ids.get(i)).size() != 0){
                failnum++;
                failmsg += Ids.get(i) + "在工序与产品关联界面存在关系，请先删除对应关系！";
                continue;
            }
            if(tRmActItemService.queryByProperty("unitid", Ids.get(i)).size() != 0){
                failnum++;
                failmsg += Ids.get(i) + "在实绩项目维护界面存在关系，请先删除对应关系！";
                continue;
            }
            LOGGER.info("计量单位维护表要删除的第" + (i + 1) + "条数据是" + tRmUnitService.getById(Ids.get(i)).toString());
            tRmUnitService.delete(Ids.get(i));
        }
        if(failnum > 0){
            LOGGER.info(JwtUtil.getUseridByToken() + "本次共删除" + Ids.size() + "条数据,其中成功" + (Ids.size() - failnum) + "条,失败" + failnum + "条,失败原因:" + failmsg);
            return failed(null, "本次共删除" + Ids.size() + "条数据,其中成功" + (Ids.size() - failnum) + "条,失败" + failnum + "条,失败原因：" + failmsg);
        }
        return success();
    }

    @ApiOperation(value = "获取Id 和 Name",notes = "获取下拉框得值(可传参数isstd（是否标准单位）)")
    @GetMapping(value = "/getIdAndName")
    public RESTfulResult getIdAndName(@RequestParam HashMap params){
        List<TRmUnit> idAndName = tRmUnitService.getIdAndName(params);
        return success(idAndName);
    }

    @ApiOperation(value="批量更新详细信息", notes="根据传过来的tRmUnit数组信息来更新详细信息")
    @ApiImplicitParam(name = "tRmUnit", value = "详细实体tRmUnit", required = true, dataType = "TRmUnit")
    //@RequiresPermissions("trmunit:update")
    @PutMapping(value = "/", produces  = "application/json;charset=UTF-8")
    public RESTfulResult batchupdate(@RequestBody TRmUnit[] model){
        int failnum = 0;
        List<String> list = new ArrayList<>();
        for(int i = 0;i < model.length;i++){
            try {
                LOGGER.info("计量单位维护修改的第" + (i + 1) + "条数据:");
                LOGGER.info("计量单位维护修改前数据是" + tRmUnitService.getById(model[i].getId()).toString());
                model[i].setUpdateman(JwtUtil.getUseridByToken());
                TRmUnit tRmUnit = tRmUnitService.modify(model[i]);
                LOGGER.info("计量单位维护修改后数据是" + tRmUnit.toString());
            }
            catch(Exception e){
                failnum++;
                list.add(model[i].getId());
                LOGGER.error("计量单位维护修改在第" + (i + 1) + "条数据出现错误,错误原因是" + e + ",id是" + model[i].getId());
            }
        }
        if(failnum > 0){
            LOGGER.info("本次共修改" + model.length + "条数据,其中成功" + (model.length - failnum) + "条,失败" + failnum + "条,失败的数据id:" + list.toString());
            return success(list,"51","本次共修改" + model.length + "条数据,其中成功" + (model.length - failnum) + "条,失败" + failnum + "条");
        }
        return success();
    }

}
