package com.ruoyi.web.controller.oa;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.oa.domain.CmcDevice;
import com.ruoyi.oa.domain.CmcDeviceApproval;
import com.ruoyi.oa.service.ICmcDeviceApprovalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.oa.service.ICmcDeviceService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * cmc设备信息Controller
 * 
 * @author cmc
 * @date 2024-03-05
 */
@RestController
@RequestMapping("/oa/device")
public class CmcDeviceController extends BaseController
{
    @Autowired
    private ICmcDeviceService cmcDeviceService;

    @Autowired
    private ICmcDeviceApprovalService cmcDeviceApprovalService;

    /**
     * 查询cmc设备信息列表
     */
    @GetMapping("/list")
    public TableDataInfo list(CmcDevice cmcDevice)
    {
        startPage();
        List<CmcDevice> list = cmcDeviceService.selectCmcDeviceList(cmcDevice);
        return getDataTable(list);
    }

    /**
     * 查询cmc设备名称列表
     */
    @GetMapping("/nameList")
    public AjaxResult getNameList()
    {
        List<Map<String, Object>> list = cmcDeviceService.selectCmcDeviceNameList();
        return success(list);
    }

    /**
     * 导出cmc设备信息列表
     */
    @Log(title = "cmc设备信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CmcDevice cmcDevice)
    {
        List<CmcDevice> list = cmcDeviceService.selectCmcDeviceList(cmcDevice);
        ExcelUtil<CmcDevice> util = new ExcelUtil<CmcDevice>(CmcDevice.class);
        util.exportExcel(response, list, "cmc设备信息数据");
    }

    /**
     * 获取cmc设备信息详细信息
     */
    @GetMapping(value = "/{deviceId}")
    public AjaxResult getInfo(@PathVariable("deviceId") Integer deviceId)
    {
        return success(cmcDeviceService.selectCmcDeviceByDeviceId(deviceId));
    }

    /**
     * 获取设备统计信息
     */
    @GetMapping(value = "/statistic")
    public AjaxResult getDeviceStatistic(CmcDeviceApproval cmcDeviceApproval) throws ParseException
    {
        JSONObject jsonObject = new JSONObject();
        JSONArray yearArray = new JSONArray();
        JSONObject yearObject = new JSONObject();
        JSONArray statusArray = new JSONArray();
        JSONObject statusObject = new JSONObject();
        JSONArray approvalArray = new JSONArray();
        JSONArray monthArray = new JSONArray();
        JSONObject monthObject = new JSONObject();
        CmcDevice cmcDevice = new CmcDevice();
        cmcDevice.setStatus("0");
        statusObject.put("被领用", cmcDeviceService.selectCmcDeviceList(cmcDevice).size());
        cmcDevice.setStatus("1");
        statusObject.put("可领用", cmcDeviceService.selectCmcDeviceList(cmcDevice).size());
        cmcDevice.setStatus("2");
        statusObject.put("维修中", cmcDeviceService.selectCmcDeviceList(cmcDevice).size());
        cmcDevice.setStatus("3");
        statusObject.put("已停用", cmcDeviceService.selectCmcDeviceList(cmcDevice).size());
        cmcDevice.setStatus("4");
        statusObject.put("已报废", cmcDeviceService.selectCmcDeviceList(cmcDevice).size());
        cmcDevice.setStatus("5");
        statusObject.put("已处置", cmcDeviceService.selectCmcDeviceList(cmcDevice).size());
        //整体
        if (cmcDeviceApproval.getApplyDate() == null) {
            //每年设备申请次数
            for (int i = 2019; i <= Calendar.getInstance().get(Calendar.YEAR); i++) {
                //总数
                cmcDeviceApproval.setApplyDate(new SimpleDateFormat("yyyy").parse(String.valueOf(i)));
                List<CmcDeviceApproval> yearList = cmcDeviceApprovalService.selectCmcDeviceApprovalList(cmcDeviceApproval);
                yearObject.put(String.valueOf(i), yearList.size());
            }
            cmcDeviceApproval.setApplyDate(null);
        }
        //年度
        else {
            String yearStr = new SimpleDateFormat("yyyy").format(cmcDeviceApproval.getApplyDate());
            //输入年份设备申请次数
            cmcDeviceApproval.setApplyDate(new SimpleDateFormat("yyyy").parse(yearStr));
            List<CmcDeviceApproval> yearList = cmcDeviceApprovalService.selectCmcDeviceApprovalList(cmcDeviceApproval);
            yearObject.put(yearStr, yearList.size());
            
            //月度统计
            for (int i = 1; i <= 12; i++) {
                String monthStr = String.format("%02d", i);
                String monthKey = yearStr + "-" + monthStr;
                String beginTimeString = monthKey + "-01";
                
                Map<String, Object> params = new HashMap<>();
                params.put("beginTime", beginTimeString + " 00:00:00");
                cmcDeviceApproval.setParams(params);
                cmcDeviceApproval.setApplyDate(new SimpleDateFormat("yyyy-MM").parse(beginTimeString));
                
                List<CmcDeviceApproval> monthList = cmcDeviceApprovalService.selectCmcDeviceApprovalList(cmcDeviceApproval);
                monthObject.put(monthKey, monthList.size());
                cmcDeviceApproval.setParams(null);
            }
        }
        getDeviceApprovalStatistic(cmcDeviceApproval, approvalArray);
        cmcDeviceApproval.setApplyDate(null);
        yearArray.add(yearObject);
        statusArray.add(statusObject);
        monthArray.add(monthObject);
        jsonObject.put("year", yearArray);
        jsonObject.put("status", statusArray);
        jsonObject.put("approval", approvalArray);
        jsonObject.put("month", monthArray);
        jsonObject.getJSONArray("approval").sort((a,b)->((JSONObject)b).getIntValue("count") - ((JSONObject)a).getIntValue("count"));
        return success(jsonObject);
    }

    /**
     * 新增cmc设备信息
     */
    @Log(title = "cmc设备信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CmcDevice cmcDevice)
    {
//        if (cmcDevice.getAcquisitionTime() != null && cmcDevice.getCost() != null && cmcDevice.getDayCost() == null) {
//            // 年数总和法折旧
//            int acquisitionYear = Integer.parseInt(new SimpleDateFormat("yyyy").format(cmcDevice.getAcquisitionTime()));
//            int life = cmcDevice.getExpectLife() == null ? 0 : cmcDevice.getExpectLife();
//            int total = 0;
//            for (int i = 0; i < life + 1; i++)
//                total += i;
//            if (total > 0) {
//                int currentYear = Integer.parseInt(new SimpleDateFormat("yyyy").format(DateUtils.getNowDate()));
//                int num = life - (currentYear - acquisitionYear) + 1;
//                BigDecimal estimateCost = new BigDecimal(num  * 0.95 / total / 365).multiply(cmcDevice.getCost());
//                cmcDevice.setDayCost(estimateCost);
//            }
//        }
        return toAjax(cmcDeviceService.insertCmcDevice(cmcDevice));
    }

    /**
     * 修改cmc设备信息
     */
    @Log(title = "cmc设备信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CmcDevice cmcDevice)
    {
//        if (cmcDevice.getAcquisitionTime() != null && cmcDevice.getCost() != null && cmcDevice.getDayCost() == null) {
//            // 年数总和法折旧
//            int acquisitionYear = Integer.parseInt(new SimpleDateFormat("yyyy").format(cmcDevice.getAcquisitionTime()));
//            int life = cmcDevice.getExpectLife() == null ? 0 : cmcDevice.getExpectLife();
//            int total = 0;
//            for (int i = 0; i < life + 1; i++)
//                total += i;
//            if (total > 0) {
//                int currentYear = Integer.parseInt(new SimpleDateFormat("yyyy").format(DateUtils.getNowDate()));
//                int num = life - (currentYear - acquisitionYear) + 1;
//                BigDecimal estimateCost = new BigDecimal(num  * 0.95 / total / 365).multiply(cmcDevice.getCost());
//                cmcDevice.setDayCost(estimateCost);
//            }
//        }
        return toAjax(cmcDeviceService.updateCmcDevice(cmcDevice));
    }

    /**
     * 修改cmc设备信息
     */
    @Log(title = "cmc设备信息", businessType = BusinessType.UPDATE)
    @PutMapping("/dayCost")
    public AjaxResult editDayCost()
    {
        List<CmcDevice> list = cmcDeviceService.selectCmcDeviceList(new CmcDevice());
        for (CmcDevice cmcDevice : list) {
            if (cmcDevice.getAcquisitionTime() != null && cmcDevice.getCost() != null && cmcDevice.getDayCost() == null) {
                // 年数总和法折旧
                int acquisitionYear = Integer.parseInt(new SimpleDateFormat("yyyy").format(cmcDevice.getAcquisitionTime()));
                int life = cmcDevice.getExpectLife() == null ? 0 : cmcDevice.getExpectLife();
                int total = 0;
                for (int i = 0; i < life + 1; i++)
                    total += i;
                if (total > 0) {
                    int currentYear = Integer.parseInt(new SimpleDateFormat("yyyy").format(DateUtils.getNowDate()));
                    int num = life - (currentYear - acquisitionYear) + 1;
                    BigDecimal estimateCost = new BigDecimal(num  * 0.95 / total / 365).multiply(cmcDevice.getCost());
                    cmcDevice.setDayCost(estimateCost);
                }
            }
            cmcDeviceService.updateCmcDevice(cmcDevice);
        }
        return toAjax(list.size());
    }

    /**
     * 删除cmc设备信息
     */
    @Log(title = "cmc设备信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{deviceIds}")
    public AjaxResult remove(@PathVariable Long[] deviceIds)
    {
        return success(cmcDeviceService.deleteCmcDeviceByDeviceIds(deviceIds));
    }

    //各设备领用次数
    public void getDeviceApprovalStatistic(CmcDeviceApproval cmcDeviceApproval, JSONArray approvalArray) {

        for (CmcDevice cmcDevice : cmcDeviceService.selectCmcDeviceList(new CmcDevice())) {
            cmcDeviceApproval.setDevices(cmcDevice.getDeviceId().toString());
            int count = cmcDeviceApprovalService.selectCmcDeviceApprovalList(cmcDeviceApproval).size();
            StringBuilder deviceNames = new StringBuilder();
            deviceNames.append(cmcDevice.getName()).append("【").append(cmcDevice.getBrand() != null ? cmcDevice.getBrand() : "")
                    .append(cmcDevice.getSeries() != null ? "-" + cmcDevice.getSeries() + "】" : "")
                    .append(cmcDevice.getCode() != null ? "（设备编号：" + cmcDevice.getCode() + "）" : "");
            if (count > 0) {
                JSONObject approvalObject = new JSONObject();
                approvalObject.put("name", deviceNames);
                approvalObject.put("count", count);
                approvalArray.add(approvalObject);
            }
        }
    }

}