package com.dxhy.base.service.fpxxrz;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dxhy.base.dao.BaseLqDkFpycxxDao;
import com.dxhy.base.entity.BaseTDxRecordInvoice;
import com.dxhy.base.entity.TdxLqDkFpycxx;
import com.dxhy.base.service.tdxrecordinvoice.BaseIFpbrzService;
import com.dxhy.base.service.tdxrecordinvoice.BaseIRzTDxRecordInvoiceService;
import com.dxhy.common.constant.CommonConstants;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.service.impl.MpBaseServiceImpl;
import com.dxhy.common.utils.BaseContextHandler;
import com.dxhy.common.utils.R;
import com.dxhy.common.vo.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 撤销已认证发票service实现类
 *
 * @author kangzq
 * @date 2019年5月11日
 * @version 1.0
 */
@SuppressWarnings({"AlibabaMethodTooLong", "AlibabaCollectionInitShouldAssignCapacity",
    "AlibabaLowerCamelCaseVariableNaming"})
@Service("baseLqcxrzService")
@Slf4j
public class BaseLqcxrzServiceImpl extends MpBaseServiceImpl<BaseLqDkFpycxxDao, TdxLqDkFpycxx>
    implements BaseLqcxrzService {

    /**
     * 发票认证service
     */
    @Resource
    private BaseIRzTDxRecordInvoiceService baseIRzTDxRecordInvoiceService;
    /**
     * 撤销已认证发票
     */
    @Resource
    private BaseCxrzfpService baseCxrzfpService;

    @Resource
    private BaseIFpbrzService baseIFpbrzService;

    @Resource
    private BaseLqDkFpycxxDao baseDkFpycxxDao;

    @Override
    public ResponseEntity<?> lqcxrz(Map<String, Object> pramsMap) {
        DynamicContextHolder.push(getDbName() + DbConstant.BUSINESS_READ);
        pramsMap.put("dbName", getDbName());

        //撤销认证条数
        int cxrzNum = 0;
        //撤销不抵扣条数
        int cxbdkNum = 0;

        String cxids = pramsMap.get("cxids").toString();

        List<String> ids = Arrays.asList(cxids.split(","));
        LambdaQueryWrapper<BaseTDxRecordInvoice> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(BaseTDxRecordInvoice::getId,ids);
        queryWrapper.eq(BaseTDxRecordInvoice::getRzlx, "1");
        //queryWrapper.eq(BaseTDxRecordInvoice::getBdkStatus, "1");
        //查询认证数据
        List<BaseTDxRecordInvoice> recordInvoices = baseIRzTDxRecordInvoiceService.list(queryWrapper);
        for(BaseTDxRecordInvoice recordInvoice:recordInvoices){
            //撤销认证
            Map<String,Object> params = new HashMap<String,Object>();
            params.put("cxids", recordInvoice.getId());
            params.put("dbName", getDbName());
            log.info("调原有撤销认证接口");
            String result = baseCxrzfpService.updateByIds(params);
            String resultJsonStr = Base64.decodeStr(result);
            log.info("调原有撤销认证返回:{},解析出:{}",result,resultJsonStr);
            JSONObject jsonObject = JSONObject.parseObject(resultJsonStr);
            //如果是空，撤销成功，删除异常表中对应数据
            if(StringUtils.isEmpty(jsonObject.getString("message"))){
                BaseTDxRecordInvoice byId = baseIRzTDxRecordInvoiceService.getById(recordInvoice.getId());
                log.info("删除异常信息表数据");
                LambdaQueryWrapper<TdxLqDkFpycxx> fpycxxWrapper = new LambdaQueryWrapper<>();
                fpycxxWrapper.eq(TdxLqDkFpycxx::getUuid, byId.getUuid());
                baseDkFpycxxDao.delete(fpycxxWrapper);
                cxrzNum++;
            }
        }

        queryWrapper.clear();
        queryWrapper.in(BaseTDxRecordInvoice::getId,ids);
        queryWrapper.eq(BaseTDxRecordInvoice::getRzlx, "4");
        //queryWrapper.eq(BaseTDxRecordInvoice::getBdkStatus, "2");
        //查询认证不抵扣数据
        recordInvoices = baseIRzTDxRecordInvoiceService.list(queryWrapper);
        for(BaseTDxRecordInvoice recordInvoice:recordInvoices){
            //撤销认证不抵扣
            Map<String,Object> params = new HashMap<String,Object>();
            params.put("uuids", recordInvoice.getUuid());
            params.put("dbName", getDbName());
            log.info("调原有撤销认证不抵扣接口");
            String result =  baseIFpbrzService.updateByQxFpbrz(params);
            String resultJsonStr = Base64.decodeStr(result);
            log.info("调原有撤销认证不抵扣接口返回:{},解析出:{}",result,resultJsonStr);
            JSONObject jsonObject = JSONObject.parseObject(resultJsonStr);
            //如果是空，撤销成功，删除异常表中对应数据
            if(StringUtils.isEmpty(jsonObject.getString("message"))){
                BaseTDxRecordInvoice byId = baseIRzTDxRecordInvoiceService.getById(recordInvoice.getId());
                log.info("删除异常信息表数据");
                LambdaQueryWrapper<TdxLqDkFpycxx> fpycxxWrapper = new LambdaQueryWrapper<>();
                fpycxxWrapper.eq(TdxLqDkFpycxx::getUuid, byId.getUuid());
                baseDkFpycxxDao.delete(fpycxxWrapper);
                cxbdkNum++;
            }
        }

        log.info("撤销认证条数:{},撤销认证不抵扣条数:{}",cxrzNum,cxbdkNum);
        try {
            return ResponseEntity.ok(R.ok());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("", e);
            return ResponseEntity.ok(R.error(CommonConstants.MSG_ERR_DEFAULT));
        }
    }

    public UserInfo getUserInfo() {
        String userInfo = BaseContextHandler.getUserInfo();
        UserInfo user = null;
        if (StringUtils.isNotBlank(userInfo)) {
            user = JSON.parseObject(userInfo, UserInfo.class);
        }
        return user;
    }


    /**
     * @Description 获取当前用户使用的数据库
     * @Author wangruwei
     * @Date 2022/11/24 17:26
     **/
    public static String getDbName(){
        String userInfo = BaseContextHandler.getUserInfo();
        UserInfo user = null;
        if (StringUtils.isNotBlank(userInfo)) {
            user = JSON.parseObject(userInfo, UserInfo.class);
        }
        if(ObjectUtil.isEmpty(user)){
            return "business";
        }
        return user.getDbName();
    }
}
