package yangtz.cs.liu.campus.controller.device;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.core.controller.BaseController;
import yangtz.cs.liu.activiti.service.IProcessService;
import yangtz.cs.liu.campus.domain.area.SchoolArea;
import yangtz.cs.liu.campus.domain.device.SchoolDeviceRecord;
import yangtz.cs.liu.campus.service.device.ISchoolDeviceRecordService;
import yangtz.cs.liu.campus.service.device.ISchoolDeviceService;
import yangtz.cs.liu.campus.vo.device.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.core.constant.ProcessCommon.ROLEKEY;
import static com.core.constant.ProcessDefinition.INSTANDHALTUNG;
import static com.core.constant.ProcessDefinition.VEHICLEAPPLICATION;
import static yangtz.cs.liu.campus.constant.ProcessState.PASS;
import static yangtz.cs.liu.campus.constant.ProcessState.REFUSE;

/**
 * 设备维修Controller
 *
 * @author ruoyi
 * @date 2022-10-16
 */
@RestController
@RequestMapping("/deviceRecord")
public class SchoolDeviceRecordController extends BaseController {
    @Autowired
    private ISchoolDeviceRecordService schoolDeviceRecordService;
    @Autowired
    private ISchoolDeviceService schoolDeviceService;
    @Autowired
    private IProcessService processService;

    @ApiOperation("列表查询")
    @GetMapping("/list")
    public TableDataInfo list(String submitState, RecordListVo recordListVo) {
        startPage();
        List<RecordListVo> list = schoolDeviceRecordService.queryList(submitState, recordListVo);
        return getDataTable(list);
    }

    /**
     * 获取维修申请详细信息
     */
    @ApiOperation("id查询")
    @GetMapping("/queryById/{id}")
    public AjaxResult queryById(@PathVariable("id") Long id) {
//        SchoolDeviceRecord schoolDeviceRecord = schoolDeviceRecordService.getById(id);
//        RecordByIdVo entity = new RecordByIdVo();
//        BeanUtils.copyProperties(schoolDeviceRecord,entity);
//        String deviceName = schoolDeviceService.getById(schoolDeviceRecord.getDeviceId()).getDeviceName();
//        entity.setDeviceName(deviceName);
//        switch (schoolDeviceRecord.getRepairType()){  //保修类型
//            case ("0"):entity.setRepairType("故障维修");break;
//            case ("1"):entity.setRepairType("设备更换");break;
//        }
        RecordByIdVo entity = schoolDeviceRecordService.getInfo(id);
        return AjaxResult.success(entity);
    }

    /**
     * 新增维修申请
     */
    @PostMapping("/add")
    public AjaxResult add(@RequestBody @Validated SchoolDeviceRecord schoolDeviceRecord) {
        schoolDeviceRecord.setType("Instandhaltung");
        schoolDeviceRecord.setReportingTime(DateUtils.getNowDate());
        return toAjax(schoolDeviceRecordService.save(schoolDeviceRecord));
    }

