package com.ruoyi.web.controller.oa;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.oa.domain.*;
import com.ruoyi.oa.service.ICmcDeviceService;
import com.ruoyi.oa.service.ICmcProjectService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
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.domain.CmcDeviceApproval;
import com.ruoyi.oa.service.ICmcDeviceApprovalService;
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/deviceApproval")
public class CmcDeviceApprovalController extends BaseController
{
    @Autowired
    private ICmcDeviceApprovalService cmcDeviceApprovalService;

    @Autowired
    private ICmcDeviceService cmcDeviceService;

    @Autowired
    private ICmcProjectService cmcProjectService;

    /**
     * 查询cmc设备审批列表
     */
    @GetMapping("/list")
    public TableDataInfo list(CmcDeviceApproval cmcDeviceApproval)
    {
        startPage();
        List<CmcDeviceApproval> list = DeviceId2Name(cmcDeviceApproval);
        return getDataTable(list);
    }

    /**
     * 导出cmc设备审批列表
     */
    @Log(title = "cmc设备审批", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CmcDeviceApproval cmcDeviceApproval)
    {
        List<CmcDeviceApproval> list = DeviceId2Name(cmcDeviceApproval);
        ExcelUtil<CmcDeviceApproval> util = new ExcelUtil<CmcDeviceApproval>(CmcDeviceApproval.class);
        util.exportExcel(response, list, "cmc设备审批数据");
    }

    /**
     * 获取cmc设备审批详细信息
     */
    @GetMapping(value = "/{deviceApplyId}")
    public AjaxResult getInfo(@PathVariable("deviceApplyId") String deviceApplyId)
    {
        return success(cmcDeviceApprovalService.selectCmcDeviceApprovalByDeviceApplyId(deviceApplyId));
    }

    /**
     * 新增cmc设备审批
     */
    @Log(title = "cmc设备审批", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CmcDeviceApproval cmcDeviceApproval)
    {
        return toAjax(cmcDeviceApprovalService.insertCmcDeviceApproval(cmcDeviceApproval));
    }

    /**
     * 新增cmc设备审批
     */
    @Log(title = "cmc设备审批", businessType = BusinessType.INSERT)
    @PostMapping("/submit")
    public AjaxResult submit(@RequestBody String formData)
    {
        JSONObject formDataJson = JSONObject.parse(formData);
        CmcDeviceApproval cmcDeviceApproval = new CmcDeviceApproval();
        cmcDeviceApproval.setDeviceApplyId(formDataJson.getString("formId"));
        cmcDeviceApproval.setApplier(getLoginUser().getUserId());
        cmcDeviceApproval.setUseDept(getLoginUser().getDeptId());
        cmcDeviceApproval.setApplyDate(DateUtils.getNowDate());
        cmcDeviceApproval.setProjectId(formDataJson.getString("projectId"));
        if (formDataJson.getString("projectId") == null)
            cmcDeviceApproval.setProjectId("0");
        cmcDeviceApproval.setApplyReason(formDataJson.getString("applyReason"));
        cmcDeviceApproval.setBeginDate(formDataJson.getDate("beginDate"));
        cmcDeviceApproval.setEndDate(formDataJson.getDate("endDate"));
        cmcDeviceApproval.setDays(formDataJson.getLong("days"));
        if (formDataJson.getJSONArray("devices").size() > 0) {
            String deviceString = formDataJson.getString("devices").substring(1, formDataJson.getString("devices").length() - 1);
            cmcDeviceApproval.setDevices(deviceString);
            String[] devices = deviceString.split(",");
            BigDecimal estimateCost = new BigDecimal(0);
            for (String device : devices) {
                CmcDevice cmcDevice = cmcDeviceService.selectCmcDeviceByDeviceId(Integer.parseInt(device));
                if (cmcDevice.getDayCost() != null)
                    estimateCost = estimateCost.add(cmcDevice.getDayCost().multiply(new BigDecimal(cmcDeviceApproval.getDays())));
            }
            cmcDeviceApproval.setEstimateCost(estimateCost);
        }
        cmcDeviceApprovalService.insertCmcDeviceApproval(cmcDeviceApproval);
        return AjaxResult.success("提交设备审批表成功");
    }

    /**
     * 修改cmc设备审批
     */
    @Log(title = "cmc设备审批", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CmcDeviceApproval cmcDeviceApproval)
    {
        return toAjax(cmcDeviceApprovalService.updateCmcDeviceApproval(cmcDeviceApproval));
    }

