/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.dmExpenseCalendar.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.modules.dmExpenseCalendar.domain.DmExpenseCalendar;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.utils.*;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.dmExpenseCalendar.repository.DmExpenseCalendarRepository;
import me.zhengjie.modules.dmExpenseCalendar.service.DmExpenseCalendarService;
import me.zhengjie.modules.dmExpenseCalendar.service.dto.DmExpenseCalendarDto;
import me.zhengjie.modules.dmExpenseCalendar.service.dto.DmExpenseCalendarQueryCriteria;
import me.zhengjie.modules.dmExpenseCalendar.service.mapstruct.DmExpenseCalendarMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.util.ObjectUtils;

import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author zhirong
* @date 2021-11-23
**/
@Slf4j
@Service
@RequiredArgsConstructor
public class DmExpenseCalendarServiceImpl implements DmExpenseCalendarService {

    private final DmExpenseCalendarRepository dmExpenseCalendarRepository;
    private final DmExpenseCalendarMapper dmExpenseCalendarMapper;
    private final UserService userService;

    @Override
    public Map<String,Object> queryAll(DmExpenseCalendarQueryCriteria criteria, Pageable pageable){
        Page<DmExpenseCalendar> page = dmExpenseCalendarRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(dmExpenseCalendarMapper::toDto));
    }

    @Override
    public List<DmExpenseCalendarDto> queryAll(DmExpenseCalendarQueryCriteria criteria){
        return dmExpenseCalendarMapper.toDto(dmExpenseCalendarRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public DmExpenseCalendarDto findById(Long id) {
        DmExpenseCalendar dmExpenseCalendar = dmExpenseCalendarRepository.findById(id).orElseGet(DmExpenseCalendar::new);
        ValidationUtil.isNull(dmExpenseCalendar.getId(),"DmExpenseCalendar","id",id);
        return dmExpenseCalendarMapper.toDto(dmExpenseCalendar);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DmExpenseCalendarDto create(DmExpenseCalendar resources) {
        return dmExpenseCalendarMapper.toDto(dmExpenseCalendarRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(DmExpenseCalendar resources) {
        DmExpenseCalendar dmExpenseCalendar = dmExpenseCalendarRepository.findById(resources.getId()).orElseGet(DmExpenseCalendar::new);
        ValidationUtil.isNull( dmExpenseCalendar.getId(),"DmExpenseCalendar","id",resources.getId());
        dmExpenseCalendar.copy(resources);
        dmExpenseCalendarRepository.save(dmExpenseCalendar);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            dmExpenseCalendarRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<DmExpenseCalendarDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (DmExpenseCalendarDto dmExpenseCalendar : all) {
            Map<String,Object> map = new LinkedHashMap<>();
//            map.put("用户", dmExpenseCalendar.getUserNumber());
            map.put("持卡人姓名", dmExpenseCalendar.getUserName());
            map.put("持卡人电话", dmExpenseCalendar.getUserPhone());
            map.put("一卡通卡号", dmExpenseCalendar.getCardNumber());
            map.put("消费金额", dmExpenseCalendar.getRechargeAmount());
            map.put("消费后金额", dmExpenseCalendar.getAmountAfterRecharge());
            map.put("消费时间", dmExpenseCalendar.getRechargeTime());
            map.put("消费内容", dmExpenseCalendar.getContent());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public Map<String, Object> homePageYktExpense() {
        Map<String, Object> map = new HashMap<>();
        map.put("getSumExpense",dmExpenseCalendarRepository.getSumExpense());
        map.put("getSumAmOut",dmExpenseCalendarRepository.getSumAmOut());
        map.put("getContentCt",dmExpenseCalendarRepository.getContentCt());
        map.put("getContentQt",dmExpenseCalendarRepository.getContentQt());
        map.put("getPatternRl",dmExpenseCalendarRepository.getPatternRl());
        map.put("getPatternCt",dmExpenseCalendarRepository.getPatternCt());
        map.put("getPatternQt",dmExpenseCalendarRepository.getPatternQt());
        return map;
    }

    @Override
    public List<DmExpenseCalendar> findBySeq(String seq) {
        return dmExpenseCalendarRepository.findBySeq(seq);
    }

    @Override
    public void vehicleExpenseRecord(JSONObject json){
        String seq = json.getString("seq");
        List<DmExpenseCalendar> dmExpenseCalendar = findBySeq(seq);
        if(ObjectUtils.isEmpty(dmExpenseCalendar)) {
            //组装返回数据
            JSONObject acc = new JSONObject();
            acc.put("seq", seq);
            acc.put("userName", json.getString("userName"));
            acc.put("userPhone", json.getString("userPhone"));
            acc.put("cardNumber", json.getString("cardNo"));
            acc.put("rechargeAmount", json.getString("amt"));
            acc.put("amountAfterRecharge", json.getString("balance"));
            acc.put("rechargeTime", json.getString("createTime"));
            if (json.getString("shop") != null) {
                acc.put("content", "餐厅");
            } else {
                acc.put("content", "其他");
            }
            if (json.getString("card_no") != null) {
                acc.put("patternPayment", "园区卡");
            } else {
                acc.put("patternPayment", "其他");
            }
            DmExpenseCalendarDto dmExpenseCalendarDto = create(JSON.toJavaObject(acc, DmExpenseCalendar.class));
            String sendContent = "消费："+dmExpenseCalendarDto.getRechargeAmount()+"元 消费后金额："+dmExpenseCalendarDto.getAmountAfterRecharge();
            MessageSendUtils.sendChatMessage("dm_recharge_record|seq|"+seq,"System",sendContent,userService.getUsernameByCardId(dmExpenseCalendarDto.getCardNumber()));
        } else {
            log.info("dmExpenseCalendar is null. seq:"+seq);
        }
    }
}