package com.bbd.bpm.controller.user;

import com.bbd.bpm.base.PageBean;
import com.bbd.bpm.domain.User;
import com.bbd.bpm.dto.SysCode;
import com.bbd.bpm.dto.response.BpmResponse;
import com.bbd.bpm.result.RespCode;
import com.bbd.bpm.result.Result;
import com.bbd.bpm.result.ResultUtil;
import com.bbd.bpm.service.UserInfoService;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.activiti.bpmn.converter.BpmnXMLConverter;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.editor.constants.ModelDataJsonConstants;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import java.io.*;

/**
 * 用户功能模块接口
 * @Author:cwd
 * @Description:用户功能模块接口
 * @Date: 2019/03/04 22:53
 * @Param:
 * @return
 **/
@Controller
@RequestMapping(value = "bpm/user")
public class UserApiController {

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private RepositoryService repositoryService;


    /**
     * @Description: 用户列表
     * @author: cwd
     * @param: id
     * @param pageBean
     * @param userName
     * @return Result
     * @date: 2019/3/4
     * @time: 11:03
     */
    @PostMapping("userList")
    @ResponseBody
    public Result userList(Integer id,PageBean pageBean,String userName){
        if(pageBean.getPageNum()==0){
            pageBean.setPageNum(1);
        }
        if (pageBean.getPageSize()==0) {
            pageBean.setPageSize(10);
        }
        Result result= userInfoService.userList(id,pageBean,userName);
        return result;
    }



    /**
     * @Author:cwd
     * @Description:获取组织列表
     * @Date: 2019/03/04 22:53
     * @param id
     * @return Result
     **/
    @PostMapping("getOrganizationInfo")
    @ResponseBody
    public Result getOrganizationInfo(Integer id){
       Result result= userInfoService.getOrganizationInfo(id);
       return result;
    }

    /**
     * @Author:cwd
     * @Description:获取组织列表
     * @Date: 2019/03/04 22:53
     * @param pageBean
     * @param id
     * @param pId
     * @param name
     * @return Result
     **/
    @PostMapping("getOrganization")
    @ResponseBody
    public Result getOrganization(PageBean pageBean,Integer id,Integer pId,String name){
        if(pageBean.getPageNum()==0){
            pageBean.setPageNum(1);
        }
        if (pageBean.getPageSize()==0) {
            pageBean.setPageSize(10);
        }
        Result result= userInfoService.getOrganization(pageBean,id,pId,name);
        return result;
    }



    /**
     * @Author:cwd
     * @Description:加载ztree
     * @Date: 2019/03/04 22:53
     * @return Result
     **/
    @PostMapping("getOrganizationList")
    @ResponseBody
    public Result getOrganization(){
        Result result = userInfoService.getOrganizationList();
        return result;
    }

    /**
     * @Author:cwd
     * @Description:添加组织
     * @Date: 2019/03/04 22:53
     * @param pId
     * @param id
     * @param abbreviationName
     * @param name
     * @return
     **/
    @PostMapping("addOrganization")
    @ResponseBody
    public Result addOrganization(String name, String abbreviationName, Long pId, Integer id){
        //获取session中的值
        Result result = userInfoService.addOrganization(name,abbreviationName,pId,id);
        return result;
    }


    /**
     * @Author:cwd
     * @Description:添加部门人员
     * @Date: 2019/03/04 22:53
     * @param id
     * @param name
     * @param pId
     * @param department
     * @param position
     * @param type
     * @return Result
     **/
    @PostMapping("addOrganizationMember")
    @ResponseBody
    public Result addOrganizationMember(String name, String position, Long pId, Integer id,Integer department,Integer type){
        //获取session中的值
        Result result = userInfoService.addOrganizationMember(name,position,pId,id,department,type);
        return result;
    }


    /**
     * @Author:cwd
     * @Description:修改组织
     * @Date: 2019/03/04 22:53
     * @param name
     * @param abbreviationName
     * @param id
     * @return Result
     **/
    @PostMapping("editOrganization")
    @ResponseBody
    public Result editOrganization(String name, String abbreviationName,Integer id){
        Result result = userInfoService.editOrganization(name,abbreviationName,id);
        return result;
    }



    /**
     * @Author:cwd
     * 删除组织及下级
     * @Date: 2019/03/04 22:53
     * @param id
     * @param pId
     * @return Result
     */
    @PostMapping("deleteOrganization")
    @ResponseBody
    public Result deleteOrganization(Long id,Integer pId){
        Result result = userInfoService.deleteOrganization(id,pId);
        return result;
    }