    /**
     * 修改cmc设备审批
     */
    @Log(title = "cmc设备审批", businessType = BusinessType.UPDATE)
    @PutMapping("/modify")
    public AjaxResult modify(@RequestBody String formData)
    {
        JSONObject formDataJson = JSONObject.parse(formData);
        CmcDeviceApproval cmcDeviceApproval = cmcDeviceApprovalService.selectCmcDeviceApprovalByDeviceApplyId(formDataJson.getString("deviceApplyId"));
        if (formDataJson.getString("modifyDevices") != null && formDataJson.getString("managerComment") == null && formDataJson.getString("dispatcher") == null) {
            cmcDeviceApproval.setDispatcher(getLoginUser().getUserId());
            cmcDeviceApproval.setDispatchComment(formDataJson.getString("dispatchComment"));
            cmcDeviceApproval.setDispatchTime(new Date());
        }
        if (formDataJson.getJSONArray("modifyDevices").size() > 0 && formDataJson.getString("managerComment") == null) {
            cmcDeviceApproval.setDispatcher(getLoginUser().getUserId());
            cmcDeviceApproval.setDispatchComment(formDataJson.getString("dispatchComment"));
            cmcDeviceApproval.setDispatchTime(new Date());
            String deviceString = formDataJson.getString("modifyDevices").substring(1, formDataJson.getString("modifyDevices").length() - 1);
            cmcDeviceApproval.setModifyDevices(deviceString);
            if (!formDataJson.getString("projectId").equals("")) {
                CmcProject cmcProject = new CmcProject();
                cmcProject.setProjectId(formDataJson.getString("projectId"));
                CmcProject project = cmcProjectService.selectCmcProjectByProjectId(cmcProject.getProjectId());
                if (project != null) {
                    if (project.getDevices() != null) {
                        String[] projectDevices = project.getDevices().split(",");
                        String[] devices = deviceString.split(",");
                        project.setDevices(String.join(",", CollectionUtils.union(Arrays.asList(projectDevices), Arrays.asList(devices))));
                    }
                    else
                        project.setDevices(deviceString);
                    cmcProjectService.updateCmcProject(project);
                }
            }
            String[] devices = deviceString.split(",");
            BigDecimal estimateCost = new BigDecimal(0);
            for (String device : devices) {
                CmcDevice cmcDevice = cmcDeviceService.selectCmcDeviceByDeviceId(Integer.parseInt(device));
                cmcDevice.setStatus("0"); //确认被领用
                cmcDeviceService.updateCmcDevice(cmcDevice);
                if (cmcDevice.getDayCost() != null)
                    estimateCost = estimateCost.add(cmcDevice.getDayCost().multiply(new BigDecimal(cmcDeviceApproval.getDays())));
            }
            cmcDeviceApproval.setEstimateCost(estimateCost);
        }
        if (formDataJson.getString("managerComment") != null && formDataJson.getString("returnDate") == null) {
            cmcDeviceApproval.setManagerUserId(getLoginUser().getUserId());
            cmcDeviceApproval.setManagerComment(formDataJson.getString("managerComment"));
            cmcDeviceApproval.setManagerTime(new Date());
        }
        if (formDataJson.getDate("returnDate") != null) {
            cmcDeviceApproval.setRemark(formDataJson.getString("remark"));
            if (formDataJson.getString("repairDevices") != null && formDataJson.getJSONArray("repairDevices").size() > 0) {
                String deviceString = formDataJson.getString("repairDevices").substring(1, formDataJson.getString("repairDevices").length() - 1);
                cmcDeviceApproval.setRepairDevices(deviceString);
                String[] devices = deviceString.split(",");
                for (String device : devices) {
                    CmcDevice cmcDevice = cmcDeviceService.selectCmcDeviceByDeviceId(Integer.parseInt(device));
                    cmcDevice.setStatus("2"); //需维修
                    cmcDeviceService.updateCmcDevice(cmcDevice);
                }
            }
            if (formDataJson.getString("returnDevices") != null && formDataJson.getJSONArray("returnDevices").size() > 0) {
                String deviceString = formDataJson.getString("returnDevices").substring(1, formDataJson.getString("returnDevices").length() - 1);
                cmcDeviceApproval.setReturnDevices(deviceString);
                String[] devices = deviceString.split(",");
                for (String device : devices) {
                    CmcDevice cmcDevice = cmcDeviceService.selectCmcDeviceByDeviceId(Integer.parseInt(device));
                    cmcDevice.setStatus("1"); //可领用
                    cmcDeviceService.updateCmcDevice(cmcDevice);
                }
            }
            cmcDeviceApproval.setReturnDate(formDataJson.getDate("returnDate"));
        }
        cmcDeviceApprovalService.updateCmcDeviceApproval(cmcDeviceApproval);
        return AjaxResult.success("修改设备审批表成功");
    }

    /**
     * 删除cmc设备审批
     */
    @Log(title = "cmc设备审批", businessType = BusinessType.DELETE)
	@DeleteMapping("/{deviceApplyIds}")
    public AjaxResult remove(@PathVariable String[] deviceApplyIds)
    {
        return success(cmcDeviceApprovalService.deleteCmcDeviceApprovalByDeviceApplyIds(deviceApplyIds));
    }

