package com.nantian.cloud.jly.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nantian.cloud.jly.entity.CheckDev;
import com.nantian.cloud.jly.entity.InspectionData;
import com.nantian.cloud.jly.service.CheckDevService;
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 = "checkDev", tags = "主要用能设备")
@RequestMapping("/checkDev")
public class CheckDevController {
    private final CheckDevService checkDevService;
    private final InspectionDataService inspectionDataService;


    /**
     * 分页查询
     *
     * @param page     分页对象
     * @param checkDev 请假审批单
     * @return
     */
    @SysLog("查询主要用能设备")
    @GetMapping("/page")
    @ApiOperation(value = "查询主要用能设备", notes = "条件查询主要用能设备信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Page", value = "分页对象", required = false, dataType = "json", paramType = "path"),
            @ApiImplicitParam(name = "CheckDev", value = "主要用能设备对象", required = false, dataType = "json", paramType = "path")
    })
    public R getcheckDevPage(Page page, CheckDev checkDev) {
        checkDev.setDelFlag("1"); //查询未删除数据
        //return R.ok(checkDevService.page(page, Wrappers.query(checkDev)));
        IPage<CheckDev> pageScope = checkDevService.getPageScope(page, checkDev);
        System.err.println("查询接口："+pageScope.getRecords().toString());
        return R.ok(pageScope);
    }


    /**
     * 信息
     *
     * @param checkDevId
     * @return R
     */
    @SysLog("通过id查询主要用能设备")
    @GetMapping("/{checkDevId}")
    @ApiOperation(value = "通过id查询主要用能设备", notes = "通过id条件查询主要用能设备信息")
    @ApiImplicitParam(name = "checkDevId", value = "主要用能设备ID", required = true, paramType = "path", dataType = "int")
    public R getById(@PathVariable("checkDevId") Integer checkDevId) {
        return R.ok(checkDevService.getById(checkDevId));
    }

    /**
     * 保存
     */
    @SysLog("保存主要用能设备")
    @PostMapping("/save")
    @ApiOperation(value = "新增主要用能设备", notes = "新增主要用能设备信息")
    @ApiImplicitParam(name = "CheckDev", value = "主要用能设备", required = true, dataType = "json", paramType = "path")
    public R save(@RequestBody CheckDev checkDev) {
        ScUser u = SecurityUtils.getUser();
        checkDev.setUserid(u.getId());
        checkDev.setDeptId(u.getDeptId());
        checkDev.setDelFlag("1");
        checkDev.setUpdateTime(new Date());
        boolean save = checkDevService.save(checkDev); //新增

        InspectionData inspectionData = inspectionDataService.getByPlanIdAndEpc(checkDev.getCheckPlanId(), checkDev.getEpc());
        checkDevService.updateInspectionData(u, checkDev, inspectionData); //更新中间表
        return save ? R.ok("新增主要用能设备信息成功") : R.failed("新增主要用能设备信息失败");
    }


    /**
     * 修改
     */
    @SysLog("修改主要用能设备")
    @PutMapping
    @ApiOperation(value = "修改主要用能设备", notes = "修改主要用能设备信息")
    @ApiImplicitParam(name = "CheckDev", value = "主要用能设备", required = true, dataType = "json", paramType = "path")
    public R updateById(@RequestBody CheckDev checkDev) {
        ScUser u = SecurityUtils.getUser();
        checkDev.setUserid(u.getId());
        checkDev.setUpdateTime(new Date());
        boolean b = checkDevService.updateById(checkDev);//修改
        return b ? R.ok("修改主要用能设备信息成功") : R.failed("修改主要用能设备信息失败");
    }

    /**
     * 更新
     */
    @SysLog("更新主要用能设备")
    @PostMapping("/renew")
    @ApiOperation(value = "更新主要用能设备", notes = "更新主要用能设备信息（修改和新增接口）")
    @ApiImplicitParam(name = "CheckDev", value = "主要用能设备", required = true, dataType = "json", paramType = "path")
    public R renew(@RequestBody CheckDev checkDev) {
        /*JSONObject json = JSONObject.parseObject(s);
        String ss = json.getString("data");
        CheckDev checkDev= (CheckDev) JSONArray.parseArray(ss, CheckDev.class);*/

        InspectionData inspectionData = inspectionDataService.getByPlanIdAndEpc(checkDev.getCheckPlanId(), checkDev.getEpc());
        if (inspectionData == null) {
            return R.failed("没有查询到自查18项资料记录");
        }else{
            if ("Y".equals(inspectionData.getEnergyusingEquipmentState())) { //已审核
                return R.failed("主要用能设备一览表已审核，不能进行增加、修改、删除操作！");
            }
        }

        ScUser u = SecurityUtils.getUser();
        checkDevService.updateInspectionData(u, checkDev, inspectionData); //更新中间表

        return R.ok(checkDevService.saveOrUpdate(checkDev));

    }

    /**
     * 导入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")
    })
    public R excelImport(MultipartFile file, BigInteger checkPlanId, String epc) throws FileFormatException {
        if(checkPlanId==null){
            return R.failed("审查计划id不能为空！");
        }
        if(epc==null||"".equals(epc)){
            return R.failed("企业社会信用编码不能为空！");
        }

        InspectionData inspectionData = inspectionDataService.getByPlanIdAndEpc(checkPlanId, epc);
        if (inspectionData != null) {
            if ("Y".equals(inspectionData.getEnergyusingEquipmentState())) { //已审核
                return R.failed("主要用能设备一览表已审核，不能进行增加、修改、删除操作！");
            }
        }

        return checkDevService.excelImport(file,checkPlanId,epc,inspectionData);
    }

    /**
     * 批量更新
     */
    @SysLog("批量更新主要用能设备")
    @PostMapping("/renewBatch")
    @ApiOperation(value = "批量更新主要用能设备（批量修改和批量新增）", notes = "批量更新主要用能设备（批量修改和批量新增）")
    @ApiImplicitParam(name = "CheckDev", value = "主要用能设备集合", required = true, dataType = "json", paramType = "path")
    //public R saveBatch(@RequestBody  List<CheckDev> checkDevList) {
    public R renewBatch(@RequestBody String s) {
        JSONObject json = JSONObject.parseObject(s);
        String ss = json.getString("data");
        String mend = json.getString("mend");
        List<CheckDev> checkDevList = (List<CheckDev>) JSONArray.parseArray(ss, CheckDev.class);

        List<CheckDev> newCheckDevList = new ArrayList<>();
        ScUser u = SecurityUtils.getUser();
        if(checkDevList != null && checkDevList.size() >= 1){
            InspectionData inspectionData = inspectionDataService.getByPlanIdAndEpc(checkDevList.get(0).getCheckPlanId(), checkDevList.get(0).getEpc());
            if (inspectionData != null) {
                checkDevService.updateInspectionData(u, checkDevList.get(0), inspectionData); //更新中间表
                if ("Y".equals(inspectionData.getEnergyusingEquipmentState())) { //已审核
                    return R.failed("主要用能设备一览表已审核，不能进行增加、修改、删除操作！");
                }
                if ("Z".equals(mend)){  //整改上传
                    inspectionData.setEnergyusingEquipmentState("Z");
                }
                checkDevService.updateInspectionData(u, checkDevList.get(0), inspectionData);  //更新中间表
                return R.ok(checkDevService.saveOrUpdateBatch(checkDevList));
            } else {
                return R.failed("数据为空！");
            }
        }
        for (CheckDev checkDev : checkDevList) {
            //未审核
            if (u.getId() != null) {
                checkDev.setUserid(u.getId());
            }
            if (u.getDeptId() != null) {
                checkDev.setDeptId(u.getDeptId());
            }
            checkDev.setDelFlag("1");
            checkDev.setUpdateTime(new Date());


            newCheckDevList.add(checkDev);
        }
        System.err.println("批量更新能用能设备newCheckDevList：" + newCheckDevList);
        return R.ok(checkDevService.saveOrUpdateBatch(newCheckDevList));
    }

    /**
     * 删除
     *
     * @param checkDevId
     * @return R
     */
    @SysLog("删除主要用能设备")
    @DeleteMapping
    @ApiOperation(value = "删除主要用能设备", notes = "删除主要用能设备信息")
    @ApiImplicitParam(name = "checkDevId", value = "主要用能设备id", required = true, dataType = "int", paramType = "path")
    public R removeById(Long checkDevId) {
        System.err.println("删除主要用能设备：" + checkDevId);

        CheckDev checkDev = checkDevService.getById(checkDevId);
        if(checkDev==null){
            return R.failed("主要用能设备不存在，删除失败！");
        }

        InspectionData inspectionData = inspectionDataService.getByPlanIdAndEpc(checkDev.getCheckPlanId(), checkDev.getEpc());
        if (inspectionData!=null) {
            if ("Y".equals(inspectionData.getEnergyusingEquipmentState())) { //已审核
                return R.failed("主要用能设备一览表已审核，不能进行增加、修改、删除操作！");
            }
        }

        //未审核
        ScUser u = SecurityUtils.getUser();
        if (u.getId() != null) {
            checkDev.setUserid(u.getId());
        }
        checkDev.setDelFlag("4");
        checkDev.setUpdateTime(new Date());
        boolean b = checkDevService.updateById(checkDev);//修改注销状态

        CheckDev newCheckDev = new CheckDev();
        newCheckDev.setDelFlag("1");
        newCheckDev.setCheckPlanId(checkDev.getCheckPlanId());
        newCheckDev.setEpc(checkDev.getEpc());
        IPage<CheckDev> page = checkDevService.page(new Page<>(), Wrappers.query(newCheckDev));
        if (page.getRecords().size() == 0) {//没有数据
            inspectionData.setEnergyusingEquipment("D");
            inspectionData.setUserid(u.getId());
            inspectionData.setUpdateTime(new Date());
            inspectionDataService.updateById(inspectionData);
        }
        return b ? R.ok("删除成功") : R.failed("删除失败");
    }

    /**
     * 批量删除
     */
    @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(checkDevService.removeByIds(list));
    }


}
