package com.chy.borrow.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.chy.borrow.config.TestData;
import com.chy.borrow.entity.BorrowApply;
import com.chy.borrow.entity.BorrowExamine;
import com.chy.borrow.eum.BorrowStatusEnum;
import com.chy.borrow.eum.ExamineStatusEnum;
import com.chy.borrow.mapper.BorrowApplyMapper;
import com.chy.borrow.mapper.BorrowExamineMapper;
import com.chy.borrow.service.BorrowApplyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chy.borrow.util.CSVUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.shanghaigeography.Util.DateUtils;
import com.shanghaigeography.Util.SnowflakeConfig;
import com.shanghaigeography.entity.ResultMsg;
import com.shanghaigeography.eum.ResultState;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 沈晔浩
 * @since 2022-03-25
 */
@Service
public class BorrowApplyServiceImpl extends ServiceImpl<BorrowApplyMapper, BorrowApply> implements BorrowApplyService {

    @Autowired
    BorrowApplyMapper borrowApplyMapper;

    @Override
    public String getList(Map map) {
        try {
            Integer current = Integer.valueOf(map.get("current").toString());
            Integer pageSize = Integer.valueOf(map.get("pageSize").toString());
            PageHelper.startPage(current, pageSize);
            Page<Map> list = borrowApplyMapper.getList(map);
            if (list != null) {
                return new ResultMsg<>(ResultState.SUCCESS, null, JSONObject.toJSONString(list), list.getPageNum(), list.getTotal(), list.getPageSize(), list.getPages()).toPageJSON();
            }
        } catch (Exception e) {
            return new ResultMsg<String>().setCode(ResultState.ERROR).setMsg("服务器出错").toJSON();
        }
        return new ResultMsg<String>().setCode(ResultState.SUCCESS).setMsg("无数据").toJSON();
    }

    @Override
    public String getListForRange(Map map) {
        try {
            Integer current = Integer.valueOf(map.get("current").toString());
            Integer pageSize = Integer.valueOf(map.get("pageSize").toString());
            map.put("borrowStatus", "");
            PageHelper.startPage(current, pageSize);
            Page<Map> list = borrowApplyMapper.getListForRange(map);
            if (list != null) {
                return new ResultMsg<>(ResultState.SUCCESS, null, JSONObject.toJSONString(list), list.getPageNum(), list.getTotal(), list.getPageSize(), list.getPages()).toPageJSON();
            }
        } catch (Exception e) {
            return new ResultMsg<String>().setCode(ResultState.ERROR).setMsg("服务器出错").toJSON();
        }
        return new ResultMsg<String>().setCode(ResultState.SUCCESS).setMsg("无数据").toJSON();
    }

    @Override
    public String getInfoById(BorrowApply borrowApply) {
        Map map1 = borrowApplyMapper.getInfoById(borrowApply.getBorrowApplyId());
        Map data = TestData.getProjectInfo(map1.get("projectCode").toString());
        if (data != null) {
            for (Object obj : data.keySet()) {
                map1.put(obj, data.get(obj));
            }
        }
        List result = new ArrayList();
        if (map1 != null) {
            result.add(map1);
        }
        return new ResultMsg<>().setCode(ResultState.SUCCESS).setData(result).toJSON();
    }

    @Override
    public String saveFile(BorrowApply borrowApply) {
        String fileName = "常规申请" + (new Date().getTime()) + ".csv";
        List<Map> list = new ArrayList<>();
        Map map = new HashMap();
        map.put("项目编号", borrowApply.getTmpCode() == null ? borrowApply.getProjectCode() : borrowApply.getTmpCode());
        map.put("数据范围", borrowApply.getDataRange());
        map.put("申请理由", borrowApply.getApplyReason());
        map.put("期限说明材料", borrowApply.getDeadlineMaterials());
        map.put("借阅期限", borrowApply.getBorrowDeadline());
        map.put("借阅数据", borrowApply.getBorrowData());
        list.add(map);
        CSVUtil.writeFileForMap("D:\\file\\" + fileName, list);
        String url = "http://47.101.207.123:8080/file/" + fileName;
        List result = new ArrayList();
        Map map1 = new HashMap();
        map1.put("url", url);
        result.add(map1);
        return new ResultMsg<>().setCode(ResultState.SUCCESS).setData(result).toJSON();
    }

    //借阅量（常规）
    @Override
    public String getCountList() {

        List<Map> countList = borrowApplyMapper.getCountList();

        return new ResultMsg<>().setCode(ResultState.SUCCESS).setData(countList).toJSON();
    }

    //部门借阅占比
    @Override
    public String getUnitCountList() {

        List<Map> unitCountList = borrowApplyMapper.getUnitCountList();

        BigDecimal total = BigDecimal.ZERO;

        for (Map data : unitCountList) {

            BigDecimal borrowCount = new BigDecimal((Long) data.get("borrowCount"));

            total = total.add(borrowCount);

        }

        BigDecimal temp = BigDecimal.ZERO;

        for (int i = 0; i < unitCountList.size(); i++) {

            Map data = unitCountList.get(i);

            if (i == unitCountList.size() - 1) {

                BigDecimal subtract = new BigDecimal("1.0000").subtract(temp);

                data.put("percentage", subtract);

            } else {
                BigDecimal count = new BigDecimal((Long) data.get("borrowCount"));

                BigDecimal percentage = count.divide(total, 4, RoundingMode.CEILING);

                temp = temp.add(percentage);

                data.put("percentage", percentage);
            }

        }

        return new ResultMsg<>().setCode(ResultState.SUCCESS).setData(unitCountList).toJSON();
    }

    @Override
    public String getApplyTimeCountList(Integer start, Integer num) {
        List<Map> timeCountList = borrowApplyMapper.getApplyTimeCountList(start, num);
        List<Map> result = new ArrayList<>();
        LocalDate date = LocalDate.now();
        LocalDate lastDay = date.with(TemporalAdjusters.lastDayOfMonth());
        System.out.println(lastDay.getDayOfMonth());
        int MonthDay=lastDay.getDayOfMonth();
        //年填充字段
        if (start == 0 && num == 0) {
            for (int i = 1; i <= 12; i++) {
                Map<String,Integer> temp = new HashMap();
                        temp.put("applyTime", i);
                        temp.put("borrowCount", 0);
                        result.add(temp);

            }
        }
        //日填充字段
        else if(start == 6 && num == 6){
            for (int i = 1; i <= 24; i++) {
                Map<String,Integer> temp = new HashMap();
                temp.put("applyTime", i);
                temp.put("borrowCount", 0);
                result.add(temp);
            }
        }
        //月填充字段
        else if(start == 3 && num == 3){
            for (int i = 1; i <=MonthDay ; i++) {
                Map<String,Integer> temp = new HashMap();
                temp.put("applyTime", i);
                temp.put("borrowCount", 0);
                result.add(temp);
            }
        }
        for (Map<String,String> data : timeCountList){

            Integer idx=Integer.valueOf(data.get("applyTime"));

            if (Integer.valueOf(data.get("applyTime")) == idx) {
                Map map = result.get(idx - 1);

                map.put("borrowCount",data.get("borrowCount"));
            }

        }
        return new ResultMsg<>().setCode(ResultState.SUCCESS).setData(result).toJSON();
    }

    @Override
    public String getApplyTimeByPeriod(Timestamp start, Timestamp end) {
        List<Map> TimeByPeriodList = borrowApplyMapper.getApplyTimeByPeriod(start, end);
        return new ResultMsg<>().setCode(ResultState.SUCCESS).setData(TimeByPeriodList).toJSON();
    }

}
