package cn.ezhizao.project.business.workflow.controller;

import cn.ezhizao.framework.web.controller.BaseController;
import cn.ezhizao.framework.web.domain.AjaxResult;
import cn.ezhizao.project.business.collection.service.IBizCollectionService;
import cn.ezhizao.project.business.payment.domain.BizPayment;
import cn.ezhizao.project.business.payment.service.IBizPaymentService;
import cn.ezhizao.project.business.workflow.domain.BizWorkFlow;
import cn.ezhizao.project.business.workflow.domain.BizWorkFlowContent;
import cn.ezhizao.project.business.workflow.service.BizWorkFlowContentService;
import cn.ezhizao.project.business.workflow.service.BizWorkFlowService;
import cn.ezhizao.project.system.domain.SysFileStorage;
import cn.ezhizao.project.system.service.ISysFileStorageService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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 javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zx
 */
@RestController
@Api(tags = "WorkFlowContent数据接口")
@RequestMapping(value = "/module/workflowContent")
public class WorkFlowContentController extends BaseController {
    @Resource
    BizWorkFlowContentService bizWorkFlowContentService;
    @Resource
    BizWorkFlowService workFlowService;
    @Resource
    IBizPaymentService paymentService;
    @Resource
    IBizCollectionService collectionService;
    @Resource
    ISysFileStorageService fileStorageService;
    @Resource
    HttpServletResponse response;

    @ApiOperation(value = "根据id查询", notes = "根据id查询")
    @GetMapping("/getById/{id}")
    @ResponseBody
    public AjaxResult getById(@PathVariable Long id) {
//        return success(workFlowContentService.getById(id));
        return toAjax(true);
    }

    @PostMapping("/save")
    @ApiOperation(value = "保存", notes = "保存")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult save(@RequestBody BizWorkFlowContent workFlowContent) {
        BizPayment payment = null;
        List<SysFileStorage> files = workFlowContent.getFiles();
        BizWorkFlow workFlow = workFlowService.getById(workFlowContent.getWorkFlowId());
        Map<String, Object> workFlowConditions = new HashMap<>();
        workFlowConditions.put("formName", workFlow.getFormName());
        List<BizWorkFlow> workFlows = workFlowService.getList(workFlowConditions);
        workFlows.sort(Comparator.comparing(BizWorkFlow::getSort));

        if (workFlows.get(workFlows.size() - 1).getId().equals(workFlow.getId()) || workFlowContent.getResult().equals(3)) {
            switch (workFlowContent.getMasterTableName()) {
                case "payment":
                    payment = paymentService.getById(workFlowContent.getMasterId());
                    payment.setActuallyDate(workFlowContent.getActuallyDate());
                    payment.setPaymentStatus(workFlowContent.getResult().equals(3) ? (byte) 2 : workFlows.get(workFlows.size() - 1).getId().equals(workFlow.getId()) && workFlowContent.getResult().equals(1) ? (byte) 1 : 0);
                    payment.setVerifyStatus(workFlowContent.getResult().equals(3) ? (byte) 2 : workFlows.get(workFlows.size() - 1).getId().equals(workFlow.getId()) && workFlowContent.getResult().equals(1) ? (byte) 1 : 0);

                    break;
                default:
                    break;
            }
        }
        if (bizWorkFlowContentService.saveOrUpdate(workFlowContent)) {
            files.forEach(l -> {
                l.setMasterId(workFlowContent.getId());
                l.setMasterTableName("work_flow_content");
            });
            return  (payment == null || paymentService.saveOrUpdate(payment)) && (files.isEmpty() || fileStorageService.saveOrUpdateBatch(files)) ? success() : error();
        } else {
            return error();
        }
    }

    @ApiOperation("取消审核")
    @PostMapping("/unverified")
    @ResponseBody
    public AjaxResult unverified(@RequestBody BizWorkFlowContent workFlowContent) {
        // 删除旧的审核结果
        QueryWrapper<BizWorkFlowContent> wrapper = new QueryWrapper<>();
        boolean bool = bizWorkFlowContentService.remove(wrapper.eq("workflow_id", workFlowContent.getWorkFlowId()).eq("master_id", workFlowContent.getMasterId()).eq("master_table_name", workFlowContent.getMasterTableName()));
        QueryWrapper<SysFileStorage> fileWrapper = new QueryWrapper<>();
        fileStorageService.remove(fileWrapper);
        return bool ? success() : error();
    }


    @PostMapping("/saveBatch")
    @ApiOperation(value = "批量保存", notes = "批量保存")
    @ResponseBody
    public AjaxResult saveBatch(@RequestBody List<BizWorkFlowContent> list) {
        return bizWorkFlowContentService.saveOrUpdateBatch(list) ? success() : error();
    }

    @ApiOperation(value = "删除", notes = "删除")
    @GetMapping("/deleteById/{id}")
    @ResponseBody
    public AjaxResult deleteById(@PathVariable Long id) {
        return bizWorkFlowContentService.removeById(id) ? success() : error();
    }

