package com.ejweb.modules.front.report.service;

import com.alibaba.fastjson.JSON;
import com.ejweb.conf.ErrorCode;
import com.ejweb.conf.GConstants;
import com.ejweb.core.api.ResponseBean;
import com.ejweb.core.service.CrudService;
import com.ejweb.core.utils.DateUtils;
import com.ejweb.core.utils.IdWorker;
import com.ejweb.core.utils.StringUtils;
import com.ejweb.core.web.Servlets;
import com.ejweb.modules.front.report.bean.FrontReportBean;
import com.ejweb.modules.front.report.dao.FrontReportDao;
import com.ejweb.modules.front.report.entity.FrontReportEntity;
import com.ejweb.modules.front.report.entity.IP2Regions;
import com.ejweb.modules.front.report.utils.IpUtils;
import com.ejweb.modules.front.upload.util.ReportAttachmentUtils;
import com.ejweb.modules.sys.entity.User;
import com.kingdee.eas.cp.eip.sso.ltpa.LtpaToken;
import com.kingdee.eas.cp.eip.sso.ltpa.LtpaTokenManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

/**
 * Created by lenovo on 2017/9/8.
 */

@Service
@Transactional(readOnly = true)
public class FrontReportService extends CrudService<FrontReportDao, FrontReportEntity> {

    private static Logger log = LoggerFactory.getLogger(FrontReportService.class);

    // 添加举报信息
    @Transactional(readOnly = false)
    public ResponseBean addReport(FrontReportBean bean, String token, HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        String reportId = IdWorker.getNextId("R");
        bean.setId(reportId);
        Date date = new Date();
        bean.setReportTime(DateUtils.formatDate(date, "yyyy-MM-dd HH:mm:ss"));

        bean.setReportStatus("0");
        log.info("report_source为:" + bean.getReportSource());
        log.info("token为:" + token);
        if (bean.getReportSource().contains("oa")) {
            try {
                DefaultResourceLoader resourceLoader = new DefaultResourceLoader();
                Resource resource = resourceLoader.getResource("LtpaToken.properties");
                String filePath = resource.getURL().getPath();

                LtpaTokenManager.loadConfig(URLDecoder.decode(URLDecoder.decode(filePath)));
                token = URLDecoder.decode(token);
                token = URLDecoder.decode(token);
                token = URLDecoder.decode(token);
                String username = "";
                boolean result = LtpaTokenManager.isValid(token);
                if (result) {//验证Token是否合法有效
                    logger.debug(".................合法token：\t\t" + token);
                    LtpaToken ltpaToken = new LtpaToken(token);
                    username = ltpaToken.getUsername();
                    bean.setReportPersonName(bean.getReportPersonName() + "-融创OA帐号:" + username);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        // 查询管理员
        User user = dao.getUser(new User());
        if (user != null) {
            bean.setExchangeBeforeUser(user.getId());
        }
        bean.setCreateBy(user.getId());
        bean.setUpdateBy(user.getId());
        Timestamp d = new Timestamp(System.currentTimeMillis());
        bean.setCreateDate(d);
        bean.setUpdateDate(d);

        int port = request.getRemotePort();//返回发出请求的客户机的端口号。
//        logger.info("port："+port);
//        String ip = StringUtils.getRemoteAddr(Servlets.getRequest());
//        /** 根据ip获得城市 */
//        String url = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=" + ip;
//        String ipResult = IpUtils.getURLContent(url).replace(";", "");
//        if (ipResult != "-2") {
//            IP2Regions json = JSON.parseObject(ipResult.split("=")[1], IP2Regions.class);
//            String city = json.getCity();
//            bean.setIpCity(city);
//        }
//        bean.setReportIp(ip);

        //
        // bean.setExchangeBeforeUser("");
        // 添加举报信息表
        int row = 0;
        try {
            row = dao.insertReport(bean);
        } catch (Exception e) {
            row = dao.insertReport(bean);
        }
        if (row == 1) { // 添加成功
            List<String> attachmentIds = bean.getIds();
            if (attachmentIds != null && attachmentIds.size() > 0) { // 添加举报附件
                for (String attachmentId : attachmentIds) {
                    ReportAttachmentUtils.addReportId(attachmentId, reportId);
                }
            }

            responseBean.setStatus(ErrorCode.STATUS_CODE_2000);
            responseBean.setMessage(GConstants.OK);
            return responseBean;
        }
        responseBean.setStatus(ErrorCode.SQL_ERROR);
        responseBean.setMessage("数据添加失败");
        return responseBean;
    }

}
