package com.gyee.frame.controller.ticket;


import com.alibaba.fastjson.JSONObject;
import com.gyee.frame.common.dataSources.DataSource;
import com.gyee.frame.common.dataSources.DataSourceType;
import com.gyee.frame.common.domain.AjaxResult;
import com.gyee.frame.model.ticket.TokenUser;
import com.gyee.frame.service.ticket.ShiroService;
import com.gyee.frame.service.ticket.WfassignmentService;
import com.gyee.frame.service.ticket.WfinstanceService;
import com.gyee.frame.service.ticket.WftransService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author chenmh
 * @since 2020-07-21
 */
@RestController
@RequestMapping("/wftrans")
public class WftransController {

    @Autowired
    WfinstanceService wfinstanceService;
    @Autowired
    WfassignmentService wfassignmentService;
    @Autowired
    WftransService wftransService;
    @Autowired
    ShiroService shiroService;


    @DataSource(value = DataSourceType.TICKET)
    @GetMapping(value = "index")
    public AjaxResult getIndex(@RequestParam("id") String ticketId){
        Map<String, Object> result = wfinstanceService.flowInstance(Double.valueOf(ticketId));

        if(result.size() == 0)
            return AjaxResult.error(4004, "流程未启动");

        return AjaxResult.successData(result);
    }


    @DataSource(DataSourceType.TICKET)
    @PostMapping(value = "flow")
    public AjaxResult postTransFlow(@RequestHeader("token") String header, @RequestParam("info") String info){
        JSONObject jsonObject = JSONObject.parseObject(info);
        int status = jsonObject.getInteger("status");
        double actionId = jsonObject.getDouble("actionid");
        double ownerId = jsonObject.getDouble("ownerid");
        double currNodeId = jsonObject.getDouble("currnodeid");
        double preNodeId = jsonObject.getDouble("prenodeid");
        double instId = jsonObject.getDouble("instid");
        double version = jsonObject.getDouble("version");
        String wfName = jsonObject.getString("wfname");
        String role = jsonObject.getString("role");
        String ticketNum = jsonObject.getString("ticketnum");
        List<String> labors = (List<String>) jsonObject.get("labors");

        TokenUser token = shiroService.findToken(header);

        // 流程正在进行
        if (status == 2){
            boolean result = wftransService.insertTrans(currNodeId, preNodeId, actionId, instId,version ,
                    ownerId, wfName, ticketNum, role, labors, token.getLaborNum());
            if(!result)
                AjaxResult.error(4004, "流程发送失败");
        }

        return AjaxResult.success("流程发送成功");
    }

}

