package com.nantian.cloud.jly.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nantian.cloud.jly.entity.*;
import com.nantian.cloud.jly.service.CheckGaugesService;
import com.nantian.cloud.jly.service.ConfigureGaugeService;
import com.nantian.cloud.jly.service.InspectionDataService;
import com.nantian.sc.cloud.common.core.util.R;
import com.nantian.sc.cloud.common.log.annotation.SysLog;
import com.nantian.sc.cloud.common.security.service.ScUser;
import com.nantian.sc.cloud.common.security.util.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.xmlbeans.impl.piccolo.io.FileFormatException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;


/**
 * 能源计量器具
 *
 * @author
 * @date 2018-09-27 15:20:44
 */
@RestController
@AllArgsConstructor
@Api(value = "checkGauges", tags = "能源计量器具")
@RequestMapping("/checkGauges")
public class CheckGaugesController {
    private final CheckGaugesService checkGaugesService;

    private final InspectionDataService inspectionDataService;

    private final ConfigureGaugeService configureGaugeService;


    /**
     * 分页查询
     *
     * @param page        分页对象
     * @param checkGauges 计量器具
     * @return
     */
    @SysLog("查询能源计量器具")
    @ApiOperation(value = "查询能源计量器具", notes = "条件查询能源计量器具")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "checkGauges", value = "能源计量器具", required = false, dataType = "json", paramType = "path"),
            @ApiImplicitParam(name = "Page", value = "分页对象", required = false, dataType = "json", paramType = "path")
    })
    @GetMapping("/page")
    public R getcheckGaugesPage(Page page, CheckGauges checkGauges) {
        checkGauges.setDelFlag("1"); //查询未删除数据
        return R.ok(checkGaugesService.getPageScope(page, checkGauges));
        //return R.ok(checkGaugesService.page(page, Wrappers.query(checkGauges)));
    }


    /**
     * 信息
     *
     * @param checkGaugesId
     * @return R
     */
    @SysLog("通过ID查询能源计量器具")
    @ApiOperation(value = "通过ID查询能源计量器具", notes = "通过ID查询能源计量器具")
    @ApiImplicitParam(name = "checkGaugesId", value = "能源计量器具id", required = true, paramType = "path", dataType = "int")
    @GetMapping("/{checkGaugesId}")
    public R getById(@PathVariable("checkGaugesId") Integer checkGaugesId) {
        return R.ok(checkGaugesService.getById(checkGaugesId));
    }

    /**
     * 保存
     *
     * @param checkGauges
     * @return R
     */
    @SysLog("保存能源计量器具")
    @ApiOperation(value = "保存能源计量器具", notes = "新增能源计量器具")
    @ApiImplicitParam(name = "CheckGauges", value = "能源计量器具", required = true, dataType = "json", paramType = "path")
    @PostMapping("/save")
    public R save(@RequestBody CheckGauges checkGauges) {
        ScUser u = SecurityUtils.getUser();
        if (u.getId() != null) {
            checkGauges.setUserid(u.getId());
        }
        checkGauges.setDeptId(u.getDeptId());
        checkGauges.setDelFlag("1");
        checkGauges.setUpdateTime(new Date());
        return R.ok(checkGaugesService.save(checkGauges));
    }

    /**
     * 批量保存
     */
	/*@ApiOperation(value = "保存能源计量器具",notes = "新增能源计量器具")
	@ApiImplicitParam(name ="CheckGauges",value = "能源计量器具",required = true,dataType = "json",paramType = "path")
	@PostMapping("/saveList")
	public R saveList(@RequestBody List<CheckGauges> checkGaugesList) {
		ScUser u= SecurityUtils.getUser();
		List<CheckGauges> newList = new ArrayList<>();
		for (CheckGauges checkGauges : checkGaugesList) {
			if(u.getId()!=null){
				checkGauges.setUserid(u.getId());
			}
			checkGauges.setDelFlag("1");
			checkGauges.setUpdateTime(new Date());
			checkGauges.setDeptId(u.getDeptId());
			newList.add(checkGauges);
		}
		return R.ok(checkGaugesService.saveBatch(newList));
	}*/

    /**
     * 导入excel
     */
    @SysLog("能源计量器具导入excel")
    @PostMapping("excelImport")
    @ApiOperation(value = "导入excel", notes = "导入excel")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "文件", required = true, dataType = "file", paramType = "path"),
            @ApiImplicitParam(name = "checkPlanId", value = "审查计划id", required = true, dataType = "string", paramType = "path"),
            @ApiImplicitParam(name = "epc", value = "企业社会信用编码", required = true, dataType = "string", paramType = "path"),
            @ApiImplicitParam(name = "tableType", value = "类型  1，能源计量器具，2，进出用能单位能源计量器具，3，进出主要次级用能单位能源计量器具，" +
                    "4，主要用能设备能源计量器具，5、其他能源计量器具", required = true, dataType = "string", paramType = "path")
    })
    public R excelImport(MultipartFile file, BigInteger checkPlanId, String epc, String tableType) throws FileFormatException {
        if (checkPlanId == null) {
            return R.failed("审查计划id不能为空！");
        }
        if (epc == null || "".equals(epc)) {
            return R.failed("企业社会信用编码不能为空！");
        }
        if (tableType == null || "".equals(tableType)) {
            return R.failed("tableType不能为空！");
        }
        InspectionData inspectionData = inspectionDataService.getByPlanIdAndEpc(checkPlanId, epc);
        if (inspectionData == null) {
            return R.failed("没有查询到自查18项资料记录");
        } else {
//            if ("Y".equals(inspectionData.getEnergyMeasuringInstrumentsState())) {  //已审核
//                return R.failed("能源计量器具一览表已审核，不能进行增加、修改、删除操作！");
//            }
//            if ("Y".equals(inspectionData.getMeasuringInstrumentsState())) {  //已审核
//                return R.failed("进出用能单位能源计量器具一览表分表已审核，不能进行增加、修改、删除操作！");
//            }
//            if ("Y".equals(inspectionData.getSecondaryMeasuringInstrumentState())) {  //已审核
//                return R.failed("进出主要次级用能单位能源计量器具一览表分表已审核，不能进行增加、修改、删除操作！");
//            }
//            if ("Y".equals(inspectionData.getMainMeasuringInstrumentState())) {  //已审核
//                return R.failed("主要用能设备能源计量器具一览表分表已审核，不能进行增加、修改、删除操作！");
//            }
//            if ("Y".equals(inspectionData.getOtherMeasuringInstrumentsState())) {  //已审核
//                return R.failed("其他能源计量器具一览表分表已审核，不能进行增加、修改、删除操作！");
//            }
        }
        return checkGaugesService.excelImport(file, checkPlanId, epc, tableType, inspectionData);
    }


    /**
     * 批量新增
     */
    @SysLog("能源计量器具批量新增")
    @PostMapping("/saveBatch")
    @ApiOperation(value = "批量新增能源计量器具", notes = "批量新增能源计量器具")
    @ApiImplicitParam(name = "CheckGauges", value = "能源计量器具对象集合", required = true, dataType = "json", paramType = "path")
    public R saveBatch(@RequestBody String s) {
        JSONObject json = JSONObject.parseObject(s);
        String ss = json.getString("checkGauges");
        String mend = json.getString("mend");
        List<CheckGauges> checkGaugesList = (List<CheckGauges>) JSONArray.parseArray(ss, CheckGauges.class);
        //ist<CheckGauges> checkGaugesLis
        ScUser u = SecurityUtils.getUser();
        List<CheckGauges> newList = new ArrayList<>();
        BigInteger checkPlanId = null;
        String enterpriseCode = null;
        String tableType = null;
        for (CheckGauges checkGauge : checkGaugesList) {
            if (u.getId() != null) {
                checkGauge.setUserid(u.getId());
            }
            checkGauge.setDelFlag("1");
            checkGauge.setUpdateTime(new Date());
            checkGauge.setDeptId(u.getDeptId());
            newList.add(checkGauge);
            checkPlanId = checkGauge.getCheckPlanId();
            enterpriseCode = checkGauge.getEpc();
            tableType = checkGauge.getTableType();
        }
        InspectionData inspectionData = new InspectionData();
        inspectionData.setCheckPlanId(checkPlanId);
        inspectionData.setEnterpriseCode(enterpriseCode);
        inspectionData.setDelFlag("1");
        InspectionData oldData = inspectionDataService.getOne(Wrappers.query(inspectionData));
        if (oldData == null) {
            checkGaugesService.updateInspectionData(u, inspectionData);  //更新中间表
//            return R.failed("没有查询到自查18项资料记录");
            return R.ok(checkGaugesService.saveOrUpdateBatch(newList));
//            return R.failed("新增成功");
        } else {
            inspectionData.setId(oldData.getId());
            //类型  1，能源计量器具，2，进出用能单位能源计量器具，
            // 3，进出主要次级用能单位能源计量器具，
            // 4，主要用能设备能源计量器具，5、其他能源计量器具
            if (tableType == null || "".equals(tableType) || "1".equals(tableType)) {
                inspectionData.setEnergyMeasuringInstruments("Y");
                inspectionData.setEnergyMeasuringInstrumentsState("D");
                if ("Z".equals(mend)){
                    inspectionData.setEnergyMeasuringInstrumentsState("Z");
                }
            } else if ("2".equals(tableType)) {
                inspectionData.setMeasuringInstruments("Y");
                inspectionData.setMeasuringInstrumentsState("D");
                if ("Z".equals(mend)){
                    inspectionData.setMeasuringInstrumentsState("Z");
                }
            } else if ("3".equals(tableType)) {
                inspectionData.setSecondaryMeasuringInstrument("Y");
                inspectionData.setSecondaryMeasuringInstrumentState("D");
                if ("Z".equals(mend)){
                    inspectionData.setSecondaryMeasuringInstrumentState("Z");
                }
            } else if ("4".equals(tableType)) {
                inspectionData.setMainMeasuringInstrument("Y");
                inspectionData.setMainMeasuringInstrumentState("D");
                if ("Z".equals(mend)){
                    inspectionData.setMainMeasuringInstrumentState("Z");
                }
            } else if ("5".equals(tableType)) {
                inspectionData.setOtherMeasuringInstruments("Y");
                inspectionData.setOtherMeasuringInstrumentsState("D");
                if ("Z".equals(mend)){
                    inspectionData.setOtherMeasuringInstrumentsState("Z");
                }
            } else {
                return R.failed("未知的tableType");
            }
            inspectionDataService.updateById(inspectionData);
        }
        return R.ok(checkGaugesService.saveOrUpdateBatch(newList));
    }

    /**
     * 修改
     *
     * @param checkGauges
     * @return R
     */
    @SysLog("修改能源计量器具信息")
    @ApiOperation(value = "修改能源计量器具信息", notes = "修改能源计量器具信息")
    @ApiImplicitParam(name = "CheckGauges", value = "能源计量器具", required = true, dataType = "json", paramType = "path")
    @PutMapping
    public R updateById(@RequestBody CheckGauges checkGauges) {
        ScUser u = SecurityUtils.getUser();
        if (u.getId() != null) {
            checkGauges.setUserid(u.getId());
        }
        checkGauges.setUpdateTime(new Date());
        return R.ok(checkGaugesService.updateById(checkGauges));
    }

    /**
     * 删除
     *
     * @param checkGaugesId
     * @return R
     */
    @SysLog("删除能源计量器具")
    @ApiOperation(value = "删除能源计量器具", notes = "删除能源计量器具信息")
    @ApiImplicitParam(name = "checkAbnormalReportId", value = "能源计量器具信息ID", required = true, dataType = "int", paramType = "path")
    @DeleteMapping("/{checkGaugesId}")
    public R removeById(@PathVariable("checkGaugesId") Long checkGaugesId) {
        CheckGauges checkGauges = checkGaugesService.getById(checkGaugesId);
        ScUser u = SecurityUtils.getUser();
        if (u.getId() != null) {
            checkGauges.setUserid(u.getId());
        }
        checkGauges.setDelFlag("4");
        checkGauges.setUpdateTime(new Date());
        return R.ok(checkGaugesService.updateById(checkGauges));
    }

    /**
     * 当生成报告时 把审查的报告同步到计量器具基本信息管理
     *
     * @param
     * @return R
     */
    @SysLog("把审查的报告同步到计量器具基本信息管理")
    @PostMapping("/updateByConfigureGauge")
    public R updateByConfigureGauge(@RequestBody CheckGauges checkGauges) {  //BigInteger checkPlanId,String epc
        //查询出计量管理基本信息的计量器具
        QueryWrapper<ConfigureGauge> queryWrapperConfigure = new QueryWrapper<>();
        queryWrapperConfigure.eq("enterprise_code", checkGauges.getEpc());
        queryWrapperConfigure.eq("del_flag", "1");
        List<ConfigureGauge> ConfigureListPro = configureGaugeService.list(queryWrapperConfigure);
        ArrayList<String> al = new ArrayList();
        ConfigureListPro.forEach(v -> {
            al.add(v.getManageNo());
        });
        //查询出审查的计量器具
        QueryWrapper<CheckGauges> queryWrapperPro = new QueryWrapper<>();
        queryWrapperPro.eq("epc", checkGauges.getEpc());
        queryWrapperPro.eq("check_plan_id", checkGauges.getCheckPlanId());
        queryWrapperPro.eq("del_flag", "1");
        List<CheckGauges> listPro = checkGaugesService.list(queryWrapperPro);
        List<ConfigureGauge> listConfigureGauge = new ArrayList<>();
        listPro.forEach(r -> {
            if (al.indexOf(r.getManagerNum()) == -1) {
                ConfigureGauge configureGauge = new ConfigureGauge();
                configureGauge.setEnterpriseCode(r.getEpc());
                configureGauge.setMeterName(r.getGaugeName());
                configureGauge.setModel(r.getGaugeType());
                configureGauge.setPrecisionLevel(r.getAccuracyLevels());
                configureGauge.setRanges(r.getTestRegion());
                configureGauge.setManufacturer(r.getProductFactory());
                configureGauge.setSerNo(r.getNumFactrory());
                configureGauge.setManageNo(r.getManagerNum());
                configureGauge.setLocation(r.getLocation());
                configureGauge.setAlignCycle(r.getCheckTime());
                configureGauge.setState(r.getGaugeStatus());
                listConfigureGauge.add(configureGauge);
            }
        });
        configureGaugeService.saveBatch(listConfigureGauge);

        return R.ok("同步成功");
    }

    /**
     * 批量删除
     */
    @SysLog("计量器具批量删除")
    @PostMapping("/removeAll")
    public R removeAll(@RequestBody String ids) {
        JSONObject json = JSONObject.parseObject(ids);
        String ss = json.getString("ids");
        String[] strArray = ss.split(",");
        List list = Arrays.asList(strArray);
        return R.ok(checkGaugesService.removeByIds(list));
    }


}
