package org.dromara.zhishu.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.pdd.pop.sdk.common.util.JsonUtil;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.zhishu.domain.PrintTemplate;
import org.dromara.zhishu.util.InterfaceUtils;
import org.dromara.zhishu.util.UrlUtil;
import org.springframework.stereotype.Service;
import org.dromara.zhishu.domain.bo.FastMailBo;
import org.dromara.zhishu.domain.vo.FastMailVo;
import org.dromara.zhishu.domain.FastMail;
import org.dromara.zhishu.mapper.FastMailMapper;
import org.dromara.zhishu.service.IFastMailService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 快递打单账号管理Service业务层处理
 *
 * @author yxy
 * @date 2025-06-06
 */
@RequiredArgsConstructor
@Service
public class FastMailServiceImpl implements IFastMailService {

    private final FastMailMapper baseMapper;

    /**
     * 查询快递打单账号管理
     *
     * @param id 主键
     * @return 快递打单账号管理
     */
    @Override
    public FastMailVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 根据用户id和快递类型查询
     * @param userId
     * @param type
     * @return
     */
    @Override
    public FastMailVo selectByUserIdAndType(String userId,String type){
        return baseMapper.selectByUserIdAndType(userId,type);
    }

    /**
     * 分页查询快递打单账号管理列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 快递打单账号管理分页列表
     */
    @Override
    public TableDataInfo<FastMailVo> queryPageList(FastMailBo bo, PageQuery pageQuery) {
        // 获取当前用户id
        Long userId = LoginHelper.getUserId();
        // 获取白名单
        if (userId != 1) {
            bo.setCreateBy(userId);
        }
        LambdaQueryWrapper<FastMail> lqw = buildQueryWrapper(bo);
        Page<FastMailVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        List<FastMailVo> fastMailVoList = result.getRecords();
        for (FastMailVo vo : fastMailVoList){
            Map map = new HashMap();
            if (vo.getFastMailType().equals("1")){
                if(vo.getType().equals("YUNDA")){
                    map.put("partnerId",vo.getPartnerId());
                    map.put("secret",vo.getSecret());
                    map.put("type","common");
                    String commonStr = InterfaceUtils.getInterfaceGetWithParams(UrlUtil.getOrderServiceUrl(),"/api/print/searchCount",map);
                    Map commonDataMap = JsonUtil.transferToObj(commonStr,Map.class);
                    if (commonDataMap.get("code").equals("200") && !commonDataMap.get("data").toString().contains("ERROR")){
                        // 韵达调用成功后，在调用获取 "代收货款" 的数量
                        List commonDataList = (List) commonDataMap.get("data");
                        Map commonData = (Map) commonDataList.get(0);
                        String commonRemainNum = commonData.get("remain_num").toString();
                        map.put("type","cod");
                        String codStr = InterfaceUtils.getInterfaceGetWithParams(UrlUtil.getOrderServiceUrl(),"/api/print/searchCount",map);
                        Map codDataMap = JsonUtil.transferToObj(codStr,Map.class);
                        List codDataList = (List) codDataMap.get("data");
                        Map codData = (Map) codDataList.get(0);
                        String codRemainNum = codData.get("remain_num").toString();
                        vo.setCommonRemainNum(commonRemainNum);
                        vo.setCodRemainNum(codRemainNum);
                    }else{
                        // 赋值0
                        vo.setCommonRemainNum("异常");
                        vo.setCodRemainNum("异常");
                    }
                }else if (vo.getType().equals("ZTO")){
                    map.put("expressDeliveryType","ZTO");
                    map.put("account",vo.getPartnerId());
                    map.put("password",vo.getSecret());
                    String codStr = InterfaceUtils.getInterfaceGetWithParams(UrlUtil.getOrderServiceUrl(),"/api/print/faceSheetBalance",map);
                    Map codDataMap = JsonUtil.transferToObj(codStr,Map.class);
                    if (codDataMap.get("message").toString().equals("操作成功")){
                        vo.setRemark(JsonUtil.transferToJson(codDataMap.get("result")));
                    }
                    System.out.println(codDataMap);
                }else if (vo.getType().equals("JTSD")){
                    // 极兔快递获取余额
                    map.put("customerCode",vo.getPartnerId());
                    map.put("password",vo.getSecret());
                    String commonStr = InterfaceUtils.getInterfaceGetWithParams(UrlUtil.getOrderServiceUrl(),"/api/jtPrint/jtEssBalance",map);
                    Map commonDataMap = JsonUtil.transferToObj(commonStr,Map.class);
                    if (commonDataMap.get("msg").equals("success")){
                        Map data = (Map) commonDataMap.get("data");
                        vo.setRemark(data.get("balance").toString());
                    }
                }
            }
        }

        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的快递打单账号管理列表
     *
     * @param bo 查询条件
     * @return 快递打单账号管理列表
     */
    @Override
    public List<FastMailVo> queryList(FastMailBo bo) {
        // 获取当前用户id
        Long userId = LoginHelper.getUserId();
        // 获取白名单
        if (userId != 1) {
            bo.setCreateBy(userId);
        }
        LambdaQueryWrapper<FastMail> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    @Override
    public List<FastMailVo> queryListApi(Long userId){
        FastMailBo bo = new FastMailBo();
        bo.setCreateBy(userId);
        LambdaQueryWrapper<FastMail> lqw = buildQueryWrapper(bo);
        List<FastMailVo> fastMailVoList = baseMapper.selectVoList(lqw);
        for (FastMailVo vo : fastMailVoList){
            Map map = new HashMap();
            map.put("partnerId",vo.getPartnerId());
            map.put("secret",vo.getSecret());
            map.put("type","common");
            String commonStr = InterfaceUtils.getInterfaceGetWithParams(UrlUtil.getOrderServiceUrl(),"/api/print/searchCount",map);
            Map commonDataMap = JsonUtil.transferToObj(commonStr,Map.class);
            if (commonDataMap.get("code").equals("200") && !commonDataMap.get("data").toString().contains("ERROR")){
                List commonDataList = (List) commonDataMap.get("data");
                Map commonData = (Map) commonDataList.get(0);
                String commonRemainNum = commonData.get("remain_num").toString();
                map.put("type","cod");
                String codStr = InterfaceUtils.getInterfaceGetWithParams(UrlUtil.getOrderServiceUrl(),"/api/print/searchCount",map);
                Map codDataMap = JsonUtil.transferToObj(codStr,Map.class);
                List codDataList = (List) codDataMap.get("data");
                Map codData = (Map) codDataList.get(0);
                String codRemainNum = codData.get("remain_num").toString();
                vo.setCommonRemainNum(commonRemainNum);
                vo.setCodRemainNum(codRemainNum);
            }else{
                // 赋值0
                vo.setCommonRemainNum("异常");
                vo.setCodRemainNum("异常");
            }
        }
        return fastMailVoList;
    }

    private LambdaQueryWrapper<FastMail> buildQueryWrapper(FastMailBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<FastMail> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(FastMail::getId);
        lqw.eq(bo.getCreateBy() != null, FastMail::getCreateBy, bo.getCreateBy());
        lqw.eq(StringUtils.isNotBlank(bo.getType()), FastMail::getType, bo.getType());
        lqw.eq(StringUtils.isNotBlank(bo.getPartnerId()), FastMail::getPartnerId, bo.getPartnerId());
        lqw.eq(StringUtils.isNotBlank(bo.getSecret()), FastMail::getSecret, bo.getSecret());
        lqw.eq(StringUtils.isNotBlank(bo.getFastMailType()), FastMail::getFastMailType, bo.getFastMailType());
        lqw.eq(bo.getCreateTime() != null, FastMail::getCreateTime, bo.getCreateTime());
        lqw.eq(bo.getUpdateTime() != null, FastMail::getUpdateTime, bo.getUpdateTime());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), FastMail::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增快递打单账号管理
     *
     * @param bo 快递打单账号管理
     * @return 是否新增成功
     */
    @Override
    public R<Void> insertByBo(FastMailBo bo) {
        // 网点面单的情况进行校验
        if (bo.getFastMailType().equals("1")){
            FastMailVo fastMailVo = selectByUserIdAndType(LoginHelper.getUserId().toString(),bo.getType());
            if(fastMailVo != null){
                return R.fail("该用户已存在该类型的快递打单账号");
            }
            Map map = new HashMap();
            if(bo.getType().equals("YUNDA")){
                // 韵达
                map.put("partnerId",bo.getPartnerId());
                map.put("secret",bo.getSecret());
                map.put("type","common");
                String commonStr = InterfaceUtils.getInterfaceGetWithParams(UrlUtil.getOrderServiceUrl(),"/api/print/searchCount",map);
                Map commonDataMap = JsonUtil.transferToObj(commonStr,Map.class);
                if (commonDataMap.get("data").toString().contains("ERROR")){
                    return R.fail("账号或联调密码不正确");
                }
            }else if (bo.getType().equals("ZTO")){
                // 中通
                map.put("expressDeliveryType",bo.getType());
                map.put("account",bo.getPartnerId());
                map.put("password",bo.getSecret());
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("siteCode",bo.getRemark());
                map.put("json",jsonObject.toString());
                String commonStr =  InterfaceUtils.getInterfaceGetWithParams(UrlUtil.getOrderServiceUrl(),"/api/ztoPrint/bindingEaccount",map);
                Map commonDataMap = JsonUtil.transferToObj(commonStr,Map.class);
                if (!commonDataMap.get("message").toString().contains("已绑定") && !commonDataMap.get("message").toString().contains("已绑定成功")){
                    return R.fail(commonDataMap.get("message").toString());
                }else{
                    bo.setRemark(jsonObject.toString());
                }
            }else if (bo.getType().equals("JTSD")){
                // 极兔速递
                map.put("customerCode",bo.getPartnerId());
                map.put("password",bo.getSecret());
                String commonStr = InterfaceUtils.getInterfaceGetWithParams(UrlUtil.getOrderServiceUrl(),"/api/jtPrint/jtVipCheckCusPwd",map);
                Map commonDataMap = JsonUtil.transferToObj(commonStr,Map.class);
                if (!commonDataMap.get("msg").equals("success")){
                    return R.fail(commonDataMap.get("msg").toString());
                }
            }
        }

        FastMail add = MapstructUtils.convert(bo, FastMail.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return R.ok("新增成功");
    }

    /**
     * 修改快递打单账号管理
     *
     * @param bo 快递打单账号管理
     * @return 是否修改成功
     */
    @Override
    public R<Void> updateByBo(FastMailBo bo) {

        if (bo.getFastMailType().equals("1")){
            Map map = new HashMap();
            if(bo.getType().equals("YUNDA")){
                map.put("partnerId",bo.getPartnerId());
                map.put("secret",bo.getSecret());
                map.put("type","common");
                String commonStr = InterfaceUtils.getInterfaceGetWithParams(UrlUtil.getOrderServiceUrl(),"/api/print/searchCount",map);
                Map commonDataMap = JsonUtil.transferToObj(commonStr,Map.class);
                if (commonDataMap.get("data").toString().contains("ERROR")){
                    return R.fail("账号或联调密码不正确");
                }
            }else if (bo.getType().equals("ZTO")){
                // 中通
                map.put("expressDeliveryType",bo.getType());
                map.put("account",bo.getPartnerId());
                map.put("password",bo.getSecret());
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("siteCode",bo.getRemark());
                map.put("json",jsonObject.toString());
                String commonStr =  InterfaceUtils.getInterfaceGetWithParams(UrlUtil.getOrderServiceUrl(),"/api/ztoPrint/bindingEaccount",map);
                Map commonDataMap = JsonUtil.transferToObj(commonStr,Map.class);
                if (!commonDataMap.get("message").toString().contains("已绑定") && !commonDataMap.get("message").toString().contains("已绑定成功")){
                    return R.fail(commonDataMap.get("message").toString());
                }else{
                    bo.setRemark(jsonObject.toString());
                }
            }
        }
        FastMail update = MapstructUtils.convert(bo, FastMail.class);
        validEntityBeforeSave(update);
        if (baseMapper.updateById(update) > 0){
            return R.ok("修改成功");
        }else {
            return R.fail("修改失败");
        }
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(FastMail entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除快递打单账号管理信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 根据面单类型删除数据
     * @param fastMailType
     * @return
     */
    @Override
    public int deleteByFastMailType(Long userId,String fastMailType){
        return baseMapper.deleteByFastMailType(userId,fastMailType);
    }
}
