package com.ruoyi.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.cs.domain.CsResourceOrderApply;
import com.ruoyi.cs.domain.CsSetTemplate;
import com.ruoyi.cs.domain.ResourceOrderApplyListVO;
import com.ruoyi.cs.domain.ResourceOrderApplyVO;
import com.ruoyi.cs.domain.dto.CsOrderApplyEditDTO;
import com.ruoyi.cs.domain.dto.CsResourceOrderApplyEditDTO;
import com.ruoyi.cs.domain.dto.CsResourceOrderApplyManageCheckDTO;
import com.ruoyi.cs.mapper.CsSetTemplateMapper;
import com.ruoyi.cs.service.ICsAnnexService;
import com.ruoyi.cs.service.ICsResourceOrderApplyService;
import com.ruoyi.mall.domain.UserChoosetype;
import com.ruoyi.mall.mapper.UserChoosetypeMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import io.swagger.annotations.Api;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 管理端PC/资源、工单申请
 *
 * @author ruoyi
 * @date 2024-04-23
 */
@Api("管理端PC/资源工单")
@RestController
@RequestMapping("/cs/csResourceOrderApply")
public class CsResourceOrderApplyController extends BaseController
{
    @Resource
    private ICsResourceOrderApplyService csResourceOrderApplyService;

    @Resource
    private SysUserRoleMapper sysUserRoleMapper;
    @Resource
    private UserChoosetypeMapper userChoosetypeMapper;

    @Resource
    private CsSetTemplateMapper csSetTemplateMapper;
    @Resource
    private ICsAnnexService csAnnexService;

    /**
     * 查询资源、工单申请列表
     */
    @PreAuthorize("@ss.hasPermi('cs:csResourceOrderApply:list')")
    @GetMapping("/list")
    public TableDataInfo list(CsResourceOrderApply csResourceOrderApply)
    {
        csResourceOrderApply.setDelFlag("0");
        // 获取登陆用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
       /* if (loginUser != null && loginUser.getUserId() != 1) {
            csResourceOrderApply.setCurrentNodeApprover(loginUser.getUserId().toString());
        }*/
        if (StringUtils.isNull(loginUser)){
            return getDataTable(new ArrayList<>());
        }
        UserChoosetype choosetype = new UserChoosetype();
        choosetype.setUserId(loginUser.getUserId());
        List<UserChoosetype> userChoosetypes = userChoosetypeMapper.selectUserChoosetypeList(choosetype);
        Map<String, List<UserChoosetype>> map =
                userChoosetypes.stream().collect(Collectors.groupingBy(UserChoosetype::getClassType));
        csResourceOrderApply.setOrderClassIds(CollectionUtils.isEmpty(map.get("1")) ? null :
                map.get("1").stream().map(UserChoosetype::getChooseClassId).collect(Collectors.toList()));
        csResourceOrderApply.setResourceOrderClassIds(CollectionUtils.isEmpty(map.get("2")) ? null :
                map.get("2").stream().map(UserChoosetype::getChooseClassId).collect(Collectors.toList()));
        csResourceOrderApply.setCurrentNodeApproverParams(String.valueOf(loginUser.getUserId()));
        startPage();
        List<ResourceOrderApplyListVO> list = csResourceOrderApplyService.selectResourceOrderApplyList(csResourceOrderApply);


        return getDataTable(list);
    }

    /**
     * 导出工单列表
     */
    @PreAuthorize("@ss.hasPermi('cs:csResourceOrderApply:export')")
    @Log(title = "工单列表", businessType = BusinessType.EXPORT)
    @PostMapping("/exportOrderApplyList")
    public void exportOrderApplyList(HttpServletResponse response, CsResourceOrderApply csResourceOrderApply)
    {
        csResourceOrderApply.setDelFlag("0");
        List<ResourceOrderApplyListVO> list = csResourceOrderApplyService.selectResourceOrderApplyList(csResourceOrderApply);
        ExcelUtil<ResourceOrderApplyListVO> util = new ExcelUtil<ResourceOrderApplyListVO>(ResourceOrderApplyListVO.class);
        util.exportExcel(response, list, "工单列表");
    }

    /**
     * 导出资源申请账号
     */
    @PreAuthorize("@ss.hasPermi('cs:csResourceOrderApply:export')")
    @Log(title = "资源申请账号", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CsResourceOrderApply csResourceOrderApply)
    {
        csResourceOrderApply.setDelFlag("0");
        List<ResourceOrderApplyVO> list = csResourceOrderApplyService.selectCsResourceOrderApplyList(csResourceOrderApply);
        if (CollectionUtil.isNotEmpty(list)){
            list.forEach(item -> {
                item.setUserName(item.getName());
                item.setUserCompanyName(item.getCompanyName());
            });
        }
        ExcelUtil<ResourceOrderApplyVO> util = new ExcelUtil<ResourceOrderApplyVO>(ResourceOrderApplyVO.class);
        util.exportExcel(response, list, "资源申请账号");
    }