    /**
     * 修改场地申请
     */
    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody @Validated SchoolDeviceRecord schoolDeviceRecord) {
        if (StringUtils.isNull(schoolDeviceRecord.getId())) {
            throw new ServiceException("更新失败,id不能为空");
        }
        return toAjax(schoolDeviceRecordService.updateById(schoolDeviceRecord));
    }

    /**
     * 删除学校场地申请
     */
    @ApiOperation("删除")
    @DeleteMapping("/deleteByIds/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids) {
        return toAjax(schoolDeviceRecordService.removeByIds(ids));
    }

    /**
     * 导出选中
     */
    @ApiOperation("导出excel")
    @PostMapping("/export/{ids}")
    public void export(@PathVariable List<Long> ids, HttpServletResponse response) throws IOException {
        List<RecordListVo> list = schoolDeviceRecordService.getByIds(ids);
        ExcelUtil<RecordListVo> util = new ExcelUtil<RecordListVo>(RecordListVo.class);
        util.exportExcel(response, list, "设备维修列表");
    }

    /**
     * 导出全部,和按条件导出
     */
    @ApiOperation("导出excel")
    @PostMapping("/exportAll")
    public void exportAll(HttpServletResponse response, String submitState, RecordListVo recordListVo) throws IOException {
        List<RecordListVo> list = schoolDeviceRecordService.queryList(submitState, recordListVo);
        ExcelUtil<RecordListVo> util = new ExcelUtil<RecordListVo>(RecordListVo.class);
        util.exportExcel(response, list, "设备维修列表");
    }

    /**
     * 提交申请
     */
    @PostMapping("/submitApply/{id}")
    public AjaxResult submitApply(@PathVariable("id") Long id) {
        SchoolDeviceRecord schoolDeviceRecord = schoolDeviceRecordService.getById(id);
        if (StringUtils.isNull(schoolDeviceRecord)) {
            throw new ServiceException("提交申请失败,未查询到相关信息");
        }
        String userName = getUsername();
        schoolDeviceRecord.setApplyUser(userName);
        schoolDeviceRecord.setApplyTime(DateUtils.getNowDate());
        //设置流程角色组标识
        Map<String, Object> map = new HashMap<>();
        map.put(ROLEKEY, schoolDeviceRecord.getRoleKey());
        return toAjax(schoolDeviceRecordService.submitApply(schoolDeviceRecord, userName, INSTANDHALTUNG, map));
    }

//    /**
//     * 我的待办列表
//     * @return
//     */
//    @ApiOperation("我的待办列表")
//    @GetMapping("/taskList")
//    public TableDataInfo taskList(SchoolDeviceRecord entity) {
//        startPage();
//        String userId = getUserId().toString();
//        List<RecordTodoVo> list = schoolDeviceRecordService.findTodoTasks(INSTANDHALTUNG, entity,userId);
//        return getDataTable(list);
//    }

    /**
     * 我的待办列表
     */
    @GetMapping("/myTaskList")
    public TableDataInfo myTaskList(SchoolDeviceRecord entity) {
        String userId = getUserId().toString();
        List<RecordTodoVo> list = schoolDeviceRecordService.findMyTodoTasks(INSTANDHALTUNG, entity, userId);
        return getDataTable(list);
    }

    /**
     * 组待办事项列表
     */
    @GetMapping("/taskList")
    public TableDataInfo taskList(SchoolDeviceRecord entity) {
        String userId = getUserId().toString();
        List<RecordTodoVo> list = schoolDeviceRecordService.findTodoTasks(INSTANDHALTUNG, entity, userId);
        return getDataTable(list);
    }


    /**
     * 完成任务
     */
    @PostMapping("/complete/{taskId}/{instanceId}")
    public AjaxResult complete(@PathVariable("taskId") String taskId, @PathVariable("instanceId") String instanceId, @RequestBody Map<String, Object> variables) {
        processService.completeTask(taskId, instanceId, variables);
        LambdaQueryWrapper<SchoolDeviceRecord> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SchoolDeviceRecord::getInstanceId, instanceId);
        SchoolDeviceRecord schoolDeviceRecord = schoolDeviceRecordService.getOne(lqw);
        if((boolean)variables.get("pass")){
            schoolDeviceRecord.setState(PASS);
        }else {
            schoolDeviceRecord.setState(REFUSE);
        }
        schoolDeviceRecordService.updateById(schoolDeviceRecord);
        return AjaxResult.success();
    }

    /**
     * 我的已办列表
     *
     * @param entity
     * @return
     */
    @ApiOperation("我的已办列表")
    @GetMapping("/taskDoneList")
    public TableDataInfo taskDoneList(SchoolDeviceRecord entity) {
        String userId = getUserId().toString();
        List<RecordTodoVo> list = schoolDeviceRecordService.findDoneTasks(INSTANDHALTUNG, entity, userId);
        int total = processService.getDoneTotal(INSTANDHALTUNG, userId);
        return getTaskTable(list, total);
    }

}