    private List<CmcDeviceApproval> DeviceId2Name(CmcDeviceApproval cmcDeviceApproval) {
        List<CmcDeviceApproval> list = cmcDeviceApprovalService.selectCmcDeviceApprovalList(cmcDeviceApproval);
        for(CmcDeviceApproval deviceApproval : list) {
            String deviceIds = deviceApproval.getDevices();
            StringBuilder deviceNames = new StringBuilder();
            StringBuilder deviceNumbers = new StringBuilder();
            if (deviceIds != null && !deviceIds.equals("") && deviceIds.split(",").length > 0) {
                for (String deviceId : deviceIds.split(",")) {
                    CmcDevice device = cmcDeviceService.selectCmcDeviceByDeviceId(Integer.parseInt(deviceId));
                    deviceNumbers.append(device.getDeviceNumber());
                    deviceNames.append(device.getName()).append("【").append(device.getBrand() != null ? device.getBrand() : "")
                            .append(device.getSeries() != null ? "-" + device.getSeries() + "】" : "")
                            .append(device.getCode() != null ? "（设备编号：" + device.getCode() + "）" : "").append(",");
                }
                deviceApproval.setDeviceNumbers(deviceNumbers.substring(0, deviceNumbers.length() - 1));
                deviceApproval.setDeviceNames(deviceNames.substring(0, deviceNames.length() - 1));
            }
            String modifyDeviceIds = deviceApproval.getModifyDevices();
            StringBuilder modifyDeviceNames = new StringBuilder();
            StringBuilder modifyDeviceNumbers = new StringBuilder();
            if (modifyDeviceIds != null && !modifyDeviceIds.equals("") && modifyDeviceIds.split(",").length > 0) {
                for (String deviceId : modifyDeviceIds.split(",")) {
                    CmcDevice device = cmcDeviceService.selectCmcDeviceByDeviceId(Integer.parseInt(deviceId));
                    modifyDeviceNumbers.append(device.getDeviceNumber());
                    modifyDeviceNames.append(device.getName()).append("【").append(device.getBrand() != null ? device.getBrand() : "")
                            .append(device.getSeries() != null ? "-" + device.getSeries() + "】" : "")
                            .append(device.getCode() != null ? "（设备编号：" + device.getCode() + "）" : "").append(",");
                }
                deviceApproval.setModifyDeviceNumbers(modifyDeviceNumbers.substring(0, modifyDeviceNumbers.length() - 1));
                deviceApproval.setModifyDeviceNames(modifyDeviceNames.substring(0, modifyDeviceNames.length() - 1));
            }
            String repairDeviceIds = deviceApproval.getRepairDevices();
            StringBuilder repairDeviceNames = new StringBuilder();
            StringBuilder repairDeviceNumbers = new StringBuilder();
            if (repairDeviceIds != null && !repairDeviceIds.equals("") && repairDeviceIds.split(",").length > 0) {
                for (String deviceId : repairDeviceIds.split(",")) {
                    CmcDevice device = cmcDeviceService.selectCmcDeviceByDeviceId(Integer.parseInt(deviceId));
                    repairDeviceNumbers.append(device.getDeviceNumber());
                    repairDeviceNames.append(device.getName()).append("【").append(device.getBrand() != null ? device.getBrand() : "")
                            .append(device.getSeries() != null ? "-" + device.getSeries() + "】" : "")
                            .append(device.getCode() != null ? "（设备编号：" + device.getCode() + "）" : "").append(",");
                }
                deviceApproval.setRepairDeviceNumbers(repairDeviceNumbers.substring(0, repairDeviceNumbers.length() - 1));
                deviceApproval.setRepairDeviceNames(repairDeviceNames.substring(0, repairDeviceNames.length() - 1));
            }
            String returnDeviceIds = deviceApproval.getReturnDevices();
            StringBuilder returnDeviceNames = new StringBuilder();
            StringBuilder returnDeviceNumbers = new StringBuilder();
            if (returnDeviceIds != null && !returnDeviceIds.equals("") && returnDeviceIds.split(",").length > 0) {
                for (String deviceId : returnDeviceIds.split(",")) {
                    CmcDevice device = cmcDeviceService.selectCmcDeviceByDeviceId(Integer.parseInt(deviceId));
                    returnDeviceNumbers.append(device.getDeviceNumber());
                    returnDeviceNames.append(device.getName()).append("【").append(device.getBrand() != null ? device.getBrand() : "")
                            .append(device.getSeries() != null ? "-" + device.getSeries() + "】" : "")
                            .append(device.getCode() != null ? "（设备编号：" + device.getCode() + "）" : "").append(",");
                }
                deviceApproval.setReturnDeviceNumbers(returnDeviceNumbers.substring(0, returnDeviceNumbers.length() - 1));
                deviceApproval.setReturnDeviceNames(returnDeviceNames.substring(0, returnDeviceNames.length() - 1));
            }
        }
        return list;
    }

}
