package com.org.hktshop.service.order.impl;

import com.org.hktshop.base.BaseService;
import com.org.hktshop.dto.HktInvoiceSearchDto;
import com.org.hktshop.dto.PageQueryDto;
import com.org.hktshop.entity.Page;
import com.org.hktshop.entity.order.HktOrder;
import com.org.hktshop.entity.order.HktOrderGoods;
import com.org.hktshop.entity.order.HktOrderInvoice;
import com.org.hktshop.entity.user.HktUsersInvoice;
import com.org.hktshop.service.order.HktOrderGoodsService;
import com.org.hktshop.service.order.HktOrderInvoiceService;
import com.org.hktshop.service.order.HktOrderService;
import com.org.hktshop.service.user.HktUsersInvoiceService;
import com.org.hktshop.utils.ExecSqlLib;
import com.org.hktshop.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class HktOrderInvoiceServiceImpl extends BaseService<HktOrderInvoice> implements HktOrderInvoiceService {
    @Autowired
    private HktOrderService orderService;
    @Autowired
    private HktUsersInvoiceService usersInvoiceService;
    @Autowired
    private HktOrderGoodsService orderGoodsService;

    @Override
    public HktOrderInvoice getHktOrderInvoice(String orderId) {
        HktOrderInvoice orderInvoice = new HktOrderInvoice();
        orderInvoice.setId(orderId);
        String sql = ExecSqlLib.GetQuerySql(orderInvoice);
        HktOrderInvoice hktOrderInvoice = this.baseJdbcDao.query(sql, orderInvoice);
        List<HktOrderGoods> hktOrderGoodsList = orderGoodsService.getHktOrderGoodsList(hktOrderInvoice.getOrderSn());
        hktOrderInvoice.setHktOrderGoods(hktOrderGoodsList);
        HktOrder hktOrder = orderService.getHktOrderById(hktOrderInvoice.getOrderSn());
        hktOrderInvoice.setTotalAmount(hktOrder.getTotalAmount());
        return hktOrderInvoice;
    }

    @Override
    public void batchUpdate(String ids, HktOrderInvoice orderInvoice) {
        String[] split = ids.split(",");
        orderInvoice.setId(split[0]);
        String sql = ExecSqlLib.GetUpdateSql(orderInvoice).replace("where id = '" + split[0] + "'", "") +
                String.format(" WHERE id in (%s)", ids);
        this.baseJdbcDao.execute(sql);
    }

    @Override
    public Page<HktOrderInvoice> getOrderInvoiceBySearch(PageQueryDto<HktInvoiceSearchDto> pageQueryDto) {
        HktInvoiceSearchDto data = pageQueryDto.getData();
        StringBuilder sql = new StringBuilder();
        HktOrderInvoice orderInvoice = new HktOrderInvoice();
        String hoi = "SELECT hoi.id,hoi.order_id as orderId,hoi.order_sn as orderSn,category,hoi.type,hoi.open_type as openType,hoi.open_obj as openObj,hoi.title,hoi.open_taxpayer as openTaxpayer,\n" +
                "hoi.operating_address as operatingAddress,hoi.open_bank_address as openBankAddress,hoi.open_bank_account as openBankAccount,hoi.invoice_url as invoiceUrl,\n" +
                "hoi.collect_name as collectName,hoi.collect_email as collectEmail,hoi.collect_mobile as collectMobile,hoi.collect_address as collectAddress,hoi.status,hoi.invoice_time as invoiceTime,\n" +
                "hoi.create_time as createTime,hoi.modify_time as modifyTime from hkt_order_invoice hoi\n" +
                "LEFT JOIN hkt_order ho ON hoi.order_sn = ho.order_sn where ho.order_status = 1";
//        sql.append(ExecSqlLib.GetQuerySql(orderInvoice).replace("order by id"," where 1=1"));
        sql.append(hoi);
        if(!StringUtils.isNull(data.getType().trim())){
            sql.append(" and hoi.type="+data.getType());
        }
        if(!StringUtils.isNull(data.getStatus().trim())){
            sql.append(" and hoi.status = "+data.getStatus().trim());
        }

        if (!StringUtils.isNull(data.getSearch())) {
            sql.append(" and hoi.order_sn like'%").append(data.getSearch()).append("%' OR hoi.open_taxpayer='%").append(data.getSearch()).append("%' OR hoi.collect_mobile='%").append(data.getSearch()).append("%'");
        }
        sql.append(" order by hoi.create_time DESC");
        return assembleData(orderInvoice, pageQueryDto.getPageSize(), pageQueryDto.getPageNum(), sql.toString());
    }

    @Override
    public HktOrderInvoice getHktOrderInvoiceByOrderId(String orderId) {
        HktOrder hktOrder = new HktOrder();
        hktOrder.setId(orderId);
        HktOrder hktOrder1 = orderService.getHktOrder(hktOrder);
        HktOrderInvoice orderInvoice = new HktOrderInvoice();
        orderInvoice.setOrderSn(hktOrder1.getOrderSn());
        String sql = ExecSqlLib.GetQuerySql(orderInvoice);
        HktOrderInvoice hktOrderInvoice = this.baseJdbcDao.query(sql, orderInvoice);
        if(hktOrderInvoice == null){
            return null;
        }
        List<HktOrderGoods> hktOrderGoodsList = orderGoodsService.getHktOrderGoodsList(hktOrderInvoice.getOrderSn());
        hktOrderInvoice.setHktOrderGoods(hktOrderGoodsList);
//        HktOrder hktOrder = orderService.getHktOrderById(hktOrderInvoice.getOrderSn());
        hktOrderInvoice.setTotalAmount(hktOrder1.getTotalAmount());
        return hktOrderInvoice;
    }

    @Override
    public void addInvoice(HktOrderInvoice orderInvoice) {
        String sql = ExecSqlLib.GetInsertSql(orderInvoice);
        this.baseJdbcDao.execute(sql);
    }

    @Override
    public Page<HktOrderInvoice> selectOrderInvoice(HktOrderInvoice hktOrderInvoice) {
        String sql = ExecSqlLib.GetQuerySql(hktOrderInvoice).replace("order by id","");
        StringBuilder sb = new StringBuilder(sql);
        if (!StringUtils.isNull(hktOrderInvoice.getSearch())) {
            if(!sb.toString().contains("where")){
                sb.append(" where 1=1 ");
            }
            sb.append(" and order_sn like '%").append(hktOrderInvoice.getSearch()).append("%' OR open_taxpayer like '%").append(hktOrderInvoice.getSearch()).append("%' OR collect_mobile like '%").append(hktOrderInvoice.getSearch()).append("%'");
        }
        Page<HktOrderInvoice> page = this.baseJdbcDao.queryPage(sb.toString(), hktOrderInvoice);
        List<HktOrderInvoice> records = page.getRecords();
        for(HktOrderInvoice ho : records){
            HktOrder hktOrderById = orderService.getHktOrderById(ho.getOrderSn());
            ho.setTotalAmount(hktOrderById.getTotalAmount());
        }
        return  page;
    }


    /**
     * 组装分页数据
     *
     * @param orderInvoice
     * @param pageSize
     * @param pageNum
     * @param sql
     * @return
     */
    private Page<HktOrderInvoice> assembleData(HktOrderInvoice orderInvoice, Integer pageSize, Integer pageNum, String sql) {
        orderInvoice.setPageNum(pageNum);
        orderInvoice.setPageSize(pageSize);
        Page<HktOrderInvoice> hktOrderInvoicePage = this.baseJdbcDao.queryPage(sql, orderInvoice);
        List<HktOrderInvoice> records = hktOrderInvoicePage.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            return hktOrderInvoicePage;
        }
        List<String> orderIdList = records.stream().map(HktOrderInvoice::getOrderSn).collect(Collectors.toList());
        String orderIds = String.join(",", orderIdList);
        List<HktOrder> hktOrderInvoices = orderService.getHktOrderByOrderIds(orderIds);
        Map<String, List<HktOrder>> orderIdsMap = hktOrderInvoices.stream().collect(Collectors.groupingBy(HktOrder::getOrderSn));
        Set<String> userid = hktOrderInvoices.stream().map(HktOrder::getUserId).collect(Collectors.toSet());
        String urserids = String.join(",", userid);
        List<HktUsersInvoice> usersInvoiceList = usersInvoiceService.getHktUsersInvoicesByUserIds(urserids);
        Map<String, List<HktUsersInvoice>> userIdsMap = usersInvoiceList.stream()
                .collect(Collectors.groupingBy(HktUsersInvoice::getUserId));
        for (HktOrderInvoice hktOrderInvoice : records) {
            if (orderIdsMap.containsKey(hktOrderInvoice.getOrderSn())) {
                HktOrder hktOrder = orderIdsMap.get(hktOrderInvoice.getOrderSn()).get(0);
                hktOrderInvoice.setOrderAmount(hktOrder.getTotalAmount());
                if (!CollectionUtils.isEmpty(userIdsMap.get(hktOrder.getUserId()))) {
                    HktUsersInvoice usersInvoice = userIdsMap.get(hktOrder.getUserId()).get(0);
                    hktOrderInvoice.setOpenName(usersInvoice.getOpenName());
                }
            }
        }
        return hktOrderInvoicePage;
    }
}
