package com.ruoyi.web.controller.oa;

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

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.oa.domain.*;
import com.ruoyi.oa.service.ICmcCarService;
import com.ruoyi.oa.service.ICmcProjectService;
import com.ruoyi.system.service.ISysUserService;
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.service.ICmcCarApprovalService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * cmc用车审批Controller
 * 
 * @author cmc
 * @date 2024-02-23
 */
@RestController
@RequestMapping("/oa/carApproval")
public class CmcCarApprovalController extends BaseController
{
    @Autowired
    private ICmcCarApprovalService cmcCarApprovalService;

    @Autowired
    private ICmcCarService cmcCarService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ICmcProjectService cmcProjectService;

    /**
     * 查询cmc用车审批列表
     */
    @GetMapping("/list")
    public TableDataInfo list(CmcCarApproval cmcCarApproval)
    {
        startPage();
        List<CmcCarApproval> list = cmcCarApprovalService.selectCmcCarApprovalList(cmcCarApproval);
        for(CmcCarApproval carApproval : list) {
            String carIds = carApproval.getCars();
            String licensePlate = carApproval.getLicensePlate();
            StringBuilder licensePlates = new StringBuilder();
            if (carIds != null && !carIds.equals("") && (licensePlate == null || licensePlate.equals(""))) {
                for (String carId : carIds.split(","))
                    licensePlates.append(cmcCarService.selectCmcCarByCarId(Integer.parseInt(carId)).getLicensePlate()).append(",");
                carApproval.setLicensePlate(licensePlates.substring(0, licensePlates.length() - 1));
            }
            String driverIds = carApproval.getDrivers();
            String driverName = carApproval.getDriverName();
            StringBuilder driverNames = new StringBuilder();
            if (driverIds != null && !driverIds.equals("") && (driverName == null || driverName.equals(""))) {
                for (String driverId : driverIds.split(","))
                    driverNames.append(userService.selectUserById(Long.parseLong(driverId)).getNickName()).append(",");
                carApproval.setDriverName(driverNames.substring(0, driverNames.length() - 1));
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出cmc用车审批列表
     */
    @Log(title = "cmc用车审批", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CmcCarApproval cmcCarApproval)
    {
        List<CmcCarApproval> list = cmcCarApprovalService.selectCmcCarApprovalList(cmcCarApproval);
        for(CmcCarApproval carApproval : list) {
            String carIds = carApproval.getCars();
            String licensePlate = carApproval.getLicensePlate();
            StringBuilder licensePlates = new StringBuilder();
            if (carIds != null && !carIds.equals("") && (licensePlate == null || licensePlate.equals(""))) {
                for (String carId : carIds.split(","))
                    licensePlates.append(cmcCarService.selectCmcCarByCarId(Integer.parseInt(carId)).getLicensePlate()).append(",");
                carApproval.setLicensePlate(licensePlates.substring(0, licensePlates.length() - 1));
            }
            String driverIds = carApproval.getDrivers();
            String driverName = carApproval.getDriverName();
            StringBuilder driverNames = new StringBuilder();
            if (driverIds != null && !driverIds.equals("") && (driverName == null || driverName.equals(""))) {
                for (String driverId : driverIds.split(","))
                    driverNames.append(userService.selectUserById(Long.parseLong(driverId)).getNickName()).append(",");
                carApproval.setDriverName(driverNames.substring(0, driverNames.length() - 1));
            }
        }
        ExcelUtil<CmcCarApproval> util = new ExcelUtil<CmcCarApproval>(CmcCarApproval.class);
        util.exportExcel(response, list, "cmc用车审批数据");
    }

    /**
     * 获取cmc用车审批详细信息
     */
    @GetMapping(value = "/{carApplyId}")
    public AjaxResult getInfo(@PathVariable("carApplyId") String carApplyId)
    {
        return success(cmcCarApprovalService.selectCmcCarApprovalByCarApplyId(carApplyId));
    }

    /**
     * 新增cmc用车审批
     */
    @Log(title = "cmc用车审批", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CmcCarApproval cmcCarApproval)
    {
        cmcCarApproval.setApplier(getLoginUser().getUserId());
        cmcCarApproval.setUseDept(getLoginUser().getDeptId());
        return toAjax(cmcCarApprovalService.insertCmcCarApproval(cmcCarApproval));
    }

    /**
     * 修改cmc用车审批
     */
    @Log(title = "cmc用车审批", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CmcCarApproval cmcCarApproval)
    {
        return toAjax(cmcCarApprovalService.updateCmcCarApproval(cmcCarApproval));
    }

    /**
     * 修改用车审批表
     */
    @Log(title = "用车审批表", businessType = BusinessType.UPDATE)
    @PutMapping( "/modify")
    public AjaxResult modify(@RequestBody String formData)
    {
        JSONObject formDataJson = JSONObject.parse(formData);
        CmcCarApproval cmcCarApproval = cmcCarApprovalService.selectCmcCarApprovalByCarApplyId(formDataJson.getString("carApplyId"));
        cmcCarApproval.setCarUsage(formDataJson.getString("carUsage"));
        cmcCarApproval.setDays(formDataJson.getLong("days"));
        cmcCarApproval.setEndDate(formDataJson.getDate("endDate"));
        cmcCarApproval.setBeginDate(formDataJson.getDate("beginDate"));
        cmcCarApproval.setProjectId(formDataJson.getString("projectId"));
        cmcCarApproval.setApplyReason(formDataJson.getString("applyReason"));
        cmcCarApproval.setApplyDate(formDataJson.getDate("applyDate"));
        cmcCarApproval.setPassengers(formDataJson.getInteger("passengers"));
        if (formDataJson.getString("deptComment") != null && formDataJson.getString("managerComment") == null) {
            cmcCarApproval.setDeptUserId(getLoginUser().getUserId());
            cmcCarApproval.setDeptComment(formDataJson.getString("deptComment"));
            cmcCarApproval.setDeptTime(new Date());
        }
        if (formDataJson.getString("managerComment") != null && formDataJson.getString("dispatchComment") == null) {
            cmcCarApproval.setManagerUserId(getLoginUser().getUserId());
            cmcCarApproval.setManagerComment(formDataJson.getString("managerComment"));
            cmcCarApproval.setManagerTime(new Date());
        }
        if (formDataJson.getString("gmComment") != null && formDataJson.getString("dispatchComment") == null) {
            cmcCarApproval.setGmUserId(getLoginUser().getUserId());
            cmcCarApproval.setGmComment(formDataJson.getString("gmComment"));
            cmcCarApproval.setGmTime(new Date());
        }
        if (formDataJson.getString("dszComment") != null && formDataJson.getString("dispatchComment") == null) {
            cmcCarApproval.setDszUserId(getLoginUser().getUserId());
            cmcCarApproval.setDszComment(formDataJson.getString("dszComment"));
            cmcCarApproval.setDszTime(new Date());
        }
        if (formDataJson.getString("unionComment") != null && formDataJson.getString("dispatchComment") == null) {
            cmcCarApproval.setUnionUserId(getLoginUser().getUserId());
            cmcCarApproval.setUnionComment(formDataJson.getString("unionComment"));
            cmcCarApproval.setUnionTime(new Date());
        }
        if (formDataJson.getString("dispatchComment") != null) {
            cmcCarApproval.setDispatcher(getLoginUser().getUserId());
            cmcCarApproval.setDispatchComment(formDataJson.getString("dispatchComment"));
            cmcCarApproval.setDispatchTime(new Date());
            cmcCarApproval.setReturnDate(formDataJson.getDate("returnDate"));
            cmcCarApproval.setKilometers(formDataJson.getString("kilometers"));
        }
        if (formDataJson.getJSONArray("cars").size() > 0) {
            String carString = formDataJson.getString("cars").substring(1, formDataJson.getString("cars").length() - 1);
            cmcCarApproval.setCars(carString);
            if (formDataJson.getString("projectId") != null && !formDataJson.getString("projectId").equals("")) {
                CmcProject cmcProject = new CmcProject();
                cmcProject.setProjectId(formDataJson.getString("projectId"));
                CmcProject project = cmcProjectService.selectCmcProjectByProjectId(cmcProject.getProjectId());
                if (project != null) {
                    if (project.getCars() != null) {
                        String[] projectCars = project.getCars().split(",");
                        String[] cars = carString.split(",");
                        project.setCars(String.join(",", CollectionUtils.union(Arrays.asList(projectCars), Arrays.asList(cars))));
                    }
                    else
                        project.setCars(carString);
                    cmcProjectService.updateCmcProject(project);
                }
            }
            String[] cars = carString.split(",");
            BigDecimal estimateCost = new BigDecimal(0);
            for (String car : cars) {
                CmcCar cmcCar = cmcCarService.selectCmcCarByCarId(Integer.parseInt(car));
                if (cmcCarApproval.getReturnDate() != null && cmcCar.getIsRent().equals("0"))
                    cmcCar.setStatus("1");
                else if (cmcCarApproval.getReturnDate() == null && cmcCar.getIsRent().equals("0"))
                    cmcCar.setStatus("0");
                else if (cmcCarApproval.getReturnDate() != null && cmcCar.getIsRent().equals("1"))
                    cmcCar.setStatus("3");
                else if (cmcCarApproval.getReturnDate() == null && cmcCar.getIsRent().equals("1"))
                    cmcCar.setStatus("0");
                if (cmcCar.getDayCost() != null)
                    estimateCost = estimateCost.add(cmcCar.getDayCost().multiply(new BigDecimal(cmcCarApproval.getDays())));
                cmcCarService.updateCmcCar(cmcCar);
            }
            cmcCarApproval.setEstimateCost(estimateCost);
        }
        if (formDataJson.getJSONArray("drivers").size() > 0) {
            cmcCarApproval.setDrivers(formDataJson.getString("drivers").substring(1, formDataJson.getString("drivers").length() - 1));
            if (formDataJson.getString("projectId") != null && !formDataJson.getString("projectId").equals("")) {
                CmcProject cmcProject = new CmcProject();
                cmcProject.setProjectId(formDataJson.getString("projectId"));
                CmcProject project = cmcProjectService.selectCmcProjectByProjectId(cmcProject.getProjectId());
                String driverString = formDataJson.getString("drivers").substring(1, formDataJson.getString("drivers").length() - 1);
                if (project.getDrivers() != null) {
                    String[] projectDrivers = project.getDrivers().split(",");
                    String[] drivers = driverString.split(",");
                    project.setDrivers(String.join(",", CollectionUtils.union(Arrays.asList(projectDrivers), Arrays.asList(drivers))));
                }
                else
                    project.setDrivers(driverString);
                cmcProjectService.updateCmcProject(project);
            }
        }
        cmcCarApprovalService.updateCmcCarApproval(cmcCarApproval);
        return AjaxResult.success("修改用车审批表成功");
    }

    /**
     * 删除cmc用车审批
     */
    @Log(title = "cmc用车审批", businessType = BusinessType.DELETE)
	@DeleteMapping("/{carApplyIds}")
    public AjaxResult remove(@PathVariable String[] carApplyIds)
    {
        return success(cmcCarApprovalService.deleteCmcCarApprovalByCarApplyIds(carApplyIds));
    }
}
