package com.ruoyi.reportManagement.service.impl;


import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.github.pagehelper.PageHelper;
import com.ruoyi.basicData.domain.TCustomerContact;
import com.ruoyi.basicData.mapper.TCustomerContactMapper;
import com.ruoyi.basicData.mapper.TWarehouseMapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.entity.TWarehouse;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.exception.WarehouseException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.sql.SqlUtil;
import com.ruoyi.reportManagement.domain.SingleAnalysisExcel;
import com.ruoyi.reportManagement.domain.SingleAnalysisFeesExcel;
import com.ruoyi.reportManagement.domain.TWhgenleg;
import com.ruoyi.reportManagement.domain.vo.WhgenlegVO;
import com.ruoyi.reportManagement.dto.TWarehousebill;
import com.ruoyi.reportManagement.excel.Whgenleg;
import com.ruoyi.reportManagement.mapper.TWhgenlegMapper;
import com.ruoyi.reportManagement.service.ITWhgenlegService;
import com.ruoyi.warehouseBusiness.domain.TWarehouseBills;
import com.ruoyi.warehouseBusiness.domain.enums.WarehouseTypeEnum;
import com.ruoyi.warehouseBusiness.mapper.TWarehouseBillsMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 库存总账Service业务层处理
 *
 * @author ruoyi
 * @date 2020-12-11
 */
@Service
public class TWhgenlegServiceImpl implements ITWhgenlegService {
    @Autowired
    private TWhgenlegMapper tWhgenlegMapper;

    @Autowired
    private TWarehouseBillsMapper tWarehouseBillsMapper;

    @Autowired
    private TWarehouseMapper tWarehouseMapper;
    @Autowired
    private TCustomerContactMapper customerContactMapper;

    /**
     * 查询库存总账
     *
     * @param fId 库存总账ID
     * @return 库存总账
     */
    @Override
    public Map<String, Object> selectTWhgenlegById(Long fId) {
        Map<String, Object> map = new HashMap<>();
        TWhgenleg whgenleg = tWhgenlegMapper.selectTWhgenlegById(fId);
        map.put("whgenleg", whgenleg);
        TWarehouseBills warehouseBills = new TWarehouseBills();
        warehouseBills.setfCorpid(whgenleg.getfCorpid());
        warehouseBills.setfMblno(whgenleg.getfMblno());
        warehouseBills.setfTrademodeid(whgenleg.getfTrademodeid());
        map.put("warehouseList", tWarehouseBillsMapper.selectTWarehousebillsList(warehouseBills));
        return map;
    }

    /**
     * 查询库存总账列表
     *
     * @param tWhgenleg 库存总账
     * @return 库存总账
     */
    @Override
    public List<TWhgenleg> selectTWhgenlegList(TWhgenleg tWhgenleg) {
        return tWhgenlegMapper.selectTWhgenlegList(tWhgenleg);
    }

    /**
     * 出库、调拨、货转查询库存总账列表
     *
     * @param tWhgenleg 库存总账
     *                  * @return 库存总账集合
     */
    @Override
    public List<Map<String, Object>> selectInventoryList(TWhgenleg tWhgenleg) {
        if (StringUtils.isNotNull(tWhgenleg.getfWarehouseLocationid())) {
            // 获取仓库信息
            TWarehouse tWarehouse = tWarehouseMapper.selectTWarehouseById(tWhgenleg.getfWarehouseLocationid());
            if (tWarehouse.getfLocation() == 1) {
                tWhgenleg.setfLocation(1L);
            } else {
                tWhgenleg.setfLocation(0L);
            }
        }
        return tWhgenlegMapper.selectInventoryList(tWhgenleg);
    }

    /**
     * 查询库存总账列表
     *
     * @param tWhgenleg 库存总账
     * @return 库存总账集合
     */
    @Override
    public AjaxResult selectWhgenlegDetailsList(TWhgenleg tWhgenleg) {
        if (StringUtils.isNotNull(tWhgenleg.getfWarehouseLocationid())) {
            // 获取仓库信息
            TWarehouse tWarehouse = tWarehouseMapper.selectTWarehouseById(tWhgenleg.getfWarehouseLocationid());
            if (tWarehouse.getfLocation() == 1) {
                tWhgenleg.setfLocation(1L);
            } else {
                tWhgenleg.setfLocation(0L);
            }
        }
        List<WhgenlegVO> voList = new ArrayList<>();
        // 查询入库、出库明细
        List<WhgenlegVO> stockVOList = tWhgenlegMapper.selectStockDetailsList(tWhgenleg);
        if (CollectionUtils.isNotEmpty(stockVOList)) {
            voList = stockVOList;
        }
        // 查询货转、调拨、通关数据
        List<WhgenlegVO> otherVOList = tWhgenlegMapper.selectOtherDetailsList(tWhgenleg);
        if (CollectionUtils.isNotEmpty(otherVOList)) {
            voList.addAll(otherVOList);
        }
        if (CollectionUtils.isNotEmpty(voList)) {
            List<WhgenlegVO> legVoList = new ArrayList<>();
            Map<Long, List<WhgenlegVO>> mapById = voList.stream().collect(Collectors.groupingBy(WhgenlegVO::getfId));
            mapById.forEach((key, value) -> {
                WhgenlegVO whgenlegVO = new WhgenlegVO();
                WhgenlegVO vo = value.stream().findFirst().orElseThrow(() -> new WarehouseException("缺少明细信息"));
                BeanUtils.copyProperties(vo, whgenlegVO);
                // 赋值字典表
                whgenlegVO.setTrademodeName(DictUtils.getDictLabel("data_trademodes", whgenlegVO.getfTrademodeid().toString()));
                // 数量
                whgenlegVO.setQty(value.stream().map(WhgenlegVO::getQty).reduce(BigDecimal::add).orElse(BigDecimal.ZERO));
                // 净重
                whgenlegVO.setNetweight(value.stream().map(WhgenlegVO::getNetweight).reduce(BigDecimal::add).orElse(BigDecimal.ZERO));
                // 毛重
                whgenlegVO.setGrossweight(value.stream().map(WhgenlegVO::getGrossweight).reduce(BigDecimal::add).orElse(BigDecimal.ZERO));
                // 业务类型
                WarehouseTypeEnum storageType = WarehouseTypeEnum.fromTypeAndBusinessType(whgenlegVO.getFBilltype(), "storageType");
                whgenlegVO.setFBilltype(storageType.getName());
                legVoList.add(whgenlegVO);
            });
            return AjaxResult.success(legVoList);
        }
        return AjaxResult.success(voList);
    }

    /**
     * app查询列表
     *
     * @param tWhgenleg 库存总账
     * @return 库存总账集合
     */
    @Override
    public List<Map<String, Object>> selectInventoryMapList(TWhgenleg tWhgenleg) {
        if (StringUtils.isNotNull(tWhgenleg.getfWarehouseLocationid())) {
            // 获取仓库信息
            TWarehouse tWarehouse = tWarehouseMapper.selectTWarehouseById(tWhgenleg.getfWarehouseLocationid());
            if (tWarehouse.getfLocation() == 1) {
                tWhgenleg.setfLocation(1L);
            } else {
                tWhgenleg.setfLocation(0L);
            }
        }
        return tWhgenlegMapper.selectInventoryMapList(tWhgenleg);
    }

    @Override
    public List<Map<String, Object>> selectWhgenlegList(TWhgenleg tWhgenleg) {
        if (StringUtils.isNotNull(tWhgenleg.getfWarehouseLocationid())) {
            // 获取仓库信息
            TWarehouse tWarehouse = tWarehouseMapper.selectTWarehouseById(tWhgenleg.getfWarehouseLocationid());
            if (tWarehouse.getfLocation() == 1) {
                tWhgenleg.setfLocation(1L);
            } else {
                tWhgenleg.setfLocation(0L);
            }
        }
        return tWhgenlegMapper.selectWhgenlegList(tWhgenleg);
    }

