package com.yihu.hos.system.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.hos.config.BeanConfig;
import com.yihu.hos.core.datatype.ClassFileUtil;
import com.yihu.hos.system.model.SystemServiceFlow;
import com.yihu.hos.system.model.SystemServiceFlowClass;
import com.yihu.hos.system.model.SystemServiceFlowTemp;
import com.yihu.hos.system.service.FlowManager;
import com.yihu.hos.web.framework.constant.ServiceFlowConstant;
import com.yihu.hos.web.framework.model.ActionResult;
import com.yihu.hos.web.framework.model.DataGridResult;
import com.yihu.hos.web.framework.model.Result;
import com.yihu.hos.web.framework.util.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 流程管理
 *
 * @author HZY
 * @vsrsion 1.0
 * Created at 2016/8/18.
 */
@RequestMapping("/flow")
@Controller
public class FlowController extends BaseController {

    @Resource(name = FlowManager.BEAN_ID)
    private FlowManager flowManage;
    @Autowired
    private BeanConfig beanConfig;

    /**
     * 流程管理管理界面
     *
     * @param model
     * @return
     */
    @RequestMapping("/initial")
    public String appInitial(Model model) {
        model.addAttribute("contentPage", "system/flow/flow");
        model.addAttribute("dfs", beanConfig.getFsUrl());
        return "partView";
    }

    @RequestMapping("/getFlowList")
    @ResponseBody
    public Result getFlowList(HttpServletRequest request, String name, String valid) {
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("name", name);
            params.put("valid", valid);

            String page = StringUtils.isEmpty(request.getParameter("page")) ? "1" : request.getParameter("page");
            String rows = StringUtils.isEmpty(request.getParameter("rows")) ? "10" : request.getParameter("rows");

            params.put("page", page);
            params.put("rows", rows);
            DataGridResult result = (DataGridResult) flowManage.getFlowList(params);
            List<SystemServiceFlow> detailModelList = result.getDetailModelList();
            return result;
        } catch (Exception ex) {
            ex.printStackTrace();
            return Result.error(ex.getMessage());
        }
    }

    /**
     * 流程管理-新增/修改页面
     *
     * @param model
     * @param id
     * @return
     */
    @RequestMapping("/editorFlow")
    public String editorFlow(Model model, String id) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            SystemServiceFlow flow = null;
            List<SystemServiceFlowClass> flowClassList = null;
            List<SystemServiceFlowTemp> flowTempList = null;
            if (id != null && id.length() > 0) {
                flow = flowManage.getFlowById(Integer.parseInt(id));
                flowClassList = flowManage.getFlowClassByFlowId(flow.getId());
                flowTempList = flowManage.getFlowTempByFlowId(flow.getId());

                if (ServiceFlowConstant.CLASS.equals(flow.getFileType())) {
                    model.addAttribute("flowClass", objectMapper.writeValueAsString(flowClassList));
                } else if (ServiceFlowConstant.JAVA.equals(flow.getFileType())) {
                    model.addAttribute("flowClass", objectMapper.writeValueAsString(flowTempList));
                }
            } else {
                flow = new SystemServiceFlow();
                flowClassList = new ArrayList<>();
                flowTempList = new ArrayList<>();
            }
            flow.setFlowClassArray(flowClassList);
            flow.setFlowTempArray(flowTempList);
            model.addAttribute("model", flow);
            model.addAttribute("dfs", beanConfig.getFsUrl());
            model.addAttribute("contentPage", "/system/flow/editorFlow");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "pageView";
    }


    /**
     * 新增流程信息
     *
     * @param request
     * @return
     */
    @RequestMapping("addFlow")
    @ResponseBody
    public Result addFlow(HttpServletRequest request, String flowClass) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            SystemServiceFlow flow = objectMapper.readValue(flowClass, SystemServiceFlow.class);

            return flowManage.addFlow(flow);
        } catch (Exception ex) {
            ex.printStackTrace();
            return Result.error(ex.getMessage());
        }
    }

    /**
     * 删除流程信息
     *
     * @param request
     * @return
     */
    @RequestMapping("/deleteFlow")
    @ResponseBody
    public Result deleteFlow(HttpServletRequest request) {

        try {
            String id = request.getParameter("id");
            if (id != null && id.length() > 0) {
                flowManage.deleteFlow(Integer.parseInt(id));
                return Result.success("删除成功！");
            } else {
                return Result.error("删除失败,该流程已不存在！");
            }

        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除失败！");
        }
    }

    /**
     * 修改流程信息
     */
    @RequestMapping("updateFlow")
    @ResponseBody
    public Result updateFlow(HttpServletRequest request, String flowClass) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            SystemServiceFlow flow = objectMapper.readValue(flowClass, SystemServiceFlow.class);
            return flowManage.updateFlow(flow);
        } catch (Exception ex) {
            ex.printStackTrace();
            return Result.error(ex.getMessage());
        }
    }


    @RequestMapping(value = "/flowTempList", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    public Result flowTempList(String type) {
        try {
            Result result = flowManage.getFlowList(type);
            return result;
        } catch (Exception ex) {
            ex.printStackTrace();
            return Result.error(ex.getMessage());
        }
    }

    /**
     * 上传文件并解析文件属性：包名，类名等
     *
     * @param file
     * @return
     */
    @RequestMapping(value = "parseFile", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    public Result uploadAndParse(@RequestPart MultipartFile file) {
        ActionResult re = new ActionResult();
        File tempFile = new File(System.getProperty("java.io.tmpdir") + System.getProperty("file.separator") + file.getOriginalFilename());
        try {
            file.transferTo(tempFile);
            // 解析文件并返回类属性
            Map<String, String> map = flowManage.uploadAndParse(tempFile);
            String path = ClassFileUtil.uploadFile(beanConfig.getFsUrl(), tempFile, file.getName());
            map.put("path", path);
            re.setData(map);
            if (!StringUtils.isEmpty(path)) {
                tempFile.delete();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return re;
    }


}
