package org.jeecg.modules.workOrder.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.mapper.SysUserMapper;
import org.jeecg.modules.workOrder.entity.WorkDivision;
import org.jeecg.modules.workOrder.entity.WorkOrder;
import org.jeecg.modules.workOrder.mapper.WorkOrderMapper;
import org.jeecg.modules.workOrder.service.IWorkDivisionService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 实际派工表
 * @Author: jeecg-boot
 * @Date: 2025-06-11
 * @Version: V1.0
 */
@Api(tags = "实际派工表")
@RestController
@RequestMapping("/workOrder/workDivision")
@Slf4j
public class WorkDivisionController extends JeecgController<WorkDivision, IWorkDivisionService> {
    @Autowired
    private IWorkDivisionService workDivisionService;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private WorkOrderMapper workOrderMapper;

    /**
     * 分页列表查询
     *
     * @param workDivision
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "实际派工表-分页列表查询")
    @ApiOperation(value = "实际派工表-分页列表查询", notes = "实际派工表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<WorkDivision>> queryPageList(WorkDivision workDivision,
                                                     @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                     @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                     HttpServletRequest req) {
        QueryWrapper<WorkDivision> queryWrapper = QueryGenerator.initQueryWrapper(workDivision, req.getParameterMap());
        Page<WorkDivision> page = new Page<WorkDivision>(pageNo, pageSize);
        IPage<WorkDivision> pageList = workDivisionService.page(page, queryWrapper);
        pageList.getRecords().forEach(pgl->{
            SysUser user = sysUserMapper.selectById(pgl.getExecutor());
            pgl.setExecutorName(user.getRealname());
            pgl.setExecPhone(user.getPhone());
            pgl.setPostage(user.getPost());
        });
        return Result.OK(pageList);
    }

    @ApiOperation(value = "实际派工表-列表查询", notes = "实际派工表-列表查询")
    @GetMapping(value = "/allist")
    public Result<List<WorkDivision>> queryList(WorkDivision workDivision, HttpServletRequest req) {
        LambdaQueryWrapper<WorkDivision> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WorkDivision::getWorkOrder, workDivision.getWorkOrder());
        List<WorkDivision> ist = workDivisionService.list(queryWrapper);
        ist.forEach(pgl -> {
            SysUser user = sysUserMapper.selectById(pgl.getExecutor());
            pgl.setExecutorName(user.getRealname());
            pgl.setExecPhone(user.getPhone());
        });
        return Result.OK(ist);
    }

    /**
     * 添加
     *
     * @param workDivision
     * @return
     */
    @AutoLog(value = "实际派工表-添加")
    @ApiOperation(value = "实际派工表-添加", notes = "实际派工表-添加")
    //@RequiresPermissions("org.jeecg.modules:bu_work_division:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody WorkDivision workDivision) {
        try {
            return workDivisionService.saves(workDivision)?Result.OK("派工成功！"):Result.error("派工失败！");
        } catch (Exception e){
            return Result.error(e.getMessage());
        }
    }

    @AutoLog(value = "实际派工表-取消派工")
    @ApiOperation(value = "实际派工表-取消派工", notes = "实际派工表-取消派工")
    //@RequiresPermissions("org.jeecg.modules:bu_work_division:add")
    @DeleteMapping(value = "/cancel")
    public Result<String> cancel(@RequestParam(name = "workOrder", required = true) String workOrder) {
        workOrderMapper.update(null, new LambdaUpdateWrapper<WorkOrder>().set(WorkOrder::getStatus, 0)
                .eq(WorkOrder::getId, workOrder));
        if (workDivisionService.remove(new LambdaQueryWrapper<WorkDivision>().eq(WorkDivision::getWorkOrder, workOrder))) {
            return Result.OK("取消派工成功！");
        } else {
            return Result.error("取消派工失败！");
        }
    }

    /**
     * 编辑
     *
     * @param workDivision
     * @return
     */
    @AutoLog(value = "实际派工表-编辑")
    @ApiOperation(value = "实际派工表-编辑", notes = "实际派工表-编辑")
    //@RequiresPermissions("org.jeecg.modules:bu_work_division:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody WorkDivision workDivision) {
        workDivisionService.updateById(workDivision);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "实际派工表-通过id删除")
    @ApiOperation(value = "实际派工表-通过id删除", notes = "实际派工表-通过id删除")
    //@RequiresPermissions("org.jeecg.modules:bu_work_division:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        WorkDivision workDivision = workDivisionService.getById(id);
        if(workDivisionService.count(new LambdaQueryWrapper<WorkDivision>().eq(WorkDivision::getWorkOrder, workDivision.getWorkOrder()))== 0) {
            // 当不存在派工人员时，回置该工单状态
            workOrderMapper.update(null, new LambdaUpdateWrapper<WorkOrder>().set(WorkOrder::getStatus, 0).set(WorkOrder::getCoordinator, null)
                    .eq(WorkOrder::getId, workDivision.getWorkOrder()));
        }
        workDivisionService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "实际派工表-批量删除")
    @ApiOperation(value = "实际派工表-批量删除", notes = "实际派工表-批量删除")
    //@RequiresPermissions("org.jeecg.modules:bu_work_division:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.workDivisionService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "实际派工表-通过id查询")
    @ApiOperation(value = "实际派工表-通过id查询", notes = "实际派工表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<WorkDivision> queryById(@RequestParam(name = "id", required = true) String id) {
        WorkDivision workDivision = workDivisionService.getById(id);
        if (workDivision == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(workDivision);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param workDivision
     */
    //@RequiresPermissions("org.jeecg.modules:bu_work_division:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, WorkDivision workDivision) {
        return super.exportXls(request, workDivision, WorkDivision.class, "实际派工表");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    //@RequiresPermissions("bu_work_division:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, WorkDivision.class);
    }

}
