package com.weaver.seconddev.chapanda.esign.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.weaver.common.hrm.util.HrmCommonUtil;
import com.weaver.seconddev.chapanda.esign.constant.Constants;
import com.weaver.seconddev.chapanda.esign.dao.SealTemplateDao;
import com.weaver.seconddev.chapanda.esign.entity.OkHttpDto;
import com.weaver.teams.domain.user.SimpleEmployee;
import okhttp3.*;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;

@Component
public class Esb2EsignBuildTemplatDoceUtil {
    private final static Logger log = LoggerFactory.getLogger(Esb2EsignBuildTemplatDoceUtil.class);

    @Autowired
    SealTemplateDao sealTemplateDao;

    @Autowired
    private HrmCommonUtil hrmCommonUtil;

    @Autowired
    private Esb2EsignBuildTemplatDoceUtil esb2EsignBuildTemplatDoceUtil;

    @Autowired
    private Esb2EsignPreviewUrlUtil esb2EsignPreviewUrlUtil;


    public OkHttpDto queryTemplateFileKey(String templateId,Map<String, Object> paraMap) {
        Map<String, Object> dataMap = new HashMap<String, Object>();

        List<Map<String,Object>> templateFieldList = sealTemplateDao.queryTemplateFieldByTemplateId(templateId);
        log.error("templateFieldList:{}",templateFieldList.size());
        String employee_id = String.valueOf(paraMap.get("employee_id"));
        Long employeeId = 0L;
        if(StringUtils.isNotBlank(employee_id)){
            employeeId = Long.valueOf(employee_id);
        }
        SimpleEmployee simpleEmployee = hrmCommonUtil.getSimpleEmployee(employeeId);
        log.error("simpleEmployee:{}",simpleEmployee.getUsername());
        JSONObject bodyJson = new JSONObject();

        JSONArray formArray = new JSONArray();
        for(int i=0;i<templateFieldList.size();i++){
            Map<String,Object> templateField = templateFieldList.get(i);
            String zdm = String.valueOf(templateField.get("zdm"));
            String zdlx = String.valueOf(templateField.get("zdlx"));
            String zdz = String.valueOf(templateField.get("zdz"));
            log.error("zdm:{}",zdm);
            log.error("zdlx:{}",zdlx);
            log.error("zdz:{}",zdz);
            JSONObject formJson  = converFieldValue(paraMap,simpleEmployee,zdlx,zdz,zdm);
            formArray.add(formJson);
        }
        bodyJson.put("templateFormValues",formArray);
        bodyJson.put("templateId",templateId);
        log.error("bodyJson:{}",bodyJson.toJSONString());

        String xTimevaleSignature = encryptionHmacSHA256(bodyJson.toJSONString());
        log.error("xTimevaleSignature:{}",xTimevaleSignature);
        OkHttpDto okHttpDto = doPostHttp(xTimevaleSignature,bodyJson.toJSONString());

//        dataMap.put("bodyData",bodyJson.toJSONString());
//        dataMap.put("filekey",fileKey);
//        dataMap.put("previewurl",preViewUrl);

        return okHttpDto;
    }

    public OkHttpDto queryPreviewUrl(String fileKey) {

        OkHttpDto okHttpDto = new OkHttpDto();
        if(StringUtils.isNotBlank(fileKey)){
            okHttpDto =  esb2EsignPreviewUrlUtil.queryPreviewUrl(fileKey);
        }

//        log.error("preViewUrl:{}",preViewUrl);
//        dataMap.put("bodyData",bodyJson.toJSONString());
//        dataMap.put("filekey",fileKey);
//        dataMap.put("previewurl",preViewUrl);

        return okHttpDto;
    }

//    public OkHttpDto getTemplateFileKey(String bodyData){
//        JSONArray formArray = new JSONArray();
//        for(int i=0;i<templateFieldList.size();i++){
//            Map<String,Object> templateField = templateFieldList.get(i);
//            String zdm = String.valueOf(templateField.get("zdm"));
//            String zdlx = String.valueOf(templateField.get("zdlx"));
//            String zdz = String.valueOf(templateField.get("zdz"));
//
//            log.error("zdm:{}",zdm);
//            log.error("zdlx:{}",zdlx);
//            log.error("zdz:{}",zdz);
//
//            JSONObject formJson  = converFieldValue(paraMap,simpleEmployee,zdlx,zdz,zdm);
//
//            formArray.add(formJson);
//        }
//        bodyJson.put("templateFormValues",formArray);
//        bodyJson.put("templateId",templateId);
//        log.error("bodyJson:{}",bodyJson.toJSONString());
//
//        String xTimevaleSignature = encryptionHmacSHA256(bodyData);
//        log.error("xTimevaleSignature:{}",xTimevaleSignature);
//        OkHttpDto okHttpDto = doPostHttp(xTimevaleSignature,bodyData);
////        log.error("msg:{}",msg);
////        if(StringUtils.isNotBlank(msg)){
////            JSONObject bodyJson = JSONObject.parseObject(msg);
////            if(bodyJson.containsKey("errCode")){
////                String errCode = bodyJson.getString("errCode");
////                if("0".equals(errCode)){
////                    JSONObject dataJson = bodyJson.getJSONObject("data");
////                    if(dataJson.containsKey("fileKey")){
////                        fileKey = dataJson.getString("fileKey");
////                    }
////                }
////            }
////        }
////        log.error("fileKey:{}",fileKey);
//        return okHttpDto;
//    }

