package com.cftech.base.org.web;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cftech.accounts.model.MpAccountsEntity;
import com.cftech.base.appmenu.model.Appmenu;
import com.cftech.base.appmenu.service.AppmenuService;
import com.cftech.base.org.api.QyUserUtil;
import com.cftech.base.org.model.Qyuser;
import com.cftech.core.util.QyTokenUtil;
import com.cftech.core.util.SystemConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
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.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

/**
 * Created by liuling on 2017/2/27.
 * 微信企业号用的base controller
 */
@Slf4j
@RestController
@RequestMapping("/mobile/qybase/")
public class MobileQybaseController {

    private final QyTokenUtil qyTokenUtil;
    private final QyUserUtil qyUserUtil;
    private final AppmenuService appmenuService;

    // 图片目录
    public static final String USER_IMAGES_DIR = SystemConfig.p.getProperty("userfiles.imgdir");

    @Autowired
    public MobileQybaseController(QyTokenUtil qyTokenUtil, QyUserUtil qyUserUtil, AppmenuService appmenuService) {
        this.qyTokenUtil = qyTokenUtil;
        this.qyUserUtil = qyUserUtil;
        this.appmenuService = appmenuService;
    }

    /**
     * 根据条件返回有权查看的应用链接
     *
     * @param request
     * @param accountsId 微信账号Id
     * @param app        微信应用的Id
     * @param userId  企业号的用户Id
     * @return
     */
    @RequestMapping(value = "appmenu", method = RequestMethod.GET, produces = {"application/json;charset=utf-8"})
    public JSONObject getAppmenu(HttpServletRequest request, Long accountsId, Long app, Long userId) {
        JSONObject retObj = new JSONObject();

        Qyuser qyuser = qyUserUtil.getUser(userId);

        retObj.put("errorNo", "0");
        List<Appmenu> appmenus = appmenuService.findByAccountsIdAndPositionIdAndApp(accountsId, qyuser.getPositionId(), app);
        JSONArray data = new JSONArray();
        JSONObject menuObj = null;
        for (Appmenu appmenu : appmenus) {
            menuObj = new JSONObject();
            menuObj.put("name", appmenu.getName());
            menuObj.put("icon", appmenu.getIcon());
            menuObj.put("color", appmenu.getColor());
            menuObj.put("link", appmenu.getLink());

            data.add(menuObj);
        }

        retObj.put("data", data);

        return retObj;
    }

    /**
     * 根据账户id返回JSAPI的data
     *
     * @param request    HttpServletRequest
     * @param accountsId 微信账户id
     * @return
     */
    @RequestMapping(value = "apiData", method = RequestMethod.GET, produces = {"application/json;charset=utf-8"})
    public JSONObject getJsApiData(HttpServletRequest request, Long accountsId) {
        JSONObject retObj = new JSONObject();
        MpAccountsEntity accountsEntity = qyTokenUtil.searchAccountsById(accountsId);
        String accessToken = qyTokenUtil.getToken(accountsEntity);
        String jsticket = qyTokenUtil.getJSTicket(accountsEntity);
        String noncestr = accountsEntity.getAppid();
        String timestamp = Long.toString(System.currentTimeMillis() / 1000);
        String url = request.getHeader("referer");

        retObj.put("errorNo", "0");
        retObj.put("errorMsg", "获取成功");





        String signature = qyTokenUtil.sign(jsticket, noncestr, timestamp, url);
        if (StringUtils.isEmpty(signature)) {
            retObj.put("errorNo", "1");
            retObj.put("errorMsg", "获取JsApi失败");
            return retObj;
        }

        retObj.put("jsticket", signature);
        retObj.put("noncestr", noncestr);
        retObj.put("timestamp", timestamp);
        retObj.put("appid",accountsEntity.getAppid());
        return retObj;
    }


