package com.dxhy.core.job.service.impl;

import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.core.job.dao.SysUserDao;
import com.dxhy.core.job.entity.SysDeptEntity;
import com.dxhy.core.job.entity.SysUserEntity;
import com.dxhy.core.job.service.SysDeptService;
import com.dxhy.core.job.service.SysUserService;
import com.dxhy.core.util.HttpRequestUtils;
import com.dxhy.core.util.ObjectUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * 系统用户
 *
 */
@Service("sysUserService")
@Slf4j
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUserEntity> implements SysUserService {
    @Value("${license.uid:}")
    private String uid;
    @Value("${license.secret:}")
    private String secret;
    @Value("${license.je:}")
    private String je;
    @Value("${license.licenseUrl:}")
    private String licenseUrl;
    @Value("${signature.url:}")
    private String signatureUrl;
    @Value("${signature.appKey:}")
    private String appKey;
    @Value("${signature.appSecret:}")
    private String appSecret;
    @Value("${signature.tokenUrl:}")
    private String tokenUrl;
    @Resource
    private SysDeptService sysDeptService;

    @Override
    public void getLicenseCode() {
        DynamicContextHolder.push("business" + DbConstant.BASICS_READ);
        List<SysUserEntity> userList = this.baseMapper.getSpCode();
        if (userList != null && userList.size() > 0) {
            for (SysUserEntity entity : userList) {
                if (StringUtils.isBlank(entity.getAuthorizeCode())) {
                    DynamicContextHolder.push("business" + DbConstant.BASICS_READ);
                    SysUserEntity user = this.baseMapper.getSpCodeByAuthCode(entity.getTaxno(), entity.getSpCode());
                    if (user != null) {
                        entity.setAuthorizeCode(user.getAuthorizeCode());
                        entity.setLastDate(user.getLastDate());
                        DynamicContextHolder.push("business" + DbConstant.BASICS_WRITE);
                        this.baseMapper.updateById(entity);
                        continue;
                    }
                }
                DynamicContextHolder.push("business" + DbConstant.BASICS_READ);
                SysDeptEntity dept = sysDeptService.getById(entity.getDeptId());
                List<NameValuePair> list = new ArrayList<>();
                list.add(new BasicNameValuePair("uid", uid));
                list.add(new BasicNameValuePair("secret", secret));
                list.add(new BasicNameValuePair("nsrmc", dept.getTaxname()));
                list.add(new BasicNameValuePair("nsrsbh", dept.getTaxno()));
                list.add(new BasicNameValuePair("skph", entity.getSpCode()));
                list.add(new BasicNameValuePair("je", je));
                if ("1".equals(entity.getSpType())) {
                    list.add(new BasicNameValuePair("rjlx", "8"));
                } else if ("2".equals(entity.getSpType())) {
                    list.add(new BasicNameValuePair("rjlx", "1"));
                } else if ("3".equals(entity.getSpType())) {
                    list.add(new BasicNameValuePair("rjlx", "6"));
                }
                list.add(new BasicNameValuePair("rjgn", "001"));
                list.add(new BasicNameValuePair("fplx", "000"));
                list.add(new BasicNameValuePair("bgsq", "0"));
                list.add(new BasicNameValuePair("zcmds", "0"));
                if (StringUtils.isBlank(entity.getAuthorizeCode())) {
                    list.add(new BasicNameValuePair("xfsq", "0"));
                } else {
                    list.add(new BasicNameValuePair("xfsq", "1"));
                }
                log.info(JSON.toJSONString(list));
                try {
                    String responseJson = HttpRequestUtils.httpPostXFU(list, licenseUrl);
                    System.out.println(responseJson);
                    JSONObject jsonObject = JSON.parseObject(responseJson);
                    String statusCode = jsonObject.getString("statusCode");
                    String message = jsonObject.getString("message");
                    String zcm = jsonObject.getString("zcm");
                    String jzsj = jsonObject.getString("jzsj");
                    if ("200".equals(statusCode)) {
                        SysUserEntity updateEntity = new SysUserEntity();
                        updateEntity.setAuthorizeCode(zcm);
                        updateEntity.setLastDate(new SimpleDateFormat("yyyyMMdd").parse(jzsj));
                        updateEntity.setMessage("success");
                        DynamicContextHolder.push("business" + DbConstant.BASICS_WRITE);
                        QueryWrapper<SysUserEntity> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("taxno", entity.getTaxno());
                        queryWrapper.eq("sp_code", entity.getSpCode());
                        queryWrapper.eq("user_type", "2");
                        this.baseMapper.update(updateEntity, queryWrapper);
                    } else {
                        entity.setMessage(message);
                        DynamicContextHolder.push("business" + DbConstant.BASICS_WRITE);
                        this.baseMapper.updateById(entity);
                    }

                    // this.baseMapper.updateById(entity);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }
    }

    @Override
    public void getFpzyztp() {
        try {
            DynamicContextHolder.push("business" + DbConstant.BASICS_READ);
            List<SysUserEntity> userList = this.baseMapper.listUser();
            if (userList != null && userList.size() > 0) {
                for (SysUserEntity entity : userList) {
                    DynamicContextHolder.push("business" + DbConstant.BASICS_READ);
                    SysUserEntity user = this.baseMapper.listUserByTaxno(entity.getTaxno());
                    if (user != null) {
                        entity.setFpzyztp(user.getFpzyztp());
                        DynamicContextHolder.push("business" + DbConstant.BASICS_WRITE);
                        this.baseMapper.updateById(entity);
                        continue;
                    }
                    DynamicContextHolder.push("business" + DbConstant.BASICS_READ);
                    SysDeptEntity dept = sysDeptService.getById(entity.getDeptId());
                    if (dept != null) {
                        String accessToken = getToken();
                        if (StringUtils.isNotBlank(accessToken)) {
                            Map<String, String> map = new HashMap<>();
                            map.put("NSRSBH", dept.getTaxno());
                            map.put("NSRMC", dept.getTaxname());
                            map.put("FPZYZHPHM", "");
                            map.put("FPZYZSXBM", "");
                            String str = JSON.toJSONString(map);
                            Map<String, String> reqMap = new HashMap<>();
                            reqMap.put("zipCode", "0");
                            reqMap.put("encryptCode", "0");
                            String dataExchangeId =
                                LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"))
                                    + ObjectUtil.getRandom(18);
                            reqMap.put("dataExchangeId", dataExchangeId);
                            reqMap.put("entCode", "YHCS");
                            reqMap.put("content", Base64.encodeBase64String(str.getBytes(StandardCharsets.UTF_8)));
                            String reqStr = JSON.toJSONString(reqMap);
                            log.info("签章图片请求报文=============" + reqStr);
                            String resultStr =
                                HttpRequestUtils.httpPost(reqStr, signatureUrl + "create?access_token=" + accessToken);
                            log.info("签章图片返回报文==============" + resultStr);
                            JSONObject jsonObject = JSON.parseObject(resultStr);
                            String returnStateInfo = jsonObject.getString("returnStateInfo");
                            JSONObject returnObject = JSON.parseObject(returnStateInfo);
                            String returnCode = returnObject.getString("returnCode");
                            if ("0000".equals(returnCode)) {
                                String content = jsonObject.getString("content");
                                String conStr = cn.hutool.core.codec.Base64.decodeStr(content);
                                JSONObject contenObject = JSON.parseObject(conStr);
                                String code = contenObject.getString("CODE");
                                if ("0000".equals(code)) {
                                    String data = contenObject.getString("DATA");
                                    JSONObject dataObject = JSON.parseObject(data);
                                    String fpzyztp = dataObject.getString("FPZYZTP");
                                    if (StringUtils.isNotBlank(fpzyztp)) {
                                        entity.setFpzyztp(fpzyztp);
                                        DynamicContextHolder.push("business" + DbConstant.BASICS_WRITE);
                                        this.baseMapper.updateById(entity);
                                    }
                                }

                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void getSignatureId() {
        try {
            DynamicContextHolder.push("business" + DbConstant.BASICS_READ);
            List<SysUserEntity> userList = this.baseMapper.listUserToSignatureId();
            if (userList != null && userList.size() > 0) {
                for (SysUserEntity entity : userList) {
                    DynamicContextHolder.push("business" + DbConstant.BASICS_READ);
                    SysUserEntity user = this.baseMapper.listUserToSignatureIdByTaxno(entity.getTaxno());
                    if (user != null) {
                        entity.setSignatureId(user.getSignatureId());
                        DynamicContextHolder.push("business" + DbConstant.BASICS_WRITE);
                        this.baseMapper.updateById(entity);
                        continue;
                    }
                    DynamicContextHolder.push("business" + DbConstant.BASICS_READ);
                    SysDeptEntity dept = sysDeptService.getById(entity.getDeptId());
                    if (dept != null) {
                        String accessToken = getToken();
                        if (StringUtils.isNotBlank(accessToken)) {
                            Map<String, String> map = new HashMap<>();
                            map.put("NSRSBH", dept.getTaxno());
                            map.put("NSRMC", dept.getTaxname());
                            map.put("FPZYZTP", entity.getFpzyztp());
                            String str = JSON.toJSONString(map);
                            Map<String, String> reqMap = new HashMap<>();
                            reqMap.put("zipCode", "0");
                            reqMap.put("encryptCode", "0");
                            String dataExchangeId =
                                LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"))
                                    + ObjectUtil.getRandom(18);
                            reqMap.put("dataExchangeId", dataExchangeId);
                            reqMap.put("entCode", "YHCS");
                            reqMap.put("content", Base64.encodeBase64String(str.getBytes(StandardCharsets.UTF_8)));
                            String reqStr = JSON.toJSONString(reqMap);
                            String resultStr = HttpRequestUtils.httpPost(reqStr,
                                signatureUrl + "register?access_token=" + accessToken);
                            JSONObject jsonObject = JSON.parseObject(resultStr);
                            String returnStateInfo = jsonObject.getString("returnStateInfo");
                            JSONObject returnObject = JSON.parseObject(returnStateInfo);
                            String returnCode = returnObject.getString("returnCode");
                            if ("0000".equals(returnCode)) {
                                String content = jsonObject.getString("content");
                                String conStr = cn.hutool.core.codec.Base64.decodeStr(content);
                                JSONObject contentObject = JSON.parseObject(conStr);
                                String code = contentObject.getString("CODE");
                                if ("0000".equals(code)) {
                                    String data = contentObject.getString("DATA");
                                    JSONObject dataObject = JSON.parseObject(data);
                                    String qzid = dataObject.getString("QZID");
                                    if (StringUtils.isNotBlank(qzid)) {
                                        entity.setSignatureId(qzid);
                                        DynamicContextHolder.push("business" + DbConstant.BASICS_WRITE);
                                        this.baseMapper.updateById(entity);
                                    }
                                }

                            }
                        }

                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getToken() {
        Map<String, String> map = new HashMap<>();
        map.put("appKey", appKey);
        map.put("appSecret", appSecret);
        String requestStr = JSON.toJSONString(map);
        log.info("签章token获取" + requestStr);
        try {
            String responseStr = HttpRequestUtils.httpPost(requestStr, tokenUrl);
            JSONObject jsonObject = JSON.parseObject(responseStr);
            return jsonObject.getString("access_token");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
