package cn.iocoder.yudao.module.inspection.controller;

import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.inspection.entity.InspectionInfo;
import cn.iocoder.yudao.module.inspection.entity.InspectionWorkNode;
import cn.iocoder.yudao.module.inspection.service.AppInspectionPartnerService;
import cn.iocoder.yudao.module.inspection.service.IInspectionInfoService;
import cn.iocoder.yudao.module.inspection.service.IInspectionWorkNodeService;
import cn.iocoder.yudao.module.inspection.vo.InspectionInfoVo;
import cn.iocoder.yudao.util.ExcelUtil;
//import cn.iocoder.yudao.util.WordUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import cn.iocoder.yudao.module.core.controller.BaseController;

/**
 * 【请填写功能名称】Controller
 *
 * @author ruoyi
 * @date 2023-08-13
 */
@RestController
@RequestMapping("/admin-api/system/info")
public class InspectionInfoController extends BaseController {
    @Autowired
    private IInspectionInfoService inspectionInfoService;

    @Autowired
    private IInspectionWorkNodeService inspectionWorkNodeService;
    @Autowired
    private AppInspectionPartnerService partnerList;

    /**
     * 查询【请填写功能名称】列表
     */
    @PreAuthorize("@ss.hasPermi('system:info:list')")
    @GetMapping("/list")
    public CommonResult list(InspectionInfo inspectionInfo,
                             @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
                             @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) {
        Page<InspectionInfo> page = new Page<>(pageNum, pageSize);
        IPage<InspectionInfo> list = inspectionInfoService.selectInspectionInfoList(page, inspectionInfo);
        return success(list);
    }

    /**
     * 导出【请填写功能名称】列表
     */
    @PreAuthorize("@ss.hasPermi('system:info:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, InspectionInfo inspectionInfo,
                       @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
                       @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) {
        Page<InspectionInfo> page = new Page<>(pageNum, pageSize);
        IPage<InspectionInfo> list = inspectionInfoService.selectInspectionInfoList(page, inspectionInfo);
        ExcelUtil<InspectionInfo> util = new ExcelUtil<InspectionInfo>(InspectionInfo.class);
        util.exportExcel(response, list.getRecords(), "【请填写功能名称】数据");
    }

    /**
     * 获取【请填写功能名称】详细信息
     */
//    @PreAuthorize("@ss.hasPermi('system:info:query')")
    @GetMapping(value = "/{id}")
    public CommonResult getInfo(@PathVariable("id") Long id) {
        return success(inspectionInfoService.selectInspectionInfoById(id));
    }

    /**
     * 新增【请填写功能名称】
     */
    @PostMapping("/add")
    public CommonResult add(@RequestBody InspectionInfo inspectionInfo) throws Exception {

        return toAjax(inspectionInfoService.insertInspectionInfo(inspectionInfo));
    }

    /**
     * 清账
     */
    @PostMapping("/settleAccounts")
    public CommonResult settleAccounts(Long InspectionId) {
        inspectionInfoService.settleAccounts(InspectionId);
        return success();
    }


    @PostMapping("/update")
    public CommonResult edit(@RequestBody InspectionInfo inspectionInfo) throws Exception {
        return toAjax(inspectionInfoService.updateInspectionInfo(inspectionInfo));
    }

    @PostMapping("/updateLeadMan")
    public CommonResult updateLeadMan(@RequestBody InspectionInfo inspectionInfo) {
        return toAjax(inspectionInfoService.updateLeadMan(inspectionInfo));
    }


    @PostMapping("/del")
    public CommonResult remove(@RequestParam("id") Long id) {
        return toAjax(inspectionInfoService.deleteInspectionInfoByIds(id));
    }

    /**
     * 根据当前登陆人获取可以选择的工单
     *
     * @return
     */
    @GetMapping("geStelectInspection")
    public CommonResult geStelectInspection(InspectionInfo inspectionInfo,
                                            @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
                                            @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) {
        Page<InspectionInfo> page = new Page<>(pageNum, pageSize);
        return success(inspectionInfoService.geStelectInspection(page, inspectionInfo));
    }

    /**
     * 根据当前登陆人获取可以选择的工单（业务经理查询）
     *
     * @return
     */
    @GetMapping("geStelectInspectionByBusiness")
    public CommonResult geStelectInspectionByBusiness(InspectionInfo inspectionInfo,
                                                      @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
                                                      @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) {
        Page<InspectionInfo> page = new Page<>(pageNum, pageSize);
        return success(inspectionInfoService.geStelectInspectionByBusiness(page, inspectionInfo));
    }

    /**
     * 获取工单详情
     *
     * @param inspectionId 工单id
     * @param workNodeId   节点id （geStelectInspection这个方法中返回了）
     * @return
     */
    @GetMapping("getInspectionInfo")
    public CommonResult getInspectionInfo(Integer inspectionId, String workNodeId) {
        return success(inspectionInfoService.getWorkNode(inspectionId, workNodeId));
    }