    /**
     * 新增库存总账
     *
     * @param tWhgenleg 库存总账
     * @return 结果
     */
    @Override
    public int insertTWhgenleg(TWhgenleg tWhgenleg) {
        tWhgenleg.setCreateTime(DateUtils.getNowDate());
        return tWhgenlegMapper.insertTWhgenleg(tWhgenleg);
    }

    /**
     * 修改库存总账
     *
     * @param tWhgenleg 库存总账
     * @return 结果
     */
    @Override
    public int updateTWhgenleg(TWhgenleg tWhgenleg) {
        tWhgenleg.setUpdateTime(DateUtils.getNowDate());
        return tWhgenlegMapper.updateTWhgenleg(tWhgenleg);
    }

    /**
     * 批量删除库存总账
     *
     * @param fAccyears 需要删除的库存总账ID
     * @return 结果
     */
    @Override
    public int deleteTWhgenlegByIds(Long[] fAccyears) {
        return tWhgenlegMapper.deleteTWhgenlegByIds(fAccyears);
    }

    /**
     * 删除库存总账信息
     *
     * @param fAccyear 库存总账ID
     * @return 结果
     */
    @Override
    public int deleteTWhgenlegById(Long fAccyear) {
        return tWhgenlegMapper.deleteTWhgenlegById(fAccyear);
    }


    @Override
    public Map<String, Object> selectGoodsList(Long fId) {
        Map<String, Object> map = new HashMap<>();
        // 查询仓库
        List<Map<String, Object>> whouseList;
        if (null != fId && fId != 0) {
            whouseList = tWhgenlegMapper.selectWareHouseListWhouse(fId);
        } else {
            whouseList = tWhgenlegMapper.selectWareHouseList();
        }
        if (null != whouseList && whouseList.size() > 0) {
            String fid = null; //获取 第一个 仓库ID
            for (Map<String, Object> m : whouseList) {
                String fGrossweightblc = null;
                for (String k : m.keySet()) {
                    if (k.equals("fWarehouseid")) {
                        fid = m.get(k).toString();
                    }
                    if (k.equals("fGrossweightD")) {
                        fGrossweightblc = m.get(k).toString();
                    }
                }
                m.put("fGrossweightD", calculation2(fGrossweightblc, "1000"));
                break;
            }
            //通过ID 查询仓库下 所有的 商品
            List<Map<String, Object>> goodslistWhouse = tWhgenlegMapper.selectGoodsListWhouse(Long.parseLong(fid));
            for (Map<String, Object> m : goodslistWhouse) {
                String fTotalgross = null;
                String fGrossweightblc = null;
                for (String k : m.keySet()) {
                    // 获取毛重库容
                    if (k.equals("fTotalgross")) {
                        fTotalgross = m.get(k).toString();
                    }
                    if (k.equals("fGrossweightD")) {
                        fGrossweightblc = m.get(k).toString();
                    }
                }
                m.put("balance", calculation1(fTotalgross, fGrossweightblc));
                m.put("fGrossweightD", calculation2(fGrossweightblc, "1000"));
            }
            map.put("goodslistWhouse", goodslistWhouse);
            // 查询仓库下 所有的 客户
            List<Map<String, Object>> corpsListWhouse = tWhgenlegMapper.selectCorpsListWhouse(Long.parseLong(fid));
            // 计算库容 总剩余
            for (Map<String, Object> m : corpsListWhouse) {
                String fTotalgross = null;
                String fGrossweightblc = null;
                for (String k : m.keySet()) {
                    // 获取毛重库容
                    if (k.equals("fTotalgross")) {
                        fTotalgross = m.get(k).toString();
                    }
                    if (k.equals("fGrossweightD")) {
                        fGrossweightblc = m.get(k).toString();
                    }
                }
                m.put("balance", calculation1(fTotalgross, fGrossweightblc));
                m.put("fGrossweightD", calculation2(fGrossweightblc, "1000"));
            }
            map.put("corpsListWhouse", corpsListWhouse);
        } else {
            // 仓库 库容
            TWarehouse tWarehouse = tWarehouseMapper.selectTWarehouseById(fId);
            Map<String, Object> maps = new HashMap<>();
            maps.put("fName", tWarehouse.getfName());
            maps.put("fWarehouseid", tWarehouse.getfId());
            maps.put("fTotalgross", tWarehouse.getfTotalgross());
            maps.put("fGrossweightD", "0");
            maps.put("percentage", "");
            whouseList.add(maps);
            map.put("goodslistWhouse", "");
            map.put("corpsListWhouse", "");
        }
        map.put("whouseList", whouseList);
        return map;
    }

