package com.yc.ship.module.trade.service.orderjzdetail;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.alibaba.excel.util.DateUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yc.ship.framework.common.pojo.PageResult;
import com.yc.ship.framework.common.util.object.BeanUtils;
import com.yc.ship.framework.security.core.LoginUser;
import com.yc.ship.framework.tenant.core.aop.TenantIgnore;
import com.yc.ship.module.trade.controller.admin.orderjzdetail.vo.OrderJzDetailPageReqVO;
import com.yc.ship.module.trade.controller.admin.orderjzdetail.vo.OrderJzDetailSaveReqVO;
import com.yc.ship.module.trade.dal.dataobject.order.TradeOrderDO;
import com.yc.ship.module.trade.dal.dataobject.orderjz.OrderJzDO;
import com.yc.ship.module.trade.dal.dataobject.orderjzdetail.OrderJzDetailDO;
import com.yc.ship.module.trade.dal.mysql.order.TradeOrderMapper;
import com.yc.ship.module.trade.dal.mysql.orderjz.OrderJzMapper;
import com.yc.ship.module.trade.dal.mysql.orderjzdetail.OrderJzDetailMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.yc.ship.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.yc.ship.framework.security.core.util.SecurityFrameworkUtils.getLoginUser;

/**
 * 订单接站人员名单 Service 实现类
 *
 * @author 管理员
 */
@Service
@Validated
@Slf4j
public class OrderJzDetailServiceImpl implements OrderJzDetailService {

    @Resource
    private TradeOrderMapper tradeOrderMapper;

    @Resource
    private OrderJzMapper orderJzMapper;

    @Resource
    private OrderJzDetailMapper orderJzDetailMapper;

    @Override
    public Long createOrderJzDetail(OrderJzDetailSaveReqVO createReqVO) {
        // 插入
        OrderJzDetailDO orderJzDetail = BeanUtils.toBean(createReqVO, OrderJzDetailDO.class);
        orderJzDetail.setTenantId(1L);
        orderJzDetail.setIdCard(createReqVO.getIdCard());
        orderJzDetailMapper.insert(orderJzDetail);
        // 返回
        return orderJzDetail.getId();
    }