    /**
     * 员工接单
     *
     * @param inspectionId 工单id
     * @param workNodeId   节点id （geStelectInspection这个方法中返回了）
     * @return
     */
    @PostMapping("orderTaking")
    public CommonResult orderTaking(Integer inspectionId, String workNodeId) {
        inspectionWorkNodeService.updateInspectionWorkNode(inspectionId, workNodeId);
        return success("接单成功");
    }

    /**
     * 员工取消接单
     *
     * @param inspectionId 工单id
     * @param workNodeId   节点id （geStelectInspection这个方法中返回了）
     * @return
     */
    @PostMapping("cancelAnOrder")
    public CommonResult cancelAnOrder(Integer inspectionId, String workNodeId) {
        inspectionWorkNodeService.cancelAnOrder(inspectionId, workNodeId);
        return success("接单成功");
    }

    /**
     * 项目操作（退办理、重审、项目完成）
     *
     * @param inspectionWorkNode
     */
    @PostMapping("controls")
    public CommonResult controls(@RequestBody InspectionWorkNode inspectionWorkNode) {
        inspectionWorkNodeService.updateImageAndStep(inspectionWorkNode);
        return success("操作成功");
    }

    /**
     * 通过工单id获取工单流程
     *
     * @param inspectionId
     * @return
     */
    @GetMapping("getWeorkNodesById")
    public CommonResult getWeorkNodesById(Integer inspectionId) {
        return success(inspectionInfoService.getWeorkNodesById(inspectionId));
    }

    /**
     * 判断是否需要上传图片
     *
     * @param inspectionId
     * @param workNodeId
     * @return
     */
    @GetMapping("orImages")
    public CommonResult orImages(Integer inspectionId, String workNodeId) {
        return success(inspectionWorkNodeService.orImages(inspectionId, workNodeId));
    }

    /**
     * 分页查询节点提成
     *
     * @param inspectionWorkNode
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("getRoyaltyList")
    public CommonResult getRoyaltyList(InspectionWorkNode inspectionWorkNode,
                                       @RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNum,
                                       @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) {
        IPage page = new Page(pageNum, pageSize);
        return success(inspectionWorkNodeService.getRoyaltyList(page, inspectionWorkNode));
    }

    /**
     * 获取提成总金额
     *
     * @param inspectionWorkNode
     * @return
     */
    @GetMapping("getRoyaltySum")
    public CommonResult getRoyaltySum(InspectionWorkNode inspectionWorkNode) {
        return success(inspectionWorkNodeService.getRoyaltySum(inspectionWorkNode));
    }


    /**
     * app分页查询节点提成
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("getRoyaltyListApp")
    public CommonResult getRoyaltyListApp(InspectionWorkNode inspectionWorkNode,
                                          @RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNum,
                                          @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) {
        //获取当前登陆人
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        inspectionWorkNode.setDealUserId(loginUser.getId());
        IPage page = new Page(pageNum, pageSize);
        return success(inspectionWorkNodeService.getRoyaltyList(page, inspectionWorkNode));
    }

    /**
     * 获取提成总金额app
     *
     * @return
     */
    @GetMapping("getRoyaltySumApp")
    public CommonResult getRoyaltySumApp(InspectionWorkNode inspectionWorkNode) {
        //获取当前登陆人
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        inspectionWorkNode.setDealUserId(loginUser.getId());
        return success(inspectionWorkNodeService.getRoyaltySum(inspectionWorkNode));
    }

    /**
     * 重新审核
     *
     * @param inspectionWorkNode
     * @return
     */
    @PostMapping("recheck")
    public CommonResult recheck(@RequestBody InspectionWorkNode inspectionWorkNode) {
        inspectionWorkNodeService.recheck(inspectionWorkNode);
        //发送消息提醒
        return success("操作成功");
    }

    /**
     * 判断当前登陆人是否有重检、重审、退办理的权限（app）
     *
     * @return
     */
    @GetMapping("isExamine")
    public CommonResult isExamine() {
        return success(inspectionInfoService.isExamine("jcsfdl"));
    }

    /**
     * 获取某个工单针对当前操作用户，某个状态的项目们
     *
     * @param id     工单ID
     * @param status 状态
     * @param flag   状态字段是否生效，默认生效
     * @author 小李
     * @date 10:48 2024/12/11
     **/
    @GetMapping("/getWorkNodeByIdAndNow")
    public CommonResult<?> getWorkNodeByIdAndNow(Long id, String status, @RequestParam(value = "flag", defaultValue = "true") Boolean flag) {
        return success(inspectionInfoService.getWorkNodeByIdAndNow(id, status, flag));
    }

    /**
     * 判断是否可以修改引车员
     *
     * @param id 工单ID
     * @author 小李
     * @date 15:22 2024/12/11
     **/
    @GetMapping("/judgeUpdateLeadMan")
    public CommonResult<?> judgeUpdateLeadMan(Long id) {
        return success(inspectionInfoService.judgeUpdateLeadMan(id));
    }

    /**
     * 判断当前登陆人是否有重检、重审、退办理的权限（app）
     *
     * @return
     */
    @GetMapping("getRoleList")
    public CommonResult getRoleList() {
        return success(inspectionInfoService.getRoleList());
    }