    /**
     * 获取下级部门信息
     * @Author:cwd
     * @param id
     * @return Result
     */
    @PostMapping("getAreaAll")
    @ResponseBody
    public Result getAreaAll(Integer id){
        Result areaList = userInfoService.getAreaAll(id);
        return areaList;
    }


    /**
     * @Author:cwd
     * 获取左侧树
     * @Date: 2019.3.7
     * @return Result
     */
    @GetMapping("/menuList")
    @ResponseBody
    public Result menuList(){
        Result result= userInfoService.getMenuList();
        return result;
    }


    /**
     * @Author:cwd
     * 添加用户
     * @param user
     * @Date: 2019.4.4
     * @return Result
     */
    @PostMapping("/addUser")
    @ResponseBody
    public Result addUser(User user){
        Result result= userInfoService.addUser(user);
        return result;
    }

    /**
     * @Author:cwd
     * 删除用户
     * @Date: 2019.4.4
     * @param user
     * @return
     */
    @PostMapping("/deleteUser")
    @ResponseBody
    public Result deleteUser(User user){
        Result result= userInfoService.deleteUser(user);
        return result;
    }


    @ApiOperation(value = "导出流程列表")
    @GetMapping("/exportDeployMent")
    @ResponseBody
    public BpmResponse exportDeployMent(String modelId, HttpServletResponse response) {
        BufferedOutputStream bos = null;
        BpmResponse resp = new BpmResponse();
        try {

            try {
                Model modelData = repositoryService.getModel(modelId);
                byte[] bpmnBytes = repositoryService
                        .getModelEditorSource(modelData.getId());
                // 封装输出流
                bos = new BufferedOutputStream(response.getOutputStream());
                // 写入流
                bos.write(bpmnBytes);

                String filename = modelData.getName() + ".json";
                response.setContentType("application/x-msdownload");
                response.setHeader("Content-Disposition",
                        "attachment; filename=" +  new String(filename.getBytes(),"iso-8859-1"));
                response.flushBuffer();
                resp.setSuccess(true);
                resp.setMessage("导出成功");
                resp.setCode(SysCode.SUCCESS_CODE);
                return  resp;
            } finally {
                bos.flush();
                bos.close();
            }

        } catch (Exception e) {
            System.out.println("导出失败");
            e.printStackTrace();
            return  resp;
        }

    }


    @ApiOperation(value = "导入流程列表")
    @PostMapping("/improtDeployMent")
    @ResponseBody
    public BpmResponse improtDeployMent(MultipartFile file, String name, String content) {
        BpmResponse resp = new BpmResponse();
        //验证非空
        if(name==null || name.equals("")){
            resp.setCode("201");
            return resp;
        }
        if(content==null || content.equals("")){
            resp.setCode("202");
            return resp;
        }
        String s="";
        try {
            //读取文件信息
            StringBuffer strbuffer = new StringBuffer();
            InputStream fis = file.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(fis, "UTF-8");
            BufferedReader in  = new BufferedReader(inputStreamReader);
            String str;
            while ((str = in.readLine()) != null) {
                strbuffer.append(str);
            }
             s = strbuffer.toString();
            byte[] bytes = s.getBytes();
            //添加modelId
            ObjectMapper objectMapper = new ObjectMapper();
            ObjectNode modelObjectNode = objectMapper.createObjectNode();
            Model modelData = repositoryService.newModel();
            //赋值
            modelObjectNode.put(ModelDataJsonConstants.MODEL_NAME, name);
            modelObjectNode.put(ModelDataJsonConstants.MODEL_REVISION, 1);
            modelObjectNode.put(ModelDataJsonConstants.MODEL_DESCRIPTION, content);
            modelData.setMetaInfo(modelObjectNode.toString());
            modelData.setName(name);
            //创建流程
            repositoryService.saveModel(modelData);
            repositoryService.addModelEditorSource(modelData.getId(),bytes);
            resp.setSuccess(true);
            resp.setMessage("导入成功");
            resp.setCode(SysCode.SUCCESS_CODE);
            in.close();
            return resp;
        }
        catch (IOException e) {
            resp.setSuccess(false);
            resp.setMessage("导入失败");
            resp.setCode(SysCode.SYS_ERROR);
            e.getStackTrace();
            return resp;
        }
    }





}
