package com.chinacreator.video.restful.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chinacreator.video.bean.ChannelBean;
import com.chinacreator.video.bean.OrderInfo;
import com.chinacreator.video.exception.BussinessException;
import com.chinacreator.video.mapper.ChannelDao;
import com.chinacreator.video.restful.dao.NewYearVideoDao;
import com.chinacreator.video.service.CommonService;
import com.chinacreator.video.util.DesUtil;
import com.chinacreator.video.util.MD5;
import com.chinacreator.video.validate.ChannelValidate;
import com.chinacreator.video.validate.IpValidate;
import com.chinacreator.video.validate.TimetampValidate;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.ims.v20201229.ImsClient;
import com.tencentcloudapi.ims.v20201229.models.ImageModerationRequest;
import com.tencentcloudapi.ims.v20201229.models.ImageModerationResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

@Service
public class NewYearVideoService {

    @Autowired
    private NewYearVideoDao newYearVideoDao;


    @Autowired
    private ChannelValidate channelValidate;

    @Autowired
    private IpValidate ipValidate;

    @Autowired
    private TimetampValidate timetampValidate;

    @Autowired
    private ChannelDao channelDao;

    @Autowired
    private CommonService commonService;

    public static void main(String[] args) throws UnsupportedEncodingException {
        System.out.println(URLEncoder.encode("tjjx+jN5j5czfVI\\/00wf23bsco2\\/shV9Q5jtvuaft0927295u6FLmg==","UTF-8"));
    }
    public String insertUserInfo(Map<String, Object> params) {
        String photos = String.valueOf(params.get("photos"));//格式逗号分隔（字节流可能是）
        String modules = String.valueOf(params.get("modules"));//格式逗号分隔
        String id = newYearVideoDao.getID();
        params.put("id",id);
        newYearVideoDao.insertVideoInfo(params);
        return id;
    }

    public int getNowNumber(String id){
        //返回给前端当前的序号
        int now_number = newYearVideoDao.queryNumber(id);
        return now_number;
    }

    public int getNowNumber2(String id){
        //返回给前端当前的序号
        int now_number = newYearVideoDao.queryNumber2(id);
        return now_number;
    }

    public String queryUserStatus(String id){
        return  newYearVideoDao.queryUserStatus(id);
    }

    public void hasRset(String id){
        newYearVideoDao.hasRset(id);
    }

    public void hasFinished(Map<String, Object> params){
        if("400".equals(String.valueOf(params.get("state")))){
            params.put("state","6");//标识失败
        }else{
            params.put("state","0");//成功
        }
        newYearVideoDao.hasFinished(params);
    }
    /***
     * 校验
     * @throws Exception
     */
    public void busiCheck(Map<String, Object> params) throws Exception {
        OrderInfo orderInfo=new OrderInfo();
        orderInfo.setTimestamp(String.valueOf(params.get("timestamp")));
        orderInfo.setUserid(String.valueOf(params.get("wxuserid")));//用户wxid
        orderInfo.setChannel(String.valueOf(params.get("channel")));
        orderInfo.setType(String.valueOf(params.get("type")));
        orderInfo.setSignature(String.valueOf(params.get("signature")));
        String photos = String.valueOf(params.get("photos"));//格式逗号分隔（字节流可能是）
        String modules = String.valueOf(params.get("modules"));//格式逗号分隔
        if (StringUtils.isEmpty(photos)){
            throw  new BussinessException("1021","照片参数不能为空");
        }
        if (StringUtils.isEmpty(modules)){
            throw  new BussinessException("1022","模板参数不能为空");
        }
        //timetamp验证
        //timetampValidate.validate(orderInfo.getTimestamp());
        //渠道验证
        channelValidate.validate(orderInfo.getChannel());
        //ip验证
        ipValidate.volidate(orderInfo,"1");
        //签名验证
        validate(orderInfo);
        //访问限制
        //vistVali(orderInfo,String.valueOf(params.get("type")));
    }

