package com.jianshui.platform.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.jianshui.common.constant.InvoiceCommonConstants;
import com.jianshui.common.constant.WebServiceConstant;
import com.jianshui.common.core.domain.AjaxResult;
import com.jianshui.common.core.domain.entity.Companyservice;
import com.jianshui.common.core.domain.entity.SysUser;
import com.jianshui.common.utils.BeanToMapUtils;
import com.jianshui.common.utils.SecurityUtils;
import com.jianshui.common.utils.ValidateUtils;
import com.jianshui.common.utils.jcsk.ApiHttp;
import com.jianshui.invoice.enums.ChannelSource;
import com.jianshui.platform.domain.InvoiceDelivery;
import com.jianshui.platform.dto.InvoiceDeliveryDTO;
import com.jianshui.platform.dto.InvoiceDeliveryJsonDataDTO;
import com.jianshui.platform.mapper.InvoiceDeliveryMapper;
import com.jianshui.platform.service.InvoiceDeliveryService;
import com.jianshui.platform.utils.InvoiceAllYhdjUtils;
import com.jianshui.system.domain.InvoiceAllYhdj;
import com.jianshui.system.mapper.CompanyserviceMapper;
import com.jianshui.system.mapper.SysUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;

/**
 * @Author: xingze
 * @Description: 发票交付业务实现类
 * @CreateTime: 2023-06-06  10:33
 * @Version: 1.0
 **/
@Service
@Slf4j
public class InvoiceDeliveryServiceImpl implements InvoiceDeliveryService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private CompanyserviceMapper companyServiceMapper;

    @Autowired
    private InvoiceDeliveryMapper invoiceDeliveryMapper;


    /**
     * 功能描述: 发票交付
     * @param dtos 多张（单张）交付信息
     * @return : com.jianshui.invoice.domain.dto.HXResponse
     */
    @Override
    public AjaxResult invoiceDelivery(List<InvoiceDeliveryJsonDataDTO> dtos) {
        //获取用户id
        Long userId = SecurityUtils.getUserId();
        //根据用户id获取用户信息
        SysUser sysUser = sysUserMapper.selectUserById(userId);
        //根据企业id获取企业信息
        Companyservice companyservice = companyServiceMapper.selectCompanyserviceByCompanyid(sysUser.getCompanyId());
        //获取登记用户信息
        InvoiceAllYhdjUtils invoiceAllYhdjUtils = new InvoiceAllYhdjUtils();
        InvoiceAllYhdj userInfo = invoiceAllYhdjUtils.getUserInfo(companyservice);
        if (BeanUtil.isEmpty(userInfo)) {
            return AjaxResult.error("未查询到登记信息！");
        }
        //封装上游接口实体类
        InvoiceDeliveryDTO invoiceDeliveryDTO = new InvoiceDeliveryDTO();
        invoiceDeliveryDTO.setAsync(InvoiceCommonConstants.SYNC);
        invoiceDeliveryDTO.setBsrysfzjhm(userInfo.getBsrysfzjhm());
        invoiceDeliveryDTO.setDqbm(userInfo.getDqbm());
        invoiceDeliveryDTO.setNsrsbh(userInfo.getNsrsbh());
        //校验
        ValidateUtils.validate(invoiceDeliveryDTO);
        InvoiceDelivery invoiceDelivery = new InvoiceDelivery();
        for (InvoiceDeliveryJsonDataDTO dto : dtos) {
            invoiceDeliveryDTO.setJsonData(dto);
            ValidateUtils.validate(invoiceDeliveryDTO);
            //发送请求获取结果
            JSONObject result = null;
            try {
                //发送请求
                result = ApiHttp.request(WebServiceConstant.INVOIVEDELIVERY, WebServiceConstant.URL, JSONUtil.parseObj(BeanToMapUtils.fastJsonBean2Map(invoiceDeliveryDTO)), companyservice);
                //结果解析
                String code = result.get("code") != null ? result.get("code").toString() : "";
                String msg = result.get("msg") != null ? result.get("msg").toString() : "";
                String data = result.get("data") != null ? result.get("data").toString() : "";
                //封装实体类
                BeanUtils.copyProperties(invoiceDeliveryDTO, invoiceDelivery);
                invoiceDelivery.setJflx(dto.getJflx());
                invoiceDelivery.setFphm(dto.getFphm());
                invoiceDelivery.setGmflxdh(dto.getGmflxdh());
                invoiceDelivery.setGmfyx(dto.getGmfyx());
                invoiceDelivery.setType("1");
                invoiceDelivery.setClerk(sysUser.getUserId());
                invoiceDelivery.setCreateTime(new Date());
                invoiceDelivery.setSource(ChannelSource.PLATFORM.getCode());
                if ("0000".equals(code) && StrUtil.isNotEmpty(data)) {
                    //将数据存入业务表
                    invoiceDelivery.setStatus("0");
                    invoiceDeliveryMapper.insertInvoiceDelivery(invoiceDelivery);
                } else {
                    //将数据存入业务表
                    invoiceDelivery.setStatus("1");
                    invoiceDeliveryMapper.insertInvoiceDelivery(invoiceDelivery);
                    log.error("【发票交付】API请求异常，外部报文返回code非0000。错误id{},错误信息:{}", invoiceDelivery.getId(),msg);
                    return AjaxResult.error(msg);
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.error("【发票交付】API请求异常，外部报文返回code非0000。错误信息:{}", e.getMessage());
                return AjaxResult.error("发票支付接口异常");
            }
        }
        return AjaxResult.success("0000", "处理成功");
    }

}
