package com.chushang.inspection.work.controller;


import cn.hutool.core.util.StrUtil;
import com.chushang.common.core.web.AjaxResult;
import com.chushang.common.log.annotation.SysLog;
import com.chushang.common.log.enums.BusinessType;
import com.chushang.inspection.project.dto.Delete;
import com.chushang.inspection.utils.TaskConfigUtils;
import com.chushang.inspection.work.dto.WrkInfoDTO;
import com.chushang.inspection.work.query.DispatchQuery;
import com.chushang.inspection.work.query.ReviewedQuery;
import com.chushang.inspection.work.query.WrkAppQuery;
import com.chushang.inspection.work.query.WrkInfoQuery;
import com.chushang.inspection.work.service.WrkInfoService;
import com.chushang.security.annotation.RequiresPermissions;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;

/**
* 工单信息(wrk_info)表控制层
*
* @author xxxxx
*/
@Slf4j
@RestController
@RequestMapping("/wrk/info")
public class WrkInfoController {

    @Resource
    WrkInfoService wrkInfoService;

    /**
     * 导出
     * todo
     */
    @SysLog(value = "导出列表", businessType = BusinessType.EXPORT)
    @GetMapping("/exportDispatchPage")
    @RequiresPermissions("wrk:dispatch:export")
    public void exportDispatchPage(HttpServletResponse response, WrkInfoQuery query) {
        // 派单领取列表, 就是 已经派出的工单以及领取的工单,
        wrkInfoService.exportDispatchPage(response,query);

    }

    /**
     * 查询派单/领取列表 --> 查询派单领取
     * todo
     */
    @SysLog(value = "派单/领取列表", businessType = BusinessType.QUERY)
    @GetMapping("/dispatch/page")
    @RequiresPermissions("wrk:dispatch:page")
    public AjaxResult queryDispatchPage(@Validated WrkInfoQuery query) {
        // 派单领取列表, 就是 已经派出的工单以及领取的工单,
        return AjaxResult.success(wrkInfoService.queryDispatchPage(query));
    }

    /**
     * 查询待审核列表
     * todo
     *
     * @param query 条件
     */
    @SysLog(value = "待审核列表", businessType = BusinessType.QUERY)
    @GetMapping("/review/page")
    @RequiresPermissions("wrk:reviewed:page")
    public AjaxResult queryToDeReviewedPage(@Validated ReviewedQuery query)
    {
        int wrkStatus = query.getWrkStatus();
        List<Integer> status = new ArrayList<>();
        // 待初审
        if (2 == wrkStatus){
            status.add(2);
        }
        // 待复审, 应当查询审核方式为复审, 同时审核通过人员
        else if (3 == wrkStatus){
            status.add(3);
        }
        // 归档, 审核通过, 应当查询 审核方式为初审, 审核通过, 审核方式为复审, 审核通过
        else if (4 == wrkStatus){
            status.add(4);
            status.add(7);
            status.add(8);
        }
        // 否则就是获取全部
        query.setStates(status);
        return AjaxResult.success(wrkInfoService.queryArchivePage(query));
    }

    /**
     * app查询 工单列表
     *
     * @param query 条件
     */
    @SysLog(value = "app", businessType = BusinessType.QUERY)
    @GetMapping("/app/page")
    @RequiresPermissions("wrk:app:page")
    public AjaxResult queryAppPage(@Validated WrkAppQuery query)
    {
        Integer wrkStatus = query.getWrkStatus();
        List<Integer> status = new ArrayList<>();
        // 待初审 -->
        if (2 == wrkStatus){
            status.add(2);
            status.add(3);
        }
        // 待复审, 应当查询审核方式为复审, 同时审核通过人员
        else if (3 == wrkStatus){
            status.add(3);
            status.add(2);
        }
        // 归档, 审核通过, 应当查询 审核方式为初审, 审核通过, 审核方式为复审, 审核通过
        else if (4 == wrkStatus){
            status.add(4);
            status.add(7);
            status.add(8);
        }
        // 驳回
        else if (5 == wrkStatus){
            status.add(5);
            status.add(6);
        }
        query.setWrkStatusList(status);
        return AjaxResult.success(wrkInfoService.queryAppPage(query));
    }