    @Override
    @TenantIgnore
    public Long createOrderJzDetail(List<OrderJzDetailSaveReqVO> createReqVOList) {
        if (createReqVOList == null || createReqVOList.isEmpty()) {
            return 0L;
        }
        String oid = createReqVOList.get(0).getOid();
        if (oid == null || oid.isEmpty()) {
            throw new RuntimeException("未查询到相关订单");
        }
        TradeOrderDO orderDo = tradeOrderMapper.selectOne(new LambdaQueryWrapper<TradeOrderDO>().eq(TradeOrderDO::getId, oid));
        if (orderDo == null) {
            throw new RuntimeException("未查询到相关订单");
        }
        // 根据订单编号查询jz编号
        OrderJzDO orderJzDO = orderJzMapper.selectOne(new LambdaQueryWrapper<OrderJzDO>().eq(OrderJzDO::getOrderId, oid));
        if (orderJzDO == null) {
            orderJzDO = new OrderJzDO();
            orderJzDO.setId(IdUtil.getSnowflake(0, 0).nextId());
            orderJzDO.setIsJz(1);
            orderJzDO.setJzAddress("");
            orderJzDO.setJzLinkName("");
            orderJzDO.setJzLinkPhone("");
            orderJzDO.setOrderId(orderDo.getId());
            orderJzDO.setCreateTime(LocalDateTime.now());
            orderJzDO.setTenantId(orderDo.getTenantId());
            orderJzDO.setDeleted(false);
            orderJzMapper.insert(orderJzDO);
        }
        long count = 0;
        String batchNo = IdUtil.getSnowflake(0, 0).nextIdStr();
        // 先删除当前传入游客的历史接站数据
        for (OrderJzDetailSaveReqVO orderJzDetailSaveReqVO : createReqVOList) {
            orderJzDetailMapper.delete(new LambdaQueryWrapper<OrderJzDetailDO>().eq(OrderJzDetailDO::getVisitorId, orderJzDetailSaveReqVO.getVisitorId()));
        }
        //处理三方系统退票
        for (OrderJzDetailSaveReqVO orderJzDetailSaveReqVO : createReqVOList) {
            orderJzDetailSaveReqVO.setBatchNo(batchNo);
            orderJzDetailSaveReqVO.setJzId(orderJzDO.getId());
            createOrderJzDetail(orderJzDetailSaveReqVO);
            count++;
        }
        try {
            //处理三方系统出票 二期接站
            createSupplierJz(createReqVOList, orderDo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return count;
    }

    private void createSupplierJz(List<OrderJzDetailSaveReqVO> createReqVOList, TradeOrderDO tradeOrderDO) {
        Long id = null;
        String productId = "";
        String bookname = "";
        String mobile = "";
        String idcard = "";
        for (OrderJzDetailSaveReqVO orderJzDetailSaveReqVO : createReqVOList) {
            id = orderJzDetailSaveReqVO.getId();
            mobile = orderJzDetailSaveReqVO.getPhone();
            idcard = orderJzDetailSaveReqVO.getIdCard();
        }
        JSONObject rep_body = new JSONObject();
        rep_body.put("orderId", id);
        rep_body.put("travelDate", tradeOrderDO.getTravelDate());
        rep_body.put("travelTime", "");
        rep_body.put("quantity", createReqVOList.size());
        rep_body.put("productId", "productId");
        rep_body.put("bookName", bookname);
        rep_body.put("bookMobile", mobile);
        rep_body.put("idCard", idcard);

        JSONArray vistorList = new JSONArray();
        for (OrderJzDetailSaveReqVO tradeVisitorDO : createReqVOList) {
            JSONObject vistor = new JSONObject();
            vistor.put("name", tradeVisitorDO.getName());
            vistor.put("mobile", tradeVisitorDO.getPhone());
            vistor.put("idCard", tradeVisitorDO.getIdCard());
            vistor.put("face", "");
            vistorList.add(vistor);
        }
        rep_body.put("visitPersons", vistorList);
//    String bodyStr = DesUtil.encrypt(rep_body.toString(),userKey);
//    String signStr = userId+method+timestamp+bodyStr+userKey;
//    log.info("jfg供应商预下单开始,signStr:{}",signStr);
//    String sign = MD5Utils.getMD5(signStr.getBytes("UTF-8"));
//
//    JSONObject rep_head=new JSONObject();
//    rep_head.put("user_id", userId);
//    rep_head.put("method",method );
//    rep_head.put("timestamp", timestamp);
//    rep_head.put("sign", sign);
//
//    JSONObject req=new JSONObject();
//    req.put("requestHead", rep_head);
//    req.put("requestBody", bodyStr);
//    Map<String, String> headMap = new HashMap<>();
//    headMap.put("Content-type", "application/x-www-form-urlencoded");
//    log.info("jfg供应商预下单开始,请求地址:{},请求参数:{}",createOrderUrl,req.toString());
//    String res = HttpUtil.createPost(createOrderUrl).contentType("application/json")
//            .body(Base64Util.encode(req.toString()))
//            .headerMap(headMap,false)
//            .timeout(100000)
//            .execute().body();
//    log.info("jfg供应商预下单完成,响应参数:{}",res);
//    // base64解密
//    String json = new String(Base64.decodeBase64(res.getBytes("UTF-8")));
//    log.info("jfg供应商预下单完成,响应response参数:{}",json);
//    JSONObject jsonObj = JSONUtil.parseObj(json);
//    JSONObject responseHead = jsonObj.getJSONObject("responseHead");
//    if(StringUtils.equals("1000",responseHead.getStr("res_code"))){
//      String response = jsonObj.getStr("responseBody");
//      String body = "";
//      try {
//        body = DesUtil.decrypt(response, userKey);
//      } catch (Exception e) {
//        log.info(e.toString());
//      }
//      log.info("jfg供应商预下单完成,响应body参数:{}",body);
//      JSONObject responseBody =JSONUtil.parseObj(body);
//      return CommonResult.success(new SupplierTradeOrderRespBO().setSupplierOrderNo(responseBody.getStr("partnerOrderId")));
//    }else{
//      return CommonResult.error(500,responseHead.getStr("res_msg"));
//    }
    }


    @Override
    public void updateOrderJzDetail(OrderJzDetailSaveReqVO updateReqVO) {
        // 校验存在
        validateOrderJzDetailExists(updateReqVO.getId());
        // 更新
        OrderJzDetailDO updateObj = BeanUtils.toBean(updateReqVO, OrderJzDetailDO.class);
        orderJzDetailMapper.updateById(updateObj);
    }

    @Override
    public void deleteOrderJzDetail(Long id) {
        // 校验存在
        validateOrderJzDetailExists(id);
        // 删除
        orderJzDetailMapper.deleteById(id);
    }

    private void validateOrderJzDetailExists(Long id) {
        if (orderJzDetailMapper.selectById(id) == null) {
            throw exception(500, "不存在");
        }
    }

    @Override
    public OrderJzDetailDO getOrderJzDetail(Long id) {
        return orderJzDetailMapper.selectById(id);
    }

    @Override
    public PageResult<OrderJzDetailDO> getOrderJzDetailPage(OrderJzDetailPageReqVO pageReqVO) {
        return orderJzDetailMapper.selectPage(pageReqVO);
    }

    @Override
    public List<OrderJzDetailDO> selectPageByVoyageId(String voyageId) {
        return orderJzDetailMapper.selectPageByVoyageId(voyageId);
    }

    @Override
    public List<OrderJzDetailDO> getOrderJzDetailList(OrderJzDetailPageReqVO pageReqVO) {
        String oid = pageReqVO.getOid();
        // 根据订单编号查询jz编号
        OrderJzDO orderJzDO = orderJzMapper.selectOne(new LambdaQueryWrapper<OrderJzDO>().eq(OrderJzDO::getOrderId, oid));
        if (orderJzDO == null) {
            return new ArrayList<>();
        }
        pageReqVO.setJzId(orderJzDO.getId());
        return orderJzDetailMapper.selectList(pageReqVO);
    }

    @Override
    public Long cleanOrderJzDetail(String id) {
        return orderJzDetailMapper.cleanSign(id);
    }

    @Override
    public Long signOrderJzDetail(OrderJzDetailSaveReqVO createReqVO) {
        OrderJzDetailDO detail = getOrderJzDetail(createReqVO.getId());
        // 如果ID为空，则为补登游客，按订单来查询
        if (detail == null) {
            // 查询是否有接站头表
            List<OrderJzDO> orderJzDOList = orderJzMapper.selectList(new LambdaQueryWrapper<OrderJzDO>().eq(OrderJzDO::getOrderId, createReqVO.getOid()));
            OrderJzDO orderJzDO = null;
            if (orderJzDOList == null || orderJzDOList.size() == 0) { // 创建一条
                TradeOrderDO orderDo = tradeOrderMapper.selectById(createReqVO.getOid());
                if (orderDo == null) {
                    throw new RuntimeException("未查询到相关订单");
                }
                orderJzDO = new OrderJzDO();
                orderJzDO.setId(IdUtil.getSnowflake(0, 0).nextId());
                orderJzDO.setIsJz(1);
                orderJzDO.setJzAddress("");
                orderJzDO.setJzLinkName("");
                orderJzDO.setJzLinkPhone("");
                orderJzDO.setOrderId(Long.valueOf(createReqVO.getOid()));
                orderJzMapper.insert(orderJzDO);
            } else {
                orderJzDO = orderJzDOList.get(0);
            }
            detail = new OrderJzDetailDO();
            detail.setJzId(orderJzDO.getId());
            detail.setBatchNo(IdUtil.getSnowflake(0, 0).nextIdStr());
            detail.setArriveTime(createReqVO.getArriveTime());
            detail.setAddress(createReqVO.getAddress());
            detail.setName(createReqVO.getName());
            detail.setIdCard(createReqVO.getIdCard());
            detail.setPhone(createReqVO.getPhone());
            detail.setRemark("接站补登");
            detail.setStatus(1);
        }
        detail.setSignTime(DateUtils.format(new Date(), DatePattern.NORM_DATETIME_PATTERN));
        // 当前登录人
        LoginUser loginUser = getLoginUser();
        detail.setSignMan(MapUtils.getString(loginUser.getInfo(), LoginUser.INFO_KEY_NICKNAME));
        detail.setSignRemark(createReqVO.getSignRemark());
        detail.setSignImage(createReqVO.getSignImage());

        if (detail.getId() == null) {
            orderJzDetailMapper.insert(detail);
        } else {
            orderJzDetailMapper.updateById(detail);
        }
        return detail.getId();
    }

    @Override
    public PageResult<OrderJzDetailDO> getOrderJzDetailPage2(OrderJzDetailPageReqVO pageReqVO) {
        IPage<OrderJzDetailDO> page = new Page<>(pageReqVO.getPageNo(), pageReqVO.getPageSize());
        IPage<OrderJzDetailDO> iPage = orderJzDetailMapper.selectPage2(page, pageReqVO);
        return new PageResult<>(iPage.getRecords(), iPage.getTotal());
    }


    @Override
    public PageResult<?> getOrderJzDetailPage3(OrderJzDetailPageReqVO pageReqVO) {
        IPage<Map> page = new Page<>(pageReqVO.getPageNo(), pageReqVO.getPageSize());
        IPage<?> iPage = orderJzDetailMapper.selectPage3(page, pageReqVO);
        return new PageResult<>(iPage.getRecords(), iPage.getTotal());
    }

    @Override
    public List<OrderJzDetailDO> getVisitorExportList(OrderJzDetailPageReqVO pageReqVO) {
        return orderJzDetailMapper.selectVisitorExportList(pageReqVO);
    }

    // ==================== 赠送行程接站相关 ====================

    @Override
    public PageResult<OrderJzDetailDO> getGiftPage(OrderJzDetailPageReqVO pageReqVO) {
        IPage<OrderJzDetailDO> page = new Page<>(pageReqVO.getPageNo(), pageReqVO.getPageSize());
        IPage<OrderJzDetailDO> iPage = orderJzDetailMapper.selectGiftPage(page, pageReqVO);
        return new PageResult<>(iPage.getRecords(), iPage.getTotal());
    }

    @Override
    public List<OrderJzDetailDO> getGiftExportList(OrderJzDetailPageReqVO pageReqVO) {
        return orderJzDetailMapper.selectGiftExportList(pageReqVO);
    }

    @Override
    public PageResult<?> getGiftOrderPage(OrderJzDetailPageReqVO pageReqVO) {
        IPage<Map> page = new Page<>(pageReqVO.getPageNo(), pageReqVO.getPageSize());
        IPage<?> iPage = orderJzDetailMapper.selectGiftOrderPage(page, pageReqVO);
        return new PageResult<>(iPage.getRecords(), iPage.getTotal());
    }


}