package com.nantian.cloud.dbcapp.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.nantian.cloud.dbcapp.entity.AccessEnergysTructure;
import com.nantian.cloud.dbcapp.service.AccessEnergysTructureService;
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.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@CrossOrigin
@RestController
@AllArgsConstructor
@RequestMapping("/accessEnergysTructure")
@Api(value = "accessEnergysTructure", tags = "延期接入企业-能源消费结构表")
public class AccessEnergysTructureController {

    @Autowired
    private AccessEnergysTructureService tructureService;

    @GetMapping("/list")
    @SysLog("获取能源消费结构信息")
    @ApiOperation(value = "获取能源消费结构信息", notes = "获取能源消费结构信息")
    public R list(String epc, String date) {
        return R.ok(tructureService.list(new QueryWrapper<AccessEnergysTructure>()
                .eq("del_flag","1")
                .like("enterprise_code", epc==null ? "" :epc)
                .like("record_date", date==null ? "" :date)));
    }

    @PostMapping("/renewParamBatch")
    @SysLog("更新能源消费结构信息")
    @ApiOperation(value = "更新能源消费结构信息", notes = "更新能源消费结构信息")
    public R saveOrUpdateBatch(@RequestBody String str) {
        JSONObject json = JSONObject.parseObject(str);
        String epc = json.getString("epc");
        String date = json.getString("date");
        if(epc==null || date==null){
            return R.failed("企业编码或统计周期不能为空！");
        }
        List<AccessEnergysTructure> dataList = (List<AccessEnergysTructure>) JSONArray.parseArray(json.getString("list"), AccessEnergysTructure.class);
        ScUser u = SecurityUtils.getUser();
        for (AccessEnergysTructure tructure : dataList) {
            if(tructure.getId()==null){
                tructure.setDelFlag("1");
            }
            tructure.setEnterpriseCode(epc.toString());
            tructure.setRecordDate(date.toString());
            tructure.setUpdateTime(new Date());
            tructure.setDeptId(u.getDeptId());
            tructure.setUserid(u.getId());
//            tructureService.saveOrUpdate(tructure);
        }
        tructureService.saveOrUpdateBatch(dataList);
        return  R.ok("更新能源消费结构信息成功！");
    }
}