    /**
     * 获取资源、工单申请详细信息
     */
    @PreAuthorize("@ss.hasPermi('cs:csResourceOrderApply:query')")
    @GetMapping(value = "/{applyId}")
    public AjaxResult getInfo(@PathVariable("applyId") String applyId)
    {
        return AjaxResult.success(csResourceOrderApplyService.selectCsResourceOrderApplyByApplyId(applyId));
    }

    /**
     * 新增资源、工单申请
     */
    @PreAuthorize("@ss.hasPermi('cs:csResourceOrderApply:add')")
    @Log(title = "资源、工单申请", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CsResourceOrderApply csResourceOrderApply)
    {
        return toAjax(csResourceOrderApplyService.insertCsResourceOrderApply(csResourceOrderApply));
    }

    /**
     * 修改资源、工单申请
     */
    @PreAuthorize("@ss.hasPermi('cs:csResourceOrderApply:edit')")
    @Log(title = "资源、工单申请", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CsResourceOrderApply csResourceOrderApply)
    {
        return toAjax(csResourceOrderApplyService.updateCsResourceOrderApply(csResourceOrderApply));
    }

    /**
     * 删除资源、工单申请
     */
    @PreAuthorize("@ss.hasPermi('cs:csResourceOrderApply:remove')")
    @Log(title = "资源、工单申请", businessType = BusinessType.DELETE)
	@DeleteMapping("/{applyIds}")
    public AjaxResult remove(@PathVariable String[] applyIds)
    {
        return toAjax(csResourceOrderApplyService.deleteCsResourceOrderApplyByApplyIds(applyIds));
    }

    /**
     * 获取资源申请详细信息
     */
    @PreAuthorize("@ss.hasPermi('cs:csResourceOrderApply:query')")
    @GetMapping(value = "/getResourceApplyDetail/{applyId}")
    public AjaxResult getResourceApplyDetail(@PathVariable("applyId") String applyId)
    {
        return AjaxResult.success(csResourceOrderApplyService.applyForResourceDetail(applyId));
    }

    /**
     * 审批资源申请
     */
    @PreAuthorize("@ss.hasPermi('cs:csResourceOrderApply:edit')")
    @Log(title = "管理端PC编辑资源申请", businessType = BusinessType.UPDATE)
    @PutMapping("/editResourceApply")
    public AjaxResult editResourceApply(@RequestBody CsResourceOrderApplyEditDTO editDTO)
    {
        return toAjax(csResourceOrderApplyService.updateApplyForResource(editDTO));
    }

    /**
     * 审核资源申请 拒绝/通过
     */
    @PreAuthorize("@ss.hasPermi('cs:csResourceOrderApply:check')")
    @Log(title = "管理端PC编辑资源申请", businessType = BusinessType.UPDATE)
    @PutMapping("/checkResourceApply")
    public AjaxResult checkResourceApply(@RequestBody CsResourceOrderApplyManageCheckDTO  checkDTO)
    {
        return toAjax(csResourceOrderApplyService.checkApplyForResourceAndManager(checkDTO));
    }

    /**
     * 工单详情
     */
    @GetMapping(value = "/getOrderDetail/{applyId}")
    public AjaxResult getOrderDetail(@PathVariable("applyId") String applyId)
    {
        return AjaxResult.success(csResourceOrderApplyService.applyForOrderDetail(applyId));
    }

    /**
     * 处理工单申请
     * @param orderDTO 参数
     * @return 结果
     */
    @RepeatSubmit
    @Log(title = "处理工单申请", businessType = BusinessType.UPDATE)
    @PostMapping("/handleOrderApply")
    public AjaxResult handleOrderApply(@RequestBody CsOrderApplyEditDTO orderDTO){
        return toAjax(csResourceOrderApplyService.handleApplyForOrder(orderDTO));
    }

    /**
     * 编辑工单申请
     * @param orderDTO 参数
     * @return 结果
     */
    @RepeatSubmit
    @Log(title = "编辑工单申请", businessType = BusinessType.UPDATE)
    @PostMapping("/editOrderApply")
    public AjaxResult editOrderApply(@RequestBody CsOrderApplyEditDTO orderDTO){

        CsResourceOrderApply resourceOrderApply = csResourceOrderApplyService.selectCsResourceOrderApplyByApplyId(orderDTO.getApplyId());
        if (resourceOrderApply == null) {
            return AjaxResult.error("该状态不可编辑");
        }
        return toAjax(csResourceOrderApplyService.editApplyForOrder(orderDTO));
    }

    /**
     * 通过表单值获取模版设置详细信息
     */
    @GetMapping("/getInfoByFormValue")
    public AjaxResult getInfoByFormValue(CsSetTemplate csSetTemplate){
        return AjaxResult.success(csSetTemplateMapper.getInfoByFormValue(csSetTemplate.getFormValue()));
    }
}