    @ApiOperation(value = "批量删除", notes = "批量删除")
    @PostMapping("/batchDelete")
    @ResponseBody
    public AjaxResult batchDelete(@RequestBody List<Long> list) {
        return bizWorkFlowContentService.removeBatchByIds(list) ? success() : error();
    }

    @ApiOperation(value = "带条件List 分页查询", notes = "带条件List 分页查询")
    @GetMapping("/list")
    @ResponseBody
    public AjaxResult getList(BizWorkFlowContent conditions) throws NoSuchFieldException, IllegalAccessException {
        setTenantId(conditions);
        Map<String, Object> map = new HashMap<>(16);
        BizWorkFlow mainConditions = new BizWorkFlow();
        mainConditions.setFormName(conditions.getFormName());
        List<BizWorkFlow> workFlows = workFlowService.getListByBean(mainConditions);
//        contentConditions.set
        List<BizWorkFlowContent> contents = bizWorkFlowContentService.getListByBean(conditions);
        contents.forEach(l -> {
            SysFileStorage fileConditions = new SysFileStorage();
            fileConditions.setMasterId(l.getId());
            fileConditions.setMasterTableName("work_flow_content");
            l.setFiles(fileStorageService.getList(fileConditions));
        });
        workFlows.forEach(l -> l.setContent(contents.stream().filter(v -> v.getWorkFlowId().equals(l.getId())).findFirst().orElse(null)));
        workFlows.sort(Comparator.comparing(BizWorkFlow::getSort));
        map.put("list", workFlows);
        return success(map);
    }

    @ApiOperation(value = "判断流程状态")
    @PostMapping("/check")
    @ResponseBody
    public AjaxResult check(@RequestBody Map<String, Object> conditions) throws NoSuchFieldException, IllegalAccessException {
        // 根据formName 获取工作流列表
        // 根据masterTableName 和 masterId 获取完成情况
        // 获取最后一个审核结果和第一个未审核结果
        setTenantId(conditions);
        List<BizWorkFlow> workFlows = workFlowService.getList(conditions);
        List<BizWorkFlowContent> contents = bizWorkFlowContentService.getList(conditions);
        workFlows.forEach(l -> {
            l.setContent(contents.stream().filter(v -> v.getWorkFlowId().equals(l.getId())).findFirst().orElse(null));
            if (l.getPermissionType().equals(4)) {
                l.setDepartmentIdList(Arrays.stream(l.getDepartmentIds().split(",")).collect(Collectors.toList()));
            }
        });
        BizWorkFlow latest = workFlows.stream().filter(v -> v.getContent() != null).max(Comparator.comparing(BizWorkFlow::getSort)).orElse(null);
        BizWorkFlow unfinished = workFlows.stream().filter(v -> v.getContent() == null).min(Comparator.comparing(BizWorkFlow::getSort)).orElse(null);
        Map<String, Object> result = new HashMap<>(2);
        result.put("latest", latest);
        result.put("next", unfinished);
        return success(result);
    }

    @ApiOperation(value = "取消审核")
    @PostMapping("/backVerified")
    @ResponseBody
    public AjaxResult backVerified(@RequestBody BizWorkFlow workFlow) {
        BizPayment payment = null;

        Integer jobNum = 0;
        BizWorkFlowContent workFlowContent = workFlow.getContent();
        workFlow = workFlowService.getById(workFlowContent.getWorkFlowId());
        List<SysFileStorage> files = workFlowContent.getFiles();

        Map<String, Object> workFlowConditions = new HashMap<>();
        workFlowConditions.put("formName", workFlow.getFormName());
        List<BizWorkFlow> workFlows = workFlowService.getList(workFlowConditions);
        workFlows.sort(Comparator.comparing(BizWorkFlow::getSort));

        if (workFlows.get(workFlows.size() - 1).getId().equals(workFlow.getId()) || workFlowContent.getResult().equals(3)) {
            switch (workFlowContent.getMasterTableName()) {
                case "payment":
                    payment = paymentService.getById(workFlowContent.getMasterId());
                    payment.setVerifyStatus((byte) 0);
                    break;
                default:
                    break;
            }
        }
        if (jobNum > 0) {
            return error("请删除合同已完成任务。");
        }
        if (bizWorkFlowContentService.removeById(workFlowContent)) {
            files.forEach(l -> {
                l.setMasterId(workFlowContent.getId());
                l.setMasterTableName("work_flow_content");
            });
            return (payment == null || paymentService.updateById(payment)) ? success() : error();
        } else {
            return error();
        }
    }

    private String getResultLabel(Integer result) {
        switch (result) {
            case 1:
                return "通过";
            case 2:
                return "暂停";
            case 3:
                return "不通过";
            default:
                return "错误";
        }
    }
}