    /***
     * 校验
     * @throws Exception
     */
    public void busiQueryCheck(Map<String, Object> params) throws Exception {
        OrderInfo orderInfo=new OrderInfo();
        orderInfo.setTimestamp(String.valueOf(params.get("timestamp")));
        orderInfo.setUserid(String.valueOf(params.get("wxuserid")));
        orderInfo.setType(String.valueOf(params.get("type")));
        orderInfo.setChannel(String.valueOf(params.get("channel")));
        orderInfo.setSignature(String.valueOf(params.get("signature")));

        //timetamp验证
        //timetampValidate.validate(orderInfo.getTimestamp());
        //渠道验证
        channelValidate.validate(orderInfo.getChannel());
        //ip验证
        ipValidate.volidate(orderInfo,"1");
        //签名验证
        validate(orderInfo);
        //访问限制
        //vistVali(orderInfo,String.valueOf(params.get("type")));
    }

    /***
     * 校验
     * @throws Exception
     */
    public void busiFinishCheck(Map<String, Object> params) throws Exception {
        OrderInfo orderInfo=new OrderInfo();
        orderInfo.setChannel("newyearvideo");
        //ip验证
        ipValidate.volidate(orderInfo,"1");
    }
    /**
     * 验证访问限制，1分钟内同一业务只能办理一次
     * @param orderInfo
     * @throws Exception
     * type 1：插入业务数据 2：查询业务数据
     */
    private void vistVali(OrderInfo orderInfo,String type) throws Exception {
        String [] params = new String [2];
        params[0] = type;
        params[1] = orderInfo.getUserid();
        if(commonService.vistVali2(params, "NewYearVideoInfo")){
            throw new BussinessException("8001", "指定时间内重复请求");
        }
    }

    public String validateWX(String wxuserid,String channel) throws Exception {
        if(StringUtils.isEmpty(wxuserid)) {
            throw new BussinessException("10007", "微信号不能为空");
        }
        ChannelBean channelBean = channelDao.queryChannel(channel);
        try {
            wxuserid = DesUtil.decode(wxuserid, channelBean.getPassword());
        } catch (Exception e) {
            if(e instanceof BussinessException){
                throw e;
            }else {
                throw new BussinessException("10008", "微信号加密错误");
            }
        }
        return wxuserid;
    }

    public void validate(OrderInfo orderInfo) throws Exception {
        String lcalsign = getSign(orderInfo);
        System.out.println(lcalsign);
        lcalsign = MD5.MD5Encode(lcalsign);
        System.out.println(lcalsign);
        if(!lcalsign.equals(orderInfo.getSignature())) {
            throw new BussinessException("10006", "签名校验失败");
        }
    }
    /**
     * 拼接签名信息 wxuserid+type+channel+timestamp
     * @param orderInfo
     * @return
     */
    private String getSign(OrderInfo orderInfo) {
        if (orderInfo == null) {
            return "";
        }
        StringBuilder strb = new StringBuilder();
        strb.append(orderInfo.getUserid());
        strb.append(orderInfo.getType());
        strb.append(orderInfo.getChannel());
        strb.append(orderInfo.getTimestamp());
        return strb.toString();
    }


    public Map<String, Object> queryVideoInfo(Map<String, Object> params) {
        List<Map<String, Object>> list = newYearVideoDao.queryVideoInfo(params);//取最新的一条数据
        if (list!=null && list.size()>0){
            return  list.get(0);
        }else {
            return null;
        }
    }

    public String checkPhoto(String photo){
        try{

            Credential cred = new Credential("AKID6zcMtBm746rNVQoSZR2MQWMDj0YqvbeV", "qWmptRlpc8QUKPI2WpsgGZdwrzvby5A6");

            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("ims.tencentcloudapi.com");

            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);

            ImsClient client = new ImsClient(cred, "ap-shanghai", clientProfile);

            ImageModerationRequest req = new ImageModerationRequest();
            req.setFileContent(photo);

            ImageModerationResponse resp = client.ImageModeration(req);
            String result = ImageModerationResponse.toJsonString(resp);
            JSONObject jsonObject = JSON.parseObject(result);
            if("Pass".equals(jsonObject.getString("Suggestion"))){
                System.out.println("pass");
                return "pass";
            }else{
                System.out.println("false");
                return "block";//屏蔽
            }
        } catch (TencentCloudSDKException e) {
            System.out.println(e.toString());
            return "false";//审核失败
        }
    }
}