    @Override
    public List<Map<String, Object>> selectWareHouseList() {
        List<Map<String, Object>> list = new ArrayList<>();
        list = tWhgenlegMapper.selectWareHouseList();
        if (list != null && list.size() > 0) {
            for (Map<String, Object> m : list) {
                String fTotalgross = null;
                String fGrossweightblc = null;
                for (String k : m.keySet()) {
                    // 获取毛重库容
                    if (k.equals("fTotalgross")) {
                        fTotalgross = m.get(k).toString();
                    }
                    if (k.equals("fGrossweightD")) {
                        fGrossweightblc = m.get(k).toString();
                    }
                }
                m.put("percentage", calculation(fGrossweightblc, fTotalgross));
                m.put("fGrossweightD", calculation2(fGrossweightblc, "1000"));
            }
        } else {
            List<TWarehouse> tWarehouses = tWarehouseMapper.selectTWarehouseList(new TWarehouse());
            for (TWarehouse tWarehouse : tWarehouses) {
                Map<String, Object> maps = new HashMap<>();
                maps.put("fName", tWarehouse.getfName());
                maps.put("fWarehouseid", tWarehouse.getfId());
                maps.put("fTotalgross", tWarehouse.getfTotalgross());
                maps.put("fGrossweightD", "0");
                maps.put("percentage", "");
                list.add(maps);
            }
        }
        return list;
    }

    @Override
    public List<Map<String, Object>> selectWareHouseLists() {
        List<Map<String, Object>> list = new ArrayList<>();
        List<TWarehouse> tWarehouses = tWarehouseMapper.selectTWarehouseLists(new TWarehouse());
        for (TWarehouse tWarehouse : tWarehouses) {
            Map<String, Object> maps = new HashMap<>();
            maps.put("fName", tWarehouse.getfName());
            maps.put("fWarehouseid", tWarehouse.getfId());
            maps.put("fTotalgross", tWarehouse.getfTotalgross());
            maps.put("fGrossweightD", "0");
            maps.put("percentage", "");
            list.add(maps);
        }
        return list;
    }

    @Override
    public Map<String, Object> selectCorpsList(Long fId) {
        Map<String, Object> map = new HashMap<>();
        // 查询所有 客户
        List<Map<String, Object>> corpsList = tWhgenlegMapper.selectCorpsList();
        map.put("corpsList", corpsList);
        if (corpsList != null) {
            Long fid = null;
            for (Map<String, Object> m : corpsList) {
                for (String k : m.keySet()) {
                    if (k.equals("fCorpid")) {
                        fid = (Long) m.get(k);
                    }
                    break;
                }
            }
            List<Map<String, Object>> corpsListWhouse;
            if (null != fId) {
                corpsListWhouse = tWhgenlegMapper.selectCorpsListWhouse(fId);
            } else {
                corpsListWhouse = tWhgenlegMapper.selectCorpsListWhouse(fid);
            }
            for (Map<String, Object> m : corpsListWhouse) {
                String fTotalgross = null;
                String fGrossweightblc = null;
                for (String k : m.keySet()) {
                    // 获取毛重库容
                    if (k.equals("fTotalgross")) {
                        fTotalgross = m.get(k).toString();
                    }
                    if (k.equals("fGrossweightD")) {
                        fGrossweightblc = m.get(k).toString();
                    }
                }
                m.put("percentage", calculation(fGrossweightblc, fTotalgross));
            }
            map.put("corpsListWhouse", corpsListWhouse);
        }
        return map;
    }

    @Override
    public List<Map<String, Object>> selectDateFQtyblcListList() {
        // 当天往前推 一周
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd ");
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DATE, -8);
        String frontday = format.format(c.getTime());
        // 当前日期
        String nowadays = DateUtils.getDate();
        Map<String, Object> map = new HashMap<>();
        map.put("frontday", frontday);
        map.put("nowadays", nowadays);

        List<Map<String, Object>> list = tWhgenlegMapper.selectDateFQtyblcListList(map);
        // 对比 日期 为空入库赋值0
        ArrayList<String> pastDaysList = dayList(8);
        for (String day : pastDaysList) {
            if (!day.equals(nowadays)) {
                Map<String, Object> map1 = new HashMap<String, Object>();
                map1.put("fOriginalbilldate", day);
                map1.put("fQtyblc", 0);
                list.add(map1);
            }
        }
        List<Map<String, Object>> countList = combineMap("fOriginalbilldate", list);
        return countList;
    }

    @Override
    public List<Whgenleg> whgenlegExport(TWhgenleg tWhgenleg) throws Exception {
        if (StringUtils.isNotNull(tWhgenleg.getfWarehouseLocationid())) {
            // 获取仓库信息
            TWarehouse tWarehouse = tWarehouseMapper.selectTWarehouseById(tWhgenleg.getfWarehouseLocationid());
            if (tWarehouse.getfLocation() == 1) {
                tWhgenleg.setfLocation(1L);
            } else {
                tWhgenleg.setfLocation(0L);
            }
        }
        List<Whgenleg> list = tWhgenlegMapper.selectWhgenlegMessage(tWhgenleg);
        //List<Whgenleg> list1 = ListMapToBeanUtils.castMapToBean(list,Whgenleg.class);
        return list;
    }

    @Override
    public List<Map<String, Object>> selectdetailedList(TWarehousebill tWarehousebill) {
        List<Map<String, Object>> mapList = tWarehouseBillsMapper.selectDetailedList(tWarehousebill);
        System.out.println(mapList);
        return mapList;
    }

    /**
     * 查询单票分析信息
     *
     * @param singleAnalysisExcel 查询条件
     * @return 结果
     */
    @Override
    public List<SingleAnalysisExcel> selectSingleAnalysis(SingleAnalysisExcel singleAnalysisExcel) {
        return tWarehouseBillsMapper.selectSingleAnalysis(singleAnalysisExcel);
    }

    /**
     * 查询单票分析费用信息
     *
     * @param singleAnalysisExcel
     * @return
     */
    @Override
    public List<SingleAnalysisFeesExcel> selectSingleAnalysisFees(SingleAnalysisExcel singleAnalysisExcel) {
        return tWarehouseBillsMapper.selectSingleAnalysisFees(singleAnalysisExcel);
    }

    @Override
    public List<Map<String, Object>> getWarehouse(TWhgenleg tWhgenleg) {
        return tWhgenlegMapper.getWarehouse(tWhgenleg);
    }

    @Override
    public List<Map<String, Object>> appWhGenLegList(TWhgenleg tWhgenleg, Integer pageNum, Integer pageSize) {
        TCustomerContact customerContact = new TCustomerContact();
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if ("外部用户".equals(user.getDept().getDeptName())) {
            customerContact.setfTel(SecurityUtils.getLoginUser().getUser().getUserName());
            List<TCustomerContact> tCustomerContacts = customerContactMapper.selectTCustomerContactList(customerContact);
            if (CollectionUtils.isNotEmpty(tCustomerContacts)) {
                tWhgenleg.setfCorpid(tCustomerContacts.get(0).getfPid());
            }
        }
        if (StringUtils.isNotNull(tWhgenleg.getfWarehouseLocationid())) {
            // 获取仓库信息
            TWarehouse tWarehouse = tWarehouseMapper.selectTWarehouseById(tWhgenleg.getfWarehouseLocationid());
            if (tWarehouse.getfLocation() == 1) {
                tWhgenleg.setfLocation(1L);
            } else {
                tWhgenleg.setfLocation(0L);
            }
        }

        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            PageHelper.startPage(pageNum, pageSize);
        }
        return tWhgenlegMapper.selectInventoryMapList(tWhgenleg);
    }

    /**
     * @param fOriginalbilldate 根据该字段进行合并
     * @param dataList          原始数据
     * @return
     */
    public static List<Map<String, Object>> combineMap(String fOriginalbilldate, List<Map<String, Object>> dataList) {
        //用于存放最后的结果
        List<Map<String, Object>> countList = new ArrayList<Map<String, Object>>();
        for (int i = 0; i < dataList.size(); i++) {
            String oldCombineField = String.valueOf(dataList.get(i).get(fOriginalbilldate));

            int flag = 0;//0为新增数据，1为增加count
            for (int j = 0; j < countList.size(); j++) {
                String newCombineField = String.valueOf(countList.get(j).get(fOriginalbilldate));
                if (oldCombineField.equals(newCombineField)) {
                    //做累加的操作
                    Integer afterSaleProfit = Integer.parseInt(String.valueOf(dataList.get(i).get("fQtyblc"))) + Integer.parseInt(String.valueOf(countList.get(j).get("fQtyblc")));
                    countList.get(j).put("fQtyblc", afterSaleProfit);
                    flag = 1;
                    break;
                }
            }
            if (flag == 0) {
                countList.add(dataList.get(i));
            }
        }
        return countList;
    }


    /**
     * 获取过去 任意天内的日期数组
     *
     * @param intervals intervals天内
     * @return 日期数组
     */
    public static ArrayList<String> dayList(int intervals) {
        ArrayList<String> pastDaysList = new ArrayList<>();
        for (int i = 0; i < intervals; i++) {
            pastDaysList.add(getPastDate(i));
        }
        return pastDaysList;
    }

    /**
     * 获取过去第几天的日期
     *
     * @param past
     * @return
     */
    public static String getPastDate(int past) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - past);
        Date today = calendar.getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String result = format.format(today);
        return result;
    }

    /**
     * 返回百分比
     *
     * @param fTotalgross
     * @param fGrossweightblc
     * @return
     */
    public static String calculation(String fTotalgross, String fGrossweightblc) {
        BigDecimal num1 = new BigDecimal(fTotalgross);
        BigDecimal num2 = new BigDecimal(fGrossweightblc);
        BigDecimal result = num1.divide(num2, 2, BigDecimal.ROUND_HALF_UP);
        int i = new Double(result.doubleValue() * 100).intValue();
        String str = i + "%";
        return str;
    }

    /**
     * 结余数/1000
     *
     * @param fTotalgross
     * @param fGrossweightblc
     * @return
     */
    public static String calculation2(String fTotalgross, String fGrossweightblc) {
        BigDecimal num1 = new BigDecimal(fTotalgross);
        BigDecimal num2 = new BigDecimal(fGrossweightblc);
        BigDecimal result = num1.divide(num2, 2, BigDecimal.ROUND_HALF_UP);
        return result.toString();
    }

    /**
     * 库容-结余毛重
     *
     * @param fTotalgross
     * @param fGrossweightblc
     * @return
     */
    public static BigDecimal calculation1(String fTotalgross, String fGrossweightblc) {
        BigDecimal num1 = new BigDecimal(fTotalgross);
        BigDecimal num2 = new BigDecimal(fGrossweightblc);
        BigDecimal result = num1.subtract(num2);
        return result.setScale(2, BigDecimal.ROUND_HALF_UP);
    }


}
