package com.ruoyi.web.controller.oa;

import java.math.BigDecimal;
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.ICmcCarService;
import com.ruoyi.system.service.ISysUserService;
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;

    /**
     * 查询cmc用车审批列表
     */
    @GetMapping("/list")
    public TableDataInfo list(CmcCarApproval cmcCarApproval)
    {
        startPage();
        List<CmcCarApproval> list = cmcCarApprovalService.selectCmcCarApprovalList(cmcCarApproval);
        for(CmcCarApproval carApproval : list) {
            String carIds = carApproval.getCars();
            StringBuilder carNames = new StringBuilder();
            if (carIds != null && !carIds.equals("") && carIds.split(",").length > 0) {
                for (String carId : carIds.split(","))
                    carNames.append(cmcCarService.selectCmcCarByCarId(Integer.parseInt(carId)).getLicensePlate()).append(",");
                carApproval.setCarNames(carNames.substring(0, carNames.length() - 1));
            }
            String driverIds = carApproval.getDrivers();
            StringBuilder driverNames = new StringBuilder();
            if (driverIds != null && !driverIds.equals("") && driverIds.split(",").length > 0) {
                for (String driverId : driverIds.split(","))
                    driverNames.append(userService.selectUserById(Long.parseLong(driverId)).getNickName()).append(",");
                carApproval.setDriverNames(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();
            StringBuilder carNames = new StringBuilder();
            if (carIds != null && !carIds.equals("") && carIds.split(",").length > 0) {
                for (String carId : carIds.split(","))
                    carNames.append(cmcCarService.selectCmcCarByCarId(Integer.parseInt(carId)).getLicensePlate()).append(",");
                carApproval.setCarNames(carNames.substring(0, carNames.length() - 1));
            }
            String driverIds = carApproval.getDrivers();
            StringBuilder driverNames = new StringBuilder();
            if (driverIds != null && !driverIds.equals("") && driverIds.split(",").length > 0) {
                for (String driverId : driverIds.split(","))
                    driverNames.append(userService.selectUserById(Long.parseLong(driverId)).getNickName()).append(",");
                carApproval.setDriverNames(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(@RequestParam("form")String formData)
    {
        JSONObject formDataJson = JSONObject.parse(formData);
        CmcCarApproval cmcCarApproval = cmcCarApprovalService.selectCmcCarApprovalByCarApplyId(formDataJson.getString("carApplyId"));
        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());
        }
        if (formDataJson.getJSONArray("cars").size() > 0 && formDataJson.getJSONArray("drivers").size() > 0) {
            cmcCarApproval.setDispatcher(getLoginUser().getUserId());
            String carString = formDataJson.getString("cars").substring(1, formDataJson.getString("cars").length() - 1);
            cmcCarApproval.setCars(carString);
            cmcCarApproval.setDrivers(formDataJson.getString("drivers").substring(1, formDataJson.getString("drivers").length() - 1));
            String[] cars = carString.split(",");
            BigDecimal estimateCost = new BigDecimal(0);
            for (String car : cars) {
                CmcCar cmcCar = cmcCarService.selectCmcCarByCarId(Integer.parseInt(car));
                cmcCar.setStatus("0");
                if (cmcCar.getDayCost() != null)
                    estimateCost = estimateCost.add(cmcCar.getDayCost().multiply(new BigDecimal(cmcCarApproval.getDays())));
            }
            cmcCarApproval.setEstimateCost(estimateCost);
        }
        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));
    }
}
