package com.chy.borrow.controller;


import com.chy.borrow.config.TestData;
import com.chy.borrow.entity.BorrowApply;
import com.chy.borrow.eum.BorrowStatusEnum;
import com.chy.borrow.mapper.BorrowApplyMapper;
import com.chy.borrow.service.BorrowApplyService;
import com.chy.borrow.service.TmpCodeService;
import com.chy.borrow.util.FileUploadUtil;
import com.shanghaigeography.Util.DateUtils;
import com.shanghaigeography.Util.SnowflakeConfig;
import com.shanghaigeography.entity.ResultMsg;
import com.shanghaigeography.eum.ResultState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.sql.Timestamp;
import java.util.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 沈晔浩
 * @since 2022-03-25
 */
@Controller
@CrossOrigin
@RequestMapping("/borrowApply")
public class BorrowApplyController extends BaseController {
    @Autowired
    BorrowApplyService borrowApplyService;
    @Autowired
    TmpCodeService tmpCodeService;
    @Autowired
    BorrowApplyMapper borrowApplyMapper;


    @RequestMapping("/hasCode")
    @ResponseBody
    public String hasCode(@RequestBody Map map) {
        String code = map.get("code").toString();
        Map data = TestData.getProjectInfo(code);
        boolean isExceed =isExceed(code);
        if (data != null) {
            data.put("type", "1");
            List list = new ArrayList();
            list.add(data);
            return new ResultMsg<>().setCode(isExceed?ResultState.ERROR_NEEDDATA:ResultState.SUCCESS).setMsg(isExceed?"借阅期限已经过期":"查询成功").setData(list).toJSON();
        }
        Map map1 = new HashMap();
        map1.put("tmp_code", code);
        if (tmpCodeService.listByMap(map1).size() > 0) {
            Map map2 = new HashMap();
            map2.put("type", "2");
            List list = new ArrayList();
            list.add(map2);
            return new ResultMsg<>().setCode(isExceed?ResultState.ERROR_NEEDDATA:ResultState.SUCCESS).setMsg(isExceed?"借阅期限已经过期":"查询成功").setData(list).toJSON();
        }
        return new ResultMsg<>().setCode(ResultState.ERROR).setMsg("查询失败,没有此项目编号或临时编号信息").toJSON();
    }

