package com.willalp.web.controller.app;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.willalp.clockingin.domain.BizLeave;
import com.willalp.clockingin.service.IBizLeaveService;
import com.willalp.common.core.controller.BaseController;
import com.willalp.common.core.domain.AjaxResult;
import com.willalp.common.core.page.TableDataInfo;
import com.willalp.common.utils.SecurityUtils;
import com.willalp.common.utils.StringUtils;
import com.willalp.erms.domain.HsGoodsStorageRecord;
import com.willalp.erms.service.IHsGoodsStorageRecordService;
import com.willalp.erms.service.IHsGoodsStorageService;
import com.willalp.files.domain.HsOrgPersonnelFiles;
import com.willalp.files.domain.PersonnelHireApproval;
import com.willalp.files.service.IHsOrgPersonnelFilesService;
import com.willalp.files.service.IPersonnelHireApprovalService;
import com.willalp.flow.domain.HsFlowTask;
import com.willalp.flow.domain.req.FlowReq;
import com.willalp.flow.service.HsFlowEngineService;
import com.willalp.flow.service.IBizLeaveImgService;
import com.willalp.flow.util.BeanMapUtilByReflect;
import com.willalp.system.service.ISysConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;

@Api("APP流控制器")
@RestController
@RequestMapping("/app")
public class AppFLowController extends BaseController {
    @Resource
    private IBizLeaveService bizLeaveService;

    @Resource
    private IBizLeaveImgService leaveImgService;

    @Resource
    private HsFlowEngineService flowEngineService;

    @Resource
    private ISysConfigService sysConfigService;

    @Resource
    private IHsGoodsStorageService storageService;

    /**
     * 请假提交
     *
     * @param leave
     * @return
     */
    @ApiOperation("提交请假")
    @PostMapping("/submitApply/leave")
    public AjaxResult submitLeave(@RequestBody BizLeave leave) {
        String idStr = IdWorker.getIdStr();
        String taskId = IdWorker.getIdStr();
        leave.setId(Long.parseLong(idStr));
        leave.setTaskId(taskId);
        leave.setApplyTime(new Date());
        if (leave.getImgUrls().size() != 0) {
            leave.getImgUrls().forEach(i -> i.setBizLeaveId(idStr));
            leaveImgService.saveBatch(leave.getImgUrls());
        }
        bizLeaveService.insertBizLeave(leave);
        Map<String, Object> map = null;
        try {
            //对象转换为Map集合
            map = BeanMapUtilByReflect.beanToMap(leave);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        String bizLeaveFlowRunId = sysConfigService.selectConfigByKey(HsFlowEngineService.BIZ_LEAVE_FLOW_KEY);
        return AjaxResult.success(
                flowEngineService.submitTask(new HsFlowTask(taskId, idStr, bizLeaveFlowRunId), map));
    }

    @Resource
    private IHsGoodsStorageRecordService goodsStorageRecordService;

    /**
     * 物资领用提交
     *
     * @param goodsStorageRecord
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("物资系统提交")
    @PostMapping("/submitApply/rcr")
    public AjaxResult submitLeave(@RequestBody HsGoodsStorageRecord goodsStorageRecord) {
        String idStr = IdWorker.getIdStr();
        String taskId = IdWorker.getIdStr();
        goodsStorageRecord.setId(idStr);
        goodsStorageRecord.setApplyUserId(SecurityUtils.getUsername());
        String reserveConsumingRunId = null;
        switch (goodsStorageRecord.getRecordType()) {
            case "1":
                goodsStorageRecord.setTitle("物资登记审批");
                goodsStorageRecord.setRecordType("1");
                reserveConsumingRunId = sysConfigService.selectConfigByKey(HsFlowEngineService.RESERVE_REGISTER_FLOW_RUN_KEY);
                break;
            case "2":
                goodsStorageRecord.setTitle("物资领用审批");
                goodsStorageRecord.setRecordType("2");
                reserveConsumingRunId = sysConfigService.selectConfigByKey(HsFlowEngineService.RESERVE_FLOW_KEY);
                break;
            case "3":
                goodsStorageRecord.setTitle("物资归还审批");
                goodsStorageRecord.setRecordType("3");
                reserveConsumingRunId = sysConfigService.selectConfigByKey(HsFlowEngineService.RESERVE_RETURN_FLOW_RUN_KEY);
                break;
            default:
                return AjaxResult.error("非法提交【未选择库存类型】");
        }
        goodsStorageRecord.setApplyDate(new Date());
        if (storageService.getById(goodsStorageRecord.getGoodsId()) == null) {
            return AjaxResult.error("库中没有找到该物资");
        }
        goodsStorageRecordService.save(goodsStorageRecord);
        Map<String, Object> map = null;
        try {
            //对象转换为Map集合
            map = BeanMapUtilByReflect.beanToMap(goodsStorageRecord);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return AjaxResult.success(
                flowEngineService.submitTask(new HsFlowTask(taskId, idStr, reserveConsumingRunId), map));
    }

    @Resource
    private IPersonnelHireApprovalService personnelHireApprovalService;

    @Resource
    private IHsOrgPersonnelFilesService personnelFilesService;

    /**
     * 入职提交
     *
     * @param orgPersonnelFiles
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("入职提交")
    @PostMapping("/submitApply/personnelHire")
    public AjaxResult submitPersonnelHire(@RequestBody HsOrgPersonnelFiles orgPersonnelFiles) {
        String idStr = IdWorker.getIdStr();
        String taskId = IdWorker.getIdStr();
        String userCode = orgPersonnelFiles.getUserCode();
        //注册过的员工表单信息
        HsOrgPersonnelFiles files = orgPersonnelFilesService.getBaseMapper().selectOne(new QueryWrapper<HsOrgPersonnelFiles>()
                .eq("user_code", userCode));
        if (files == null) {
            return AjaxResult.error("未找到会助理注册信息");
        }
        //设置入职中状态
        orgPersonnelFiles.setId(files.getId());
        orgPersonnelFiles.setNowStatus("1");
        //入职流程组件
        PersonnelHireApproval personnelHireApproval = new PersonnelHireApproval();
        personnelHireApproval.setId(idStr);
        personnelHireApproval.setPersonnelId(files.getId());
        personnelHireApproval.setApplyUserId(SecurityUtils.getUsername());
        personnelHireApproval.setApplyUserName(orgPersonnelFiles.getUserName());
        personnelHireApproval.setCreateTime(new Date());
        personnelHireApproval.setTitle("员工入职审批");
        personnelHireApproval.setApplyTime(orgPersonnelFiles.getHiredate());
        personnelHireApproval.setHireOrDimission("1");
        personnelHireApprovalService.save(personnelHireApproval);
        personnelFilesService.updateById(orgPersonnelFiles);
        Map<String, Object> map = null;
        try {
            //对象转换为Map集合
            map = BeanMapUtilByReflect.beanToMap(personnelHireApproval);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        String reserveConsumingRunId = sysConfigService.selectConfigByKey(HsFlowEngineService.PRSSONNEl_HIRE_APP_FLOW_RUN_KEY);
        return AjaxResult.success(
                flowEngineService.submitTask(new HsFlowTask(taskId, idStr, reserveConsumingRunId), map));
    }

    /**
     * 离职提交
     *
     * @param personnelHireApproval
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("离职提交")
    @PostMapping("/submitApply/personnelDimission")
    public AjaxResult submitPersonnelDimission(@RequestBody PersonnelHireApproval personnelHireApproval) {
        String idStr = IdWorker.getIdStr();
        String taskId = IdWorker.getIdStr();
        //入职流程组件
        personnelHireApproval.setId(idStr);
        personnelHireApproval.setApplyUserId(SecurityUtils.getUsername());
        personnelHireApproval.setCreateTime(new Date());
        personnelHireApproval.setTitle("员工离职审批");
        personnelHireApproval.setHireOrDimission("2");
        personnelHireApprovalService.save(personnelHireApproval);
        Map<String, Object> map = null;
        try {
            //对象转换为Map集合
            map = BeanMapUtilByReflect.beanToMap(personnelHireApproval);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        String reserveConsumingRunId = sysConfigService.selectConfigByKey(HsFlowEngineService.PERSONNEL_DIMISSION_APPROVAL_FLOW_RUN_KEY);
        return AjaxResult.success(
                flowEngineService.submitTask(new HsFlowTask(taskId, idStr, reserveConsumingRunId), map));
    }


    /**
     * 下一步
     *
     * @param fr
     * @return
     */
    @ApiOperation("下一步")
    @PostMapping("/nextStep")
    public AjaxResult nextStep(@RequestBody FlowReq fr) {
        return AjaxResult.success(
                flowEngineService.nextStep(fr));
    }

    /**
     * 获取待办
     *
     * @param taskId
     * @return
     */
    @ApiOperation("获取指定待办任务")
    @RequestMapping("/gtdToId")
    public AjaxResult getToDoByTaskId(@RequestParam String taskId, @RequestParam String type) {
        if ("7".equals(type)) {
            return AjaxResult.success(
                    flowEngineService.getTaskIdByCcId(taskId));
        } else {
            return AjaxResult.success(
                    flowEngineService.getToDoByTaskId(taskId));
        }
    }

    /**
     * 获取
     *
     * @param taskId
     * @return
     */
    @ApiOperation("获取指定待办任务")
    @RequestMapping("/gBlToId")
    public AjaxResult getLeaveByTaskId(String taskId) {
        return AjaxResult.success(
                bizLeaveService.getBaseMapper().selectOne(new QueryWrapper<BizLeave>()
                        .eq("task_id", taskId)));
    }

    /**
     * 获取待办
     *
     * @return
     */
    @ApiOperation("获取待办")
    @RequestMapping("/gtd")
    public TableDataInfo getToDo() {
        startPage();
        return getDataTable(
                flowEngineService.getToDo(SecurityUtils.getUsername()));
    }

    /**
     * 获取已办
     *
     * @return
     */
    @ApiOperation("获取已办")
    @RequestMapping("/gd")
    public TableDataInfo getDon() {
        startPage();
        return getDataTable(
                flowEngineService.getDone(SecurityUtils.getUsername()));
    }

    /**
     * 获取所有发起审批
     */
    @GetMapping("/initiator")
    public TableDataInfo initiatorLis() {
        startPage();
        return getDataTable(
                flowEngineService.getInitiator(SecurityUtils.getUsername()));
    }

    /**
     * 获取当前任务记录
     *
     * @param taskId
     * @return
     */
    @ApiOperation("获取当前任务进度")
    @RequestMapping("/ctr")
    public AjaxResult currentTaskRecords(String taskId) {
        return AjaxResult.success(
                flowEngineService.currentTaskRecords(taskId));
    }

    /**
     * 驳回时选择进度
     *
     * @param taskId
     * @return
     */
    @ApiOperation("驳回时选择进度")
    @RequestMapping("/reject/ctr")
    public AjaxResult rejectTaskRecords(String taskId) {
        return AjaxResult.success(
                flowEngineService.rejectTaskRecords(taskId));
    }


    /**
     * 任务撤销
     *
     * @param taskId
     * @return
     */
    @ApiOperation("任务撤销")
    @RequestMapping("/revoke")
    public AjaxResult revoke(String taskId) {
        return toAjax(
                flowEngineService.revoke(taskId));
    }

    @Resource
    private IHsOrgPersonnelFilesService orgPersonnelFilesService;

    /**
     * 请假记录
     *
     * @return
     */
    @ApiOperation("请假记录")
    @RequestMapping("/leaveList")
    public TableDataInfo leaveList() {
        String username = SecurityUtils.getUsername();
        if (StringUtils.isNotBlank(username)) {
            long department = orgPersonnelFilesService.count(new QueryWrapper<HsOrgPersonnelFiles>()
                    .eq("department", "319")
                    .eq("user_code", username));
            if (department > 0) {
                startPage();
                return getDataTable(
                        bizLeaveService.selectPersonnelList(new BizLeave()));
            }
        }
        return getDataTable(new ArrayList<>());
    }
}