    /***
     *
     * @param xTimevaleSignature
     * @return
     */
    public OkHttpDto doPostHttp(String xTimevaleSignature,String bodyData){

        OkHttpDto okHttpDto = new OkHttpDto();
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        // "{\n\t\"templateFormValues\": [\n\t\t{\n\t\t\t\"formId\": 186,\n\t\t\t\"formValue\": \"50\"\n\t\t},\n\t\t{\n\t\t\t\"formId\": 185,\n\t\t\t\"formValue\": \"壹万元\"\n\t\t},\n\t\t{\n\t\t\t\"formId\": 184,\n\t\t\t\"formValue\": \"10000\"\n\t\t},\n\t\t{\n\t\t\t\"formId\": 183,\n\t\t\t\"formValue\": \"茶百道测试\"\n\t\t},\n\t\t{\n\t\t\t\"formId\": 182,\n\t\t\t\"formValue\": \"HT-001\"\n\t\t},\n\t\t{\n\t\t\t\"formId\": 181,\n\t\t\t\"formValue\": \"HT-001\"\n\t\t},\n\t\t{\n\t\t\t\"formId\": 135,\n\t\t\t\"formValue\": \"01\"\n\t\t},\n\t\t{\n\t\t\t\"formId\": 134,\n\t\t\t\"formValue\": \"06\"\n\t\t},\n\t\t{\n\t\t\t\"formId\": 132,\n\t\t\t\"formValue\": \"2025\"\n\t\t},\n\t\t{\n\t\t\t\"formId\": 131,\n\t\t\t\"formValue\": \"HT-001\"\n\t\t},\n\t\t{\n\t\t\t\"formId\": 130,\n\t\t\t\"formValue\": \"成都嘉煜中1楼\"\n\t\t},\n\t\t{\n\t\t\t\"formId\": 129,\n\t\t\t\"formValue\": \"成都嘉煜中心店\"\n\t\t},\n\t\t{\n\t\t\t\"formId\": 128,\n\t\t\t\"formValue\": \"成都嘉煜中1楼\"\n\t\t},\n\t\t{\n\t\t\t\"formId\": 127,\n\t\t\t\"formValue\": \"320328198803201515\"\n\t\t},\n\t\t{\n\t\t\t\"formId\": 126,\n\t\t\t\"formValue\": \"01\"\n\t\t},\n\t\t{\n\t\t\t\"formId\": 125,\n\t\t\t\"formValue\": \"06\"\n\t\t},\n\t\t{\n\t\t\t\"formId\": 124,\n\t\t\t\"formValue\": \"2025\"\n\t\t}\n\t],\n\t\"templateId\": \"JMHT-ZXSJ\"\n\t\n}"
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, bodyData);
        try {
            Request request = new Request.Builder()
                    .url(Constants.eSignHost+Constants.templateDocUrl)
                    .method("POST", body)
                    .addHeader("x-timevale-project-id", Constants.xTimevaleProjectId)
                    .addHeader("x-timevale-signature", xTimevaleSignature)
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = client.newCall(request).execute();
            int code = response.code();
            String msg = response.body().string();
            log.error("code:{}",code);
            log.error("msg:{}",msg);
            okHttpDto.setResponseCode(code);
            okHttpDto.setResponseBody(msg);
            convertData(msg,okHttpDto);

        } catch (IOException e) {
            log.error("e:"+e.getMessage());
            throw new RuntimeException(e);
        }
        return okHttpDto;
    }

    /***
     *
     * @param bodyData
     * @return
     */
    public String encryptionHmacSHA256(String bodyData){
        String encryptionData = "";
        try {
            // 初始化Mac对象
            Mac sha256Hmac = Mac.getInstance("HmacSHA256");
            SecretKeySpec secretKeySpec = new SecretKeySpec(Constants.secretKey.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
            sha256Hmac.init(secretKeySpec);
            byte[] result = sha256Hmac.doFinal(bodyData.getBytes(StandardCharsets.UTF_8));
            encryptionData = Hex.encodeHexString(result);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        }
        return encryptionData;
    }


    public void convertData(String reposponseBody,OkHttpDto okHttpDto){
        JSONObject bodyJson = JSONObject.parseObject(reposponseBody);
        int errCode = -100;
        if(bodyJson.containsKey("errCode")){
            errCode = bodyJson.getInteger("errCode");
            log.error("errCode:{}",errCode);
        }
        okHttpDto.setDataCode(errCode);
        String msg = "";
        if(bodyJson.containsKey("msg")){
            msg = bodyJson.getString("msg");
            log.error("msg:{}",msg);
        }
        okHttpDto.setDataMsg(msg);

        if(errCode == 0){
            JSONObject responseDataJson = new JSONObject();
            if(bodyJson.containsKey("data")){
                String data = bodyJson.getString("data");
                if(StringUtils.isNotBlank(data)){
                    JSONObject dataJson = bodyJson.getJSONObject("data");
                    if(dataJson.containsKey("fileKey")){
                        String fileKey = dataJson.getString("fileKey");
                        responseDataJson.put("fileKey",fileKey);
                    }
                }
            }
            okHttpDto.setDataJson(responseDataJson);
        }
    }


    /***
     *  转换规则
     * @param paraMap
     * @param simpleEmployee
     * @param zdz
     * @param zdm
     */
    public JSONObject converFieldValue(Map<String,Object> paraMap, SimpleEmployee simpleEmployee, String zdlx, String zdz, String zdm){
        log.error("converFieldValue:zdlx:{}",zdlx);

        JSONObject bodyJson = new JSONObject();
        // 固定值
        String value = "";
        if("1".equals(zdlx)){
            value = zdz ;
        }else if("2".equals(zdlx)){ //从入参获取
            log.error("containsKey:{}",paraMap.containsKey(zdz));
            if(paraMap.containsKey(zdz)){
                value = String.valueOf(paraMap.get(zdz));
            }
            log.error("value:{}",value);
        }else if("3".equals(zdlx)){ //sql语句获取
            if(StringUtils.isNotBlank(zdm)){
                Iterator<Map.Entry<String, Object>> it = paraMap.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry<String, Object> entry = it.next();
                    log.error("Key:{},Value:{}",entry.getKey(), entry.getValue());
                    String paramKey = entry.getKey();
                    String paramValue = entry.getValue().toString();
                    if(zdz.contains("{?"+paramKey+"}")){
                        zdz = zdz.replace("{?"+paramKey+"}",paramValue);
                    }
                }
                log.error("zdz:{}",zdz);
                value = sealTemplateDao.queryValueByConfig(zdz);
                log.error("value:{}",value);
            }
        }else if("4".equals(zdlx)){ //当前登录人ID
            Long employeeId = simpleEmployee.getEmployeeId();
            value = String.valueOf(employeeId);
        }else if("5".equals(zdlx)){ //当前登录人姓名
            String username = simpleEmployee.getUsername();
            value = username;
        }else if("6".equals(zdlx)){ //当前登录人部门ID
            Long departmentId = simpleEmployee.getDepartmentId();
            value = String.valueOf(departmentId);
        }else if("7".equals(zdlx)){ //当前登录人部门名称
            String departmentName = simpleEmployee.getDepartment().getName();
            value = departmentName;
        }else if("8".equals(zdlx)){ //当前日期
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            value = sdf.format(new Date());
        }else if("9".equals(zdlx)){ //当前时间
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            value = sdf.format(new Date());
        }else if("10".equals(zdlx)){ //当前时间
            LocalDate localDate = LocalDate.now();
            value = String.valueOf(localDate.getYear());
        }else if("11".equals(zdlx)){ //当前时间
            LocalDate localDate = LocalDate.now();
            value = String.valueOf(localDate.getMonthValue());
            if(localDate.getMonthValue() <10){
                value = "0"+value;
            }
        }else if("12".equals(zdlx)){ //当前时间
            LocalDate localDate = LocalDate.now();
            value = String.valueOf(localDate.getDayOfMonth());
            if(localDate.getMonthValue() <10){
                value = "0"+value;
            }
        }

        bodyJson.put("formId",zdm);
        bodyJson.put("formValue",value);
        return bodyJson;
    }

}