    /**
     * 导出工单 word
     */
    @SysLog(value = "工单信息", businessType = BusinessType.DOWNLOAD)
    @GetMapping("/archive/export")
    @RequiresPermissions("wrk:archive:export")
    public AjaxResult downInsTemplate(@Validated ReviewedQuery query){
        Integer reviewMethod = TaskConfigUtils.reviewMethod(query.getTaskId());
        query.setStates(reviewMethod == 3 ? Lists.newArrayList(4) : Lists.newArrayList(3));
        return AjaxResult.success(wrkInfoService.downInsTemplate(query));
    }

    /**
     * 查询工单详情
     */
    @SysLog("工单详情")
    @GetMapping("/{wrkId}")
    @RequiresPermissions("wrk:info:detail")
    public AjaxResult info(@PathVariable Long wrkId)
    {
        return AjaxResult.success(wrkInfoService.queryWorkOrderDetails(wrkId));
    }

    /**
     * 批量派单/领取
     */
    @PostMapping("/dispatch/app")
    @RequiresPermissions("wrk:info:dispatch")
    @SysLog(value = "批量派单/领取", businessType = BusinessType.IMPORT)
    public AjaxResult dispatchApp(@RequestBody @Validated DispatchQuery query) {
        wrkInfoService.dispatch(query, 0);
        return AjaxResult.success();
    }

    /**
     * 批量派单/领取
     */
    @PostMapping("/dispatch")
    @RequiresPermissions("wrk:info:dispatch")
    @SysLog(value = "批量派单/领取", businessType = BusinessType.IMPORT)
    public AjaxResult dispatch(@RequestPart(value = "file", required = false) MultipartFile file, @Validated DispatchQuery query) {
        if (file.isEmpty()) {
            wrkInfoService.dispatch(query, 0);
            return AjaxResult.success();
        }
        try (Workbook workbook = WorkbookFactory.create(file.getInputStream())) {
            Sheet sheet = workbook.getSheetAt(0);
            // 商户编号行号
            int merchantIdRowNum = -1;
            // 终端编号行号
            int terminalIdRowNum = -1;

            NumberFormat nf = NumberFormat.getInstance();
            nf.setGroupingUsed(false);

            for (Row row : sheet) {
                if (row.getRowNum() == 0) {
                    for (Cell cell : row) {
                        if ("商户编号".equals(cell.getStringCellValue().trim())) {
                            merchantIdRowNum = cell.getColumnIndex();
                        } else if ("终端编号".equals(cell.getStringCellValue().trim())) {
                            terminalIdRowNum = cell.getColumnIndex();
                        }
                    }
                    continue;
                }
                if (merchantIdRowNum != -1) {
                    Cell cell = row.getCell(merchantIdRowNum);
                    switch (cell.getCellType()) {
                        case BLANK:
                            break;
                        case STRING:
                            query.getNos().add(StrUtil.trim(cell.getStringCellValue()));
                            break;
                        case NUMERIC:
                            Double aDouble = cell.getNumericCellValue();
                            query.getNos().add(nf.format(aDouble));
                            break;
                    }
                }
                if (terminalIdRowNum != -1) {
                    Cell cell = row.getCell(terminalIdRowNum);
                    switch (cell.getCellType()) {
                        case BLANK:
                            break;
                        case STRING:
                            query.getTerminalNos().add(StrUtil.trim(cell.getStringCellValue()));
                            break;
                        case NUMERIC:
                            Double aDouble = cell.getNumericCellValue();
                            query.getTerminalNos().add(nf.format(aDouble));
                            break;
                    }
                }
            }
        } catch (Exception e) {
            log.error("解析上传的文件失败", e);
        }
        wrkInfoService.dispatch(query, 0);
        return AjaxResult.success();
    }

    /**
     * 提交 工单
     */
    @PostMapping("/submit")
    @RequiresPermissions("wrk:submit")
    @SysLog(value = "工单提交", businessType = BusinessType.INSERT)
    public AjaxResult submit(@Validated @RequestBody WrkInfoDTO info) {
        wrkInfoService.submit(info);
        return AjaxResult.success();
    }


    /**
     * 撤回
     */
    @PostMapping("/withdraw")
    @RequiresPermissions("wrk:withdraw")
    @SysLog(value = "工单撤回", businessType = BusinessType.DELETE)
    public AjaxResult withdraw(@RequestBody @Validated Delete delete) throws Exception{
        wrkInfoService.withdraw(delete.getIds());
        return AjaxResult.success();
    }


}