    @GetMapping("getWordContent")
    public CommonResult getWordContent(InspectionInfo inspectionInfo) {
        //根据工单id查询工单信息
        InspectionInfoVo inspectionInfoVo = partnerList.inspectionDetail(inspectionInfo.getId());
        InspectionInfo inspectionInfos = inspectionInfoService.selectInspectionInfoById(inspectionInfo.getId());
        Map<String, Object> map = new HashMap<>();
        Date endTime = inspectionInfos.getEndTime();
        // 创建 Calendar 实例并设置时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(endTime);

        // 获取年、月、日
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1; // 月份从0开始，所以需要加1
        int day = calendar.get(Calendar.DAY_OF_MONTH);

        map.put("vin", inspectionInfos.getCarIdNo());
        map.put("day", day);
        map.put("one", "□");
        map.put("two", "□");
        map.put("three", "□");
        map.put("four", "√");
        map.put("month", month);
        map.put("year", year);
        map.put("carNum", inspectionInfoVo.getCarNum());
        map.put("userName", inspectionInfos.getBuyName());
        //TODO 还差编号和检验报告编号 告知书编号规则：8位行政区划号码+2位年份号码+4位顺序号，例如：51132201240009。 暂时写死
        StringBuilder sb = new StringBuilder();
        sb.append("51132201");
        //获取年份第二位
        DateTime now = DateUtil.date();
        String yearStr = DateUtil.format(now, "yy");
        sb.append(yearStr);
        sb.append("0001");//顺序号 暂时写死
        map.put("id", "1111111111");
        map.put("reportId", sb);

        return success(map);
    }

    /**
     * 根据模板导出word
     */
    @PostMapping("/exportWord")
    public CommonResult exportWord(HttpServletRequest request, HttpServletResponse response, @RequestBody Map map) {
        String str = UUID.randomUUID().toString() + ".docx";
        String name = inspectionInfoService.easyPoiExport("template/word/四川省超标排放汽车维护修理告知书.docx", str, map, request, response);
        return CommonResult.success(name);
    }

    /**
     * 获得不同状态的数据的数量
     *
     * @author 小李
     * @date 16:22 2024/12/18
     **/
    @GetMapping("/getCountByType")
    public CommonResult<?> getCountByType(@RequestParam(required = false, name = "partnerId") Integer partnerId) {
        return success(inspectionInfoService.getCountByType(partnerId));
    }

    /**
     * 获得不同状态的数据的数量
     *
     * @author 小李
     * @date 16:22 2024/12/18
     **/
    @GetMapping("/getBusinessCountByType")
    public CommonResult<?> getBusinessCountByType(@RequestParam(required = false, name = "partnerId") Integer partnerId,
                                                  @RequestParam(required = false, name = "unit") String unit) {
        List<String> datetimeRange = new ArrayList<>();
        if (unit != null) {
            DateTime now = DateUtil.date();
            switch (unit) {
                case "day":
                    datetimeRange.add(String.valueOf(DateUtil.beginOfDay(now)));
                    datetimeRange.add(String.valueOf(DateUtil.endOfDay(now)));
                    break;
                case "week":
                    datetimeRange.add(String.valueOf(DateUtil.beginOfWeek(now)));
                    datetimeRange.add(String.valueOf(DateUtil.endOfWeek(now)));
                    break;
                case "month":
                    datetimeRange.add(String.valueOf(DateUtil.beginOfMonth(now)));
                    datetimeRange.add(String.valueOf(DateUtil.endOfMonth(now)));
                    break;
            }
        }
        return success(inspectionInfoService.getBusinessCountByType(partnerId,datetimeRange));
    }

    /**
     * 接车拍照
     *
     * @param inspectionWorkNode
     * @return
     */
    @PostMapping("/meetCarPhoto")
    public CommonResult<?> meetCarPhoto(@RequestBody InspectionWorkNode inspectionWorkNode) {
        return success(inspectionInfoService.meetCarPhoto(inspectionWorkNode));
    }

    /**
     * 还车拍照
     *
     * @param inspectionWorkNode
     * @return
     */
    @PostMapping("/returnCarPhoto")
    public CommonResult<?> returnCarPhoto(@RequestBody InspectionWorkNode inspectionWorkNode) {
        return success(inspectionInfoService.returnCarPhoto(inspectionWorkNode));
    }

    /**
     * 修改异常工单
     *
     * @param inspectionWorkNode
     * @return
     */
    @PostMapping("/updateException")
    public CommonResult<?> updateException(@RequestBody InspectionWorkNode inspectionWorkNode) {
        inspectionWorkNodeService.updateException(inspectionWorkNode.getInspectionInfoId(), inspectionWorkNode.getIdList());
        return success("操作成功");
    }

    /**
     * 员工 引车接单
     *
     * @return
     */
    @PostMapping("/leadCar")
    public CommonResult<?> leadCar(@RequestBody InspectionInfo inspectionInfo) {
        inspectionInfoService.leadCar(inspectionInfo);
        return success("操作成功");
    }
}