    /**
     * 根据微信的账号id获取appid
     *
     * @param request
     * @param accountsId
     * @return
     */
    @RequestMapping(value = "getAppidByAccountsId", method = RequestMethod.GET, produces = {"application/json;charset=utf-8"})
    public JSONObject getAppidByAccountsId(HttpServletRequest request, Long accountsId) {
        JSONObject retObj = new JSONObject();
        MpAccountsEntity accountsEntity = qyTokenUtil.searchAccountsById(accountsId);
        if (accountsEntity == null) {
            retObj.put("errorNo", "1");
            retObj.put("errorMsg", "未找到相应的微信账号");
            return retObj;
        }
        retObj.put("errorNo", "0");
        retObj.put("appid", accountsEntity.getAppid());
        return retObj;
    }

    /**
     * 做授权认证，前端自行判断，如果没有code，则直接转向到微信的网页请求code
     *
     * @param request
     * @param accountsId
     * @param code
     * @return
     */
    @RequestMapping(value = "oauth", method = RequestMethod.GET, produces = {"application/json;charset=utf-8"})
    public JSONObject getOauth(HttpServletRequest request, Long accountsId, String code) {
        JSONObject retObj = new JSONObject();

        retObj.put("errorNo", "0");
        //如果没有code传入
        if (StringUtils.isEmpty(code)) {
            retObj.put("errorNo", "1");
            retObj.put("errorMsg", "code is not exist");
            return retObj;
        }

        Qyuser qyuser = qyUserUtil.getUserInfo(accountsId, code);
        if (qyuser == null) {
            retObj.put("errorNo", "1");
            retObj.put("errorMsg", "qyuser is not exist");
            return retObj;
        }

        JSONObject data = new JSONObject();
        //企业用户主键
        data.put("userId", qyuser.getId());
        data.put("wxuserId", qyuser.getWxuserId());
        data.put("orgId", qyuser.getOrgId());
        data.put("taglist", qyuser.getTagIds());
        data.put("avatar", qyuser.getAvatar());
        data.put("name", qyuser.getName());
        data.put("accountsId", qyuser.getAccountsId());
        data.put("positionId", qyuser.getPositionId());
        retObj.put("data", data);
        return retObj;
    }


    @RequestMapping(value = "showPic")
    public void showPic(HttpServletRequest request, HttpServletResponse response, Long accountsId, String picFileName) throws Exception{
        if(!StringUtils.isEmpty(picFileName))
        {
            if(picFileName.contains("..")||picFileName.contains("/")|| picFileName.contains("%00"))
            {
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                return;
            }
        }

        String filePath = USER_IMAGES_DIR + "";

        String picPath = filePath + File.separator + picFileName;
        //取后缀
        String ext = picFileName.substring(picFileName.lastIndexOf(".") + 1, picFileName.length());

        if ("jpg".equals(ext.toLowerCase()) || "jpeg".equals(ext.toLowerCase())) {
            response.setContentType("image/jpeg;charset=GB2312");
        }
        if ("png".equals(ext.toLowerCase())) {
            response.setContentType("image/png;charset=GB2312");
        }
        if ("bmp".equals(ext.toLowerCase())) {
            response.setContentType("image/bmp;charset=GB2312");
        }
        if ("gif".equals(ext.toLowerCase())) {
            response.setContentType("image/gif;charset=GB2312");
        }

        if("mp3".equals(ext.toLowerCase()))
        {
            response.setContentType("audio/mp3;charset=GB2312");
        }

        try {
            InputStream imageIn = new FileInputStream(picPath); // 文件流

            OutputStream output = response.getOutputStream();// 得到输出流

            BufferedInputStream bis = new BufferedInputStream(imageIn);// 输入缓冲流
            BufferedOutputStream bos = new BufferedOutputStream(output);// 输出缓冲流
            byte data[] = new byte[4096];// 缓冲字节数
            int size = 0;
            size = bis.read(data);
            while (size != -1) {
                bos.write(data, 0, size);
                size = bis.read(data);
            }
            bis.close();
            bos.flush();// 清空输出缓冲流
            bos.close();
            output.close();
        } catch (FileNotFoundException e) {
            log.error("showPic not found file, accountsId={}, picFileName={}", accountsId, picFileName);
        } catch (IOException e) {
            log.error("showPic got IOException: ", e.getMessage());
        }
    }
}
