package com.steerinfo.ems.tcm0312.controller;

import com.steerinfo.auth.utils.JwtUtil;
import com.steerinfo.ems.Utils.DateUtils;
import com.steerinfo.ems.ifmesemswatermonitor.model.IfMesEmsWatermonitor;
import com.steerinfo.ems.ifmesemswatermonitor.service.IIfMesEmsWatermonitorService;
import com.steerinfo.ems.tcm0310.model.TCm0310;
import com.steerinfo.ems.tcm0310.service.ITCm0310Service;
import com.steerinfo.ems.tcm0311.model.TCm0311;
import com.steerinfo.ems.tcm0311.service.ITCm0311Service;
import com.steerinfo.ems.tcm0312.model.TCm0312;
import com.steerinfo.ems.tcm0312.model.VWaterPlanId;
import com.steerinfo.ems.tcm0312.service.ITCm0312Service;
import com.steerinfo.ems.tcm0313.controller.TCm0313Controller;
import com.steerinfo.ems.tcm0313.model.TCm0313;
import com.steerinfo.ems.tcm0313.service.ITCm0313Service;
import com.steerinfo.ems.tcm0318.model.TCm0318;
import com.steerinfo.ems.tcm0318.service.ITCm0318Service;
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.*;

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

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

    @Autowired
    ITCm0312Service tCm0312Service;
    @Autowired
    TCm0313Controller tCm0313Controller;
    @Autowired
    ITCm0313Service tCm0313Service;
    @Autowired
    ITCm0318Service tCm0318Service;
    @Autowired
    ITCm0310Service tCm0310Service;
    @Autowired
    ITCm0311Service tCm0311Service;
    @Autowired
    private IIfMesEmsWatermonitorService ifMesEmsWatermonitorService;

    @ApiOperation(value="获取列表", notes="分页查询")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
        @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    //@RequiresPermissions("tcm0312:view")
    @GetMapping(value = "/")
    public RESTfulResult list(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
        PageList<TCm0312> list = tCm0312Service.queryForPage(parmas, pageNum, pageSize);
        return success(list);
    }
    
    @ApiOperation(value="创建", notes="根据TCm0312对象创建")
    @ApiImplicitParam(name = "tCm0312", value = "详细实体tCm0312", required = true, dataType = "TCm0312")
    //@RequiresPermissions("tcm0312:create")
    @PostMapping(value = "/")
    public RESTfulResult add(@ModelAttribute TCm0312 model){
        Map<String, Object> param = new HashMap<>();
        param.put("creatyear", model.getCreatyear());
        param.put("sitem", model.getSitem());
        param.put("powermonitorname", model.getPowermonitorname());
        param.put("systemname", model.getSystemname());
        param.put("timegranid", model.getTimegranid());
        if(tCm0312Service.query(param).size() > 0){
            return failed(null, "该计划已存在，不能继续生成！");
        }
        if(model.getDatasource() == null || "".equals(model.getDatasource())){
            return failed(null, "数据来源不能为空！");
        }
        if(model.getCreatyear() == null || "".equals(model.getCreatyear())){
            model.setCreatyear(DateUtils.getCurrentTime("yyyy"));
        }
        TCm0310 update0310 = new TCm0310();
        TCm0311 update0311 = new TCm0311();
        List<String> Sitems = Arrays.asList(model.getSitem().split(","));
        for(int i = 0;i < Sitems.size();i++){
            update0310.setWatercode(model.getSystemname());
            update0310.setUsestate("Use");
            tCm0310Service.modify(update0310);

            update0311.setItemcode(Sitems.get(i));
            update0311.setCheckstate("Check");
            TCm0311 tCm0311 = tCm0311Service.modify(update0311);

            model.setSitem(Sitems.get(i));
            model.setUnit(tCm0311.getUnit());
            Long maxid = tCm0312Service.getMaxId() == null ? 0 : Long.parseLong(tCm0312Service.getMaxId());
            model.setRecordid(String.valueOf(maxid + 1));
            model.setCreateman(JwtUtil.getUseridByToken());
            TCm0312 tCm0312 = tCm0312Service.add(model);

            //当监测指标不存在，生成对应的监测指标
            if(tCm0313Service.query(param).size() == 0) {
                TCm0313 tCm0313 = new TCm0313();
                tCm0313.setCreatyear(tCm0312.getCreatyear());
                tCm0313.setPowerdetecdepartment(tCm0312.getDetectiondepartment());
                tCm0313.setPowermonitorname(tCm0312.getPowermonitorname());
                tCm0313.setSystemname(tCm0312.getSystemname());
                tCm0313.setRecordid(tCm0312.getRecordid());
                tCm0313.setItemname(tCm0312.getSitem());
                tCm0313.setUnit(tCm0312.getUnit());
                tCm0313.setLowerlimit("0");
                tCm0313.setUpperlimit("100");
                tCm0313Service.add(tCm0313);
            }
        }
        return success();
    }

    @ApiOperation(value="更新详细信息", notes="根据url的id来指定更新对象，并根据传过来的tCm0312信息来更新详细信息")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String"),
        @ApiImplicitParam(name = "tCm0312", value = "详细实体tCm0312", required = true, dataType = "TCm0312")
    })
    //@RequiresPermissions("tcm0312:update")
    @PutMapping(value = "/{id}", produces  = "application/json;charset=UTF-8")
    public RESTfulResult update(@PathVariable String id, @RequestBody TCm0312 model){
        Map<String, Object> param = new HashMap<>();
        param.put("creatyear", model.getCreatyear());
        param.put("sitem", model.getSitem());
        param.put("powermonitorname", model.getPowermonitorname());
        param.put("systemname", model.getSystemname());
        param.put("timegranid", model.getTimegranid());
        model.setRecordid(id);
        TCm0312 before = tCm0312Service.getById(id);
        LOGGER.info("水质监测计划表修改前的数据是" + before.toString());
        model.setUpdateman(JwtUtil.getUseridByToken());
        TCm0312 tCm0312 = tCm0312Service.modify(model);
        LOGGER.info("水质监测计划表修改后的数据是" + tCm0312.toString());

        //监测指标制定修改
        TCm0313 tCm0313 = new TCm0313();
        tCm0313.setUnit(tCm0312.getUnit());
        tCm0313.setRecordid(tCm0312.getRecordid());
        tCm0313.setSystemname(tCm0312.getSystemname());
        tCm0313.setPowerdetecdepartment(tCm0312.getDetectiondepartment());
        tCm0313.setItemname(tCm0312.getSitem());
        tCm0313.setCreatyear(tCm0312.getCreatyear());
        tCm0313.setPowermonitorname(tCm0312.getPowermonitorname());
        LOGGER.info("水质监测指标表修改前的数据是" + tCm0313.toString());
        TCm0313 after = tCm0313Service.modify(tCm0313);
        LOGGER.info("水质监测指标表修改后的数据是" + after.toString());

        if (tCm0312Service.queryByProperty("systemname", model.getSystemname()).size() == 0) {
            TCm0310 tCm0310 = new TCm0310();
            tCm0310.setDetectiondepartment(model.getDetectiondepartment());
            tCm0310.setWatercode(model.getSystemname());
            tCm0310.setUsestate("NoUse");
            tCm0310Service.modify(tCm0310);
        }
        if (tCm0312Service.queryByProperty("sitem", model.getSitem()).size() == 0) {
            TCm0311 tCm0311 = new TCm0311();
            tCm0311.setItemcode(model.getSitem());
            tCm0311.setCheckstate("NoCheck");
            tCm0311Service.modify(tCm0311);
        }
        return success(tCm0312);
    }

    @ApiOperation(value="删除", notes="根据url的recordid来指定删除对象")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    @DeleteMapping(value = "/{id}")
    public RESTfulResult delete(@PathVariable String id){
        Map<String, Object> parameters = new HashMap();
        Map<String, Object> parameters2 = new HashMap();
        String[] idarray = id.split(",");
        List<String> Ids = new ArrayList<>();
        for(int i = 0;i < idarray.length;i++) {
            Ids.add(idarray[i]);
        }
        for(int i = 0;i < Ids.size();i++){
            TCm0312 model = tCm0312Service.getById(Ids.get(i));
            LOGGER.info("水质监测计划表要删除的数据是" + model.toString());
            parameters.put("watercode",model.getSystemname());
            parameters2.put("itemcode",model.getSitem());

            LOGGER.info("水质监测指标表要删除的数据是" + tCm0313Service.getById(Ids.get(i)).toString());
            tCm0313Service.delete(Ids.get(i));
            tCm0312Service.delete(Ids.get(i));

            if (tCm0312Service.queryByProperty("systemname", model.getSystemname()).size() == 0) {
                TCm0310 tCm0310 = new TCm0310();
                tCm0310.setDetectiondepartment(model.getDetectiondepartment());
                tCm0310.setWatercode(model.getSystemname());
                tCm0310.setUsestate("NoUse");
                tCm0310Service.modify(tCm0310);
            }
            if (tCm0312Service.queryByProperty("sitem", model.getSitem()).size() == 0) {
                TCm0311 tCm0311 = new TCm0311();
                tCm0311.setItemcode(model.getSitem());
                tCm0311.setCheckstate("NoCheck");
                tCm0311Service.modify(tCm0311);
            }
        }
        LOGGER.info("水质监测计划表共删除数据" + Ids.size() + "条。" );
        return success();
    }

    @ApiOperation(value="批量更新详细信息", notes="根据传过来的tCm0312数组信息来更新详细信息")
    @ApiImplicitParam(name = "tRmEnergy", value = "详细实体tCm0312", required = true, dataType = "TCm0312")
    //@RequiresPermissions("tcm0312:update")
    @PutMapping(value = "/", produces  = "application/json;charset=UTF-8")
    public RESTfulResult batchupdate(@RequestBody TCm0312[] model){
        int failnum = 0;
        String failmsg = "";
        List<String> errorid = new ArrayList<>();
        for(int i = 0;i < model.length;i++){
            try {
                Map<String, Object> param = new HashMap<>();
                param.put("creatyear", model[i].getCreatyear());
                param.put("sitem", model[i].getSitem());
                param.put("powermonitorname", model[i].getPowermonitorname());
                param.put("systemname", model[i].getSystemname());
                param.put("timegranid", model[i].getTimegranid());
                TCm0312 before = tCm0312Service.getById(model[i].getRecordid());
                LOGGER.info("水质监测计划表修改前的数据是" + before.toString());
                model[i].setUpdateman(JwtUtil.getUseridByToken());
                TCm0312 tCm0312 = tCm0312Service.modify(model[i]);
                LOGGER.info("水质监测计划表修改后的数据是" + tCm0312.toString());

                //监测指标制定修改
                TCm0313 tCm0313 = new TCm0313();
                tCm0313.setUnit(tCm0312.getUnit());
                tCm0313.setRecordid(tCm0312.getRecordid());
                tCm0313.setSystemname(tCm0312.getSystemname());
                tCm0313.setPowerdetecdepartment(tCm0312.getDetectiondepartment());
                tCm0313.setItemname(tCm0312.getSitem());
                tCm0313.setCreatyear(tCm0312.getCreatyear());
                tCm0313.setPowermonitorname(tCm0312.getPowermonitorname());
                LOGGER.info("水质监测指标表修改前的数据是" + tCm0313.toString());
                TCm0313 after = tCm0313Service.modify(tCm0313);
                LOGGER.info("水质监测指标表修改后的数据是" + after.toString());

                if (tCm0312Service.queryByProperty("systemname", model[i].getSystemname()).size() == 0) {
                    TCm0310 tCm0310 = new TCm0310();
                    tCm0310.setDetectiondepartment(model[i].getDetectiondepartment());
                    tCm0310.setWatercode(model[i].getSystemname());
                    tCm0310.setUsestate("NoUse");
                    tCm0310Service.modify(tCm0310);
                }
                if (tCm0312Service.queryByProperty("sitem", model[i].getSitem()).size() == 0) {
                    TCm0311 tCm0311 = new TCm0311();
                    tCm0311.setItemcode(model[i].getSitem());
                    tCm0311.setCheckstate("NoCheck");
                    tCm0311Service.modify(tCm0311);
                }
            }
            catch(Exception e){
                failnum++;
                errorid.add(model[i].getId());
                failmsg += "能介信息维护修改在第" + (i + 1) + "条数据出现错误,错误原因是" + e + ",id是" + model[i].getId();
            }
        }
        if(failnum > 0){
            LOGGER.info("本次共修改" + model.length + "条数据,其中成功" + (model.length - failnum) + "条,失败" + failnum + "条,失败原因:" + failmsg);
            return success(errorid,"51","本次共修改" + model.length + "条数据,其中成功" + (model.length - failnum) + "条,失败" + failnum + "条");
        }
        return success();
    }

    @ApiOperation(value="水质监测数据录入的检测计划下拉框", notes="查询id和name")
    @GetMapping(value = "/getplanidandname/")
    public RESTfulResult getPlanNameAndId(){
        List<VWaterPlanId> vWaterPlanId = tCm0312Service.getPlanNameAndId();
        System.out.println(vWaterPlanId);
        return success(vWaterPlanId);
    }

    /**
     * 将IF_MES_EMS_WATERMONITOR中未读取的数据进行处理，将数据保存至T_CM_0318
     */
    @ApiOperation(value="从MES获取检测数据", notes="将IF_MES_EMS_WATERMONITOR中未读取的数据进行处理，将数据保存至T_CM_0318")
    @GetMapping(value = "/getmesdata/")
    public void synchronousData(){
        int success = 0;
        int failure = 0;
        int updatesize = 0;
        List<IfMesEmsWatermonitor> list = ifMesEmsWatermonitorService.getNewData();
        for(int i = 0;i < list.size();i++){
            IfMesEmsWatermonitor model = list.get(i);
            Map<String, Object> params = new HashMap<>();
            params.put("systemname", model.getMaterialno());
            params.put("sitem", model.getItemcode());
            params.put("datadate", model.getInputtime());
            params.put("datasource", "MES");
            if(tCm0312Service.query(params).size() > 0){
                if(!model.getJudgetime().substring(0,10).equals(model.getInputtime().substring(0,10))){
                    List<TCm0318> updatetcm0318 = tCm0318Service.getByCode(params);
                    if(updatetcm0318.size() == 1){
                        LOGGER.info("[更改][水质监测数据更改]" + DateUtils.getCurrentTime("yyyy-MM-dd HH:mm:ss") + " ：T_CM_0318表中数据将要更新;");
                        LOGGER.info("将要更改的原数据项为：" + updatetcm0318.get(0).toString());
                        tCm0318Service.deleteByParams(params);
                        updatesize ++;
                    }
                    else if(updatetcm0318.size() < 1){
                        failure++;
                        LOGGER.error("[原数据不存在，无法修改]" + DateUtils.getCurrentTime("yyyy-MM-dd HH:mm:ss") + " ：IF_MES_EMS_WATERMONITOR中联合主键为(检测时间:" + model.getInputtime() + ",物料编号:" + model.getMaterialno() + ",监测项编号:" + model.getItemcode() + "),的数据在T_CM_0318中未找到对应关系;( 检测时间:" + model.getInputtime() + "系统名称:" + model.getMaterialname() + "检测时间:" + model.getItemcode() + ")");
                        continue;
                    }
                    else {
                        failure++;
                        LOGGER.error("[出现多条数据，无法修改]" + DateUtils.getCurrentTime("yyyy-MM-dd HH:mm:ss") + " ：IF_MES_EMS_WATERMONITOR中联合主键为(检测时间:" + model.getInputtime() + ",物料编号:" + model.getMaterialno() + ",监测项编号:" + model.getItemcode() + "),的数据在T_CM_0318中找到" + tCm0318Service.getByCode(params).size() + "条对应关系:");
                        for(int j = 0;j < updatetcm0318.size();j++){
                            LOGGER.error(updatetcm0318.get(j).toString());
                        }
                        continue;
                    }
                }
                if(tCm0318Service.getByCode(params) == null){
                    failure++;
                    LOGGER.error("[水质监测数据已存在，无法新增]" + DateUtils.getCurrentTime("yyyy-MM-dd HH:mm:ss") + " ：IF_MES_EMS_WATERMONITOR中联合主键为(检测时间:" + model.getInputtime() + ",物料编号:" + model.getMaterialno() + ",监测项编号:" + model.getItemcode() + "),的数据在T_CM_0318中找到" + tCm0318Service.getByCode(params).size() + "条对应关系:");
                    continue;
                }
                LOGGER.info("[新增][水质监测数据新增]" + DateUtils.getCurrentTime("yyyy-MM-dd HH:mm:ss") + " ：T_CM_0318表中数据将要新增;");
                TCm0318 tCm0318 = new TCm0318();
                TCm0312 tCm0312 = tCm0312Service.getByParams(params);
                tCm0318.setDetectiondepartment(tCm0312.getDetectiondepartment());
                tCm0318.setSystemname(tCm0312.getSystemname());
                tCm0318.setSitem(tCm0312.getSitem());
                tCm0318.setPowermonitorname(tCm0312.getPowermonitorname());
                tCm0318.setMonitordate(model.getInputtime().substring(0, 10));
                tCm0318.setDatadate(model.getInputtime().substring(11));
                tCm0318.setMonitoringvalue(Double.parseDouble(model.getTestresult()));
                tCm0318.setUnit(tCm0312.getUnit());
                tCm0318.setPlanid(tCm0312.getRecordid() + tCm0312.getSitem());
                tCm0318.setAnalyst(model.getRecorder());
                tCm0318.setDatastate(model.getSampletype());
                tCm0318.setNote(model.getMemo());
                tCm0318.setDatasource("MES");
                tCm0318.setInsertTime(DateUtils.getCurrentTime("yyyy-MM-dd HH:mm:ss"));
                tCm0318.setBatchno("1");
                tCm0318.setTimegranid("DAY");
                tCm0318Service.add(tCm0318);
                success ++;
            }
            else{
                failure++;
                LOGGER.error("[水质监测计划不存在]" + DateUtils.getCurrentTime("yyyy-MM-dd HH:mm:ss") + " ：IF_MES_EMS_WATERMONITOR中 ( 物料名称:" + model.getMaterialno() + ", 物料编号:" + model.getItemcode() + " 的数据在T_CM_0310中未找到对应关系:( 系统名称:" + model.getMaterialno() + ", 检测项目id:" + model.getItemcode() + ")");
            }
        }
        LOGGER.info("[水质监测数据添加完毕]" + DateUtils.getCurrentTime("yyyy-MM-dd HH:mm:ss") + "：数据添加成功" + (success + updatesize) + "条(其中修改数据为" + updatesize + "条)，失败" + failure + "条;");
    }

    /**
     * 根据监测计划生成需要人工录入的监测数据
     */
    @ApiOperation(value="生成人工录入的监测数据", notes="根据监测计划生成需要人工录入的监测数据")
    @GetMapping(value = "/getmanualdata/")
    public void getmanualdata(){
        Map<String, Object> param = new HashMap<>();
        param.put("creatyear", DateUtils.getCurrentTime("yyyy"));
        param.put("timegranid", "DAY");
        param.put("datasource", "MANUAL");
        List<TCm0312> daylist = tCm0312Service.query(param);
        for(int i = 0;i < daylist.size();i++){
            TCm0318 daydata = new TCm0318();
            daydata.setPlanid(daylist.get(i).getRecordid() + daylist.get(i).getSitem());
            daydata.setSitem(daylist.get(i).getSitem());
            daydata.setDetectiondepartment(daylist.get(i).getDetectiondepartment());
            daydata.setSystemname(daylist.get(i).getSystemname());
            daydata.setSitem(daylist.get(i).getSitem());
            daydata.setPowermonitorname(daylist.get(i).getPowermonitorname());
            daydata.setTimegranid("DAY");
            daydata.setDatasource(daylist.get(i).getDatasource());
            daydata.setUnit(daylist.get(i).getUnit());
            daydata.setInsertTime(DateUtils.getCurrentTime("yyyy-MM-dd HH:mm:ss"));
            daydata.setMonitordate(DateUtils.getCurrentTime("yyyy-MM-dd"));
            daydata.setDatadate(DateUtils.getCurrentTime("HH:mm:ss"));
            for(int j = 1;j <= Integer.parseInt(daylist.get(i).getDetectionf());j++){
                daydata.setBatchno(String.valueOf(j));
                tCm0318Service.add(daydata);
            }
        }
        if(DateUtils.isFirstDayOfMonth(new Date())){
            param.put("timegranid", "MONTH");
            List<TCm0312> mouthlist = tCm0312Service.query(param);
            for(int m = 0;m < daylist.size();m++){
                TCm0318 monthdata = new TCm0318();
                monthdata.setPlanid(daylist.get(m).getRecordid() + daylist.get(m).getSitem());
                monthdata.setSitem(daylist.get(m).getSitem());
                monthdata.setDetectiondepartment(daylist.get(m).getDetectiondepartment());
                monthdata.setSystemname(daylist.get(m).getSystemname());
                monthdata.setSitem(daylist.get(m).getSitem());
                monthdata.setPowermonitorname(daylist.get(m).getPowermonitorname());
                monthdata.setTimegranid("MONTH");
                monthdata.setDatasource(daylist.get(m).getDatasource());
                monthdata.setUnit(daylist.get(m).getUnit());
                monthdata.setInsertTime(DateUtils.getCurrentTime("yyyy-MM-dd HH:mm:ss"));
                monthdata.setMonitordate(DateUtils.getCurrentTime("yyyy-MM-dd"));
                monthdata.setDatadate(DateUtils.getCurrentTime("HH:mm:ss"));
                for(int n = 1;n <= Integer.parseInt(daylist.get(m).getDetectionf());n++){
                    monthdata.setBatchno(String.valueOf(n));
                    tCm0318Service.add(monthdata);
                }
            }
        }
    }

}