    private boolean isExceed(String code) {
        try {

            Map map = borrowApplyMapper.getTimeByCode(code);
            String applyTime = map.get("applyTime").toString();
            Integer borrowDeadline = Integer.valueOf(map.get("borrowDeadline").toString());
            Date date = DateUtils.yearAddNum(new Date(),-borrowDeadline);
            Date date1 = DateUtils.stringToDate(applyTime,"yyyy-MM-dd HH:mm:ss");
            int dif  = DateUtils.dateDiffFen(date1,date);
            if (dif<0){
                return true;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

    @RequestMapping("/getProjectCodeInfo")
    @ResponseBody
    public String getProjectCodeInfo(@RequestBody Map map) {
        String code = map.get("code").toString();
        Map data = TestData.getProjectInfo(code);
        if (data!=null){
            List list = new ArrayList();
            list.add(data);
            return new ResultMsg<>().setCode(ResultState.SUCCESS).setMsg("查询成功").setData(list).toJSON();
        }else {
            return new ResultMsg<>().setCode(ResultState.ERROR).setMsg("查询失败,没有此项目编号信息").toJSON();
        }
    }

    @RequestMapping("/list")
    @ResponseBody
    public String list(@RequestBody Map map) {
        return borrowApplyService.getList(map);
    }

    @RequestMapping("/listForRange")
    @ResponseBody
    public String listForRange(@RequestBody Map map) {
        return borrowApplyService.getListForRange(map);
    }

    @RequestMapping("/getInfoById")
    @ResponseBody
    public String getInfoById(@RequestBody BorrowApply borrowApply) {
        return borrowApplyService.getInfoById(borrowApply);
    }

    @RequestMapping(value = "/insert", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String insert(@RequestBody BorrowApply borrowApply, @RequestHeader String userId) {
        try {
            borrowApply.setProjectCode(borrowApply.getProjectCode().equals("") ? null : borrowApply.getProjectCode());
            String borrowStatus = BorrowStatusEnum.get(1) == null ? null : BorrowStatusEnum.get(1).getStatusCodeString();
            borrowApply.setBorrowApplyId(getBorrowApplyId());
            borrowApply.setApplyUserId(userId);
            borrowApply.setApplyTime(new Date());
            borrowApply.setBorrowStatus(borrowStatus);
            borrowApplyService.save(borrowApply);
            return new ResultMsg<String>().setCode(ResultState.SUCCESS).setMsg("申请成功").toJSON();
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultMsg<String>().setCode(ResultState.ERROR).setMsg("申请失败").toJSON();
        }
    }

    @RequestMapping(value = "/updateRange")
    @ResponseBody
    public String updateRange(@RequestBody BorrowApply borrowApply) {
        try {
//            String borrowStatus = BorrowStatusEnum.get(1)==null?null:BorrowStatusEnum.get(1).getStatusCodeString();
//            borrowApply.setBorrowApplyId(new SnowflakeConfig().snowflakeStringId());
//            borrowApply.setApplyTime(new Date());
//            borrowApply.setBorrowStatus(borrowStatus);
            borrowApplyService.updateById(borrowApply);
            return new ResultMsg<String>().setCode(ResultState.SUCCESS).setMsg("期限修改成功").toJSON();
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultMsg<String>().setCode(ResultState.ERROR).setMsg("期限修改失败").toJSON();
        }
    }

    @RequestMapping(value = "/save")
    @ResponseBody
    public String save(@RequestBody BorrowApply borrowApply) {
        return borrowApplyService.saveFile(borrowApply);
    }

    @RequestMapping(value = "/import")
    @ResponseBody
    public String importFile(@RequestBody BorrowApply borrowApply) {
        try {
            borrowApplyService.saveFile(borrowApply);
            return new ResultMsg<String>().setCode(ResultState.SUCCESS).setMsg("期限修改成功").toJSON();
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultMsg<String>().setCode(ResultState.ERROR).setMsg("期限修改失败").toJSON();
        }
    }

    @RequestMapping(value = "/insertNew", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String insertNew(BorrowApply borrowApply, @RequestParam MultipartFile[] fileList, @RequestHeader String userId) {
        try {
//            BorrowApply borrowApply = JSON.parseObject(JSON.toJSONString(borrowApplyVo),BorrowApply.class);
//            if (borrowApplyVo.getFileList()!=null) {
            if (fileList != null && fileList.length > 0) {
//                MultipartFile[] fileList = borrowApplyVo.getFileList();
                String file = "";
                for (MultipartFile multipartFile : fileList) {
                    if (file != "") {
                        file += ",";
                    }
                    file += "http://47.101.207.123:8080/file/" + FileUploadUtil.uploadToBasePath(multipartFile, "D:\\file\\").replaceAll("\\\\", "/");
                }
                borrowApply.setDeadlineMaterials(file);
            }
            borrowApply.setProjectCode(borrowApply.getProjectCode().equals("") ? null : borrowApply.getProjectCode());
            String borrowStatus = BorrowStatusEnum.get(1) == null ? null : BorrowStatusEnum.get(1).getStatusCodeString();
            borrowApply.setBorrowApplyId(new SnowflakeConfig().snowflakeStringId());
            borrowApply.setApplyUserId(userId);
            borrowApply.setApplyTime(new Date());
            borrowApply.setBorrowStatus(borrowStatus);
            borrowApplyService.save(borrowApply);
            return new ResultMsg<String>().setCode(ResultState.SUCCESS).setMsg("申请成功").toJSON();
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultMsg<String>().setCode(ResultState.ERROR).setMsg("申请失败").toJSON();
        }
    }

    public String getBorrowApplyId() {
        String borrowApplyId_before = "cg" + DateUtils.getNowTimeStringToDD("yyyyMMdd");
        int count = borrowApplyMapper.getCountByCode(borrowApplyId_before);
        if (count < 9) {
            return borrowApplyId_before + "000" + (count + 1);
        } else if (count < 99) {
            return borrowApplyId_before + "00" + (count + 1);
        } else if (count < 999) {
            return borrowApplyId_before + "0" + (count + 1);
        } else {
            return borrowApplyId_before + (count + 1);
        }
    }

    @RequestMapping(value = "/listUnitCount")
    @ResponseBody
    public String getUnitCountList() {
        return borrowApplyService.getUnitCountList();
    }

    @RequestMapping(value = "/listTempCount")
    @ResponseBody
    public String getCountList() {
        return borrowApplyService.getCountList();
    }

    @RequestMapping(value = "/listYMDCount")
    @ResponseBody
    public String getYearCountList(Integer start,Integer num) {
        return borrowApplyService.getApplyTimeCountList(start,num);
    }


    @RequestMapping(value = "/listPeriodCount")
    @ResponseBody
    public String getDayCountList(String start, String end) {

        Timestamp startTime = Timestamp.valueOf(start);

        Timestamp endTime = Timestamp.valueOf(end);

        return borrowApplyService.getApplyTimeByPeriod(startTime, endTime);
    }
}