package com.bonus.hn.bearing.capacity.backstage.project.controller;

import com.bonus.hn.bearing.capacity.backstage.companypro.entity.ProjectManagerBean;
import com.bonus.hn.bearing.capacity.backstage.manager.annotation.LogAnnotation;
import com.bonus.hn.bearing.capacity.backstage.manager.table.PageTableRequest;
import com.bonus.hn.bearing.capacity.backstage.manager.utils.*;
import com.bonus.hn.bearing.capacity.backstage.project.entity.FileBean;
import com.bonus.hn.bearing.capacity.backstage.project.entity.LineProjectBean;
import com.bonus.hn.bearing.capacity.backstage.project.entity.ProgressBean;
import com.bonus.hn.bearing.capacity.backstage.project.service.ProgressService;
import io.swagger.annotations.ApiOperation;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.nio.file.Files;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.*;

/**
 * @author xliu
 * @date 2023/11/6 14:46 工程进度管理
 */
@RestController
@RequestMapping("/proProgress")
public class ProgressController {

    @Resource
    private ProgressService service;

    @LogAnnotation
    @PostMapping("getBasicDataList")
    @ApiOperation(value = "工程进度管理-基础列表查询")
    public R getBasicDataList(ProgressBean o){
        List<ProgressBean> list = service.getBasicDataList(o);
        return list.size() > 0 ? R.okTable(list, list.size()):R.failTable("暂无数据");
    }
    @LogAnnotation
    @PostMapping("getProjectProgress")
    @ApiOperation(value = "工程进度管理-项目进度杆塔状态列表查询")
    public R getProjectProgress(ProgressBean o){
        List<ProgressBean> list = service.getProjectProgress(o);
        return list.size() > 0 ? R.okTable(list, list.size()):R.failTable("暂无数据");
    }
    @LogAnnotation
    @PostMapping("getPersonList")
    @ApiOperation(value = "工程进度管理-获取成员列表")
    public R getPersonList(ProgressBean o){
        List<ProgressBean> list = service.getPersonList(o);
        return list.size() > 0 ? R.okTable(list, list.size()):R.failTable("暂无数据");
    }
    @LogAnnotation
    @PostMapping("getFileList")
    @ApiOperation(value = "工程进度管理-获取文件列表")
    public R getFileList(FileBean o){
        List<FileBean> list = service.getFileList(o);
        return list.size() > 0 ? R.okTable(list, list.size()):R.failTable("暂无数据");
    }

    @RequestMapping(value = "getProTitleData", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "工程进度管理-获取工程数据表头")
    public AjaxRes getProTitleData(ProgressBean o){
        AjaxRes ar = new AjaxRes();
        ProgressBean bean = service.getProTitleData(o);
        Map<String, Object> map = new HashMap<>(100);
        if(bean !=null){
            map.put("ProgressBean",bean);
        }
        ar.setSucceed(map, GlobalConst.DATA_SUCCEED);
        return ar;
    }
    @RequestMapping(value = "getTowerData", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "工程进度管理-获取杆塔更新数据")
    public AjaxRes getTowerData(ProgressBean o){
        AjaxRes ar = new AjaxRes();
        Map<String, Object> map = new HashMap<>(100);
        map = service.getTowerData(o);
        ar.setSucceed(map, GlobalConst.DATA_SUCCEED);
        return ar;
    }
    @RequestMapping(value = "getBackspaceTowerData", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "工程进度管理-回退杆塔数据")
    public AjaxRes getBackspaceTowerData(ProgressBean o){
        AjaxRes ar = new AjaxRes();
        Map<String, Object> map = new HashMap<>(100);
        map = service.getBackspaceTowerData(o);
        ar.setSucceed(map, GlobalConst.DATA_SUCCEED);
        return ar;
    }
    @RequestMapping(value = "getProcessTitles", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "工程进度管理-获取项目进度数据")
    public AjaxRes getProcessTitles(ProgressBean o){
        AjaxRes ar = new AjaxRes();
        Map<String, Object> map = new HashMap<>(100);
        map = service.getProcessTitles(o);
        ar.setSucceed(map, GlobalConst.DATA_SUCCEED);
        return ar;
    }
    @RequestMapping(value = "getTowerRecordTimeLine", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "工程进度管理-获取更新记录时间线")
    public AjaxRes getTowerRecordTimeLine(ProgressBean o){
        AjaxRes ar = new AjaxRes();
        Map<String, Object> map = new HashMap<>(100);
        map = service.getTowerRecordTimeLine(o);
        ar.setSucceed(map, GlobalConst.DATA_SUCCEED);
        return ar;
    }

    @RequestMapping(value = "updateProProgress", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "工程进度管理-更新项目进度")
    public AjaxRes updateProProgress(@RequestBody ProgressBean bean){
        AjaxRes ar = new AjaxRes();
        int cb = service.updateProProgress(bean);
        ar.setFailMsg(GlobalConst.DATA_FAIL);
        if(cb>0){
            ar.setFailMsg(GlobalConst.INIT_SUCCEED);
        }
        return  ar;
    }

    @RequestMapping(value = "updateBackspaceProProgress", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "工程进度管理-回退项目进度")
    public AjaxRes updateBackspaceProProgress(@RequestBody ProgressBean bean){
        AjaxRes ar = new AjaxRes();
        int cb = service.updateBackspaceProProgress(bean);
        ar.setFailMsg(GlobalConst.DATA_FAIL);
        if(cb>0){
            ar.setFailMsg(GlobalConst.INIT_SUCCEED);
        }
        return  ar;
    }

    @LogAnnotation
    @PostMapping("delFileRecordById")
    @ApiOperation(value = "工程进度管理-删除文件记录")
    public AjaxRes delFileRecordById(FileBean bean) {
        AjaxRes ar = new AjaxRes();
        int result  = service.delFileRecordById(bean);
        if(result==1){
            ar.setSucceedMsg(GlobalConst.DATA_SUCCEED);
        }else {
            ar.setFailMsg(GlobalConst.DATA_FAIL);
        }
        return ar;
    }

    @PostMapping("/upload")
    @ResponseBody
    @ApiOperation(value = "工程进度管理-更新项目进度")
    public List<String> handleFileUpload(@RequestParam("file") MultipartFile[] files, FileBean b) {
        List<String> fileNames = new ArrayList<>();
        for (MultipartFile file : files) {
            if (file.isEmpty()) {
                fileNames.add("File is empty");
                continue;
            }
            try {
                // 获取文件名
                String fileName = file.getOriginalFilename();
                String mkdirsName = "proProcess";
                // linux 系统路径
                String filePath = "/data/hnczl/" + mkdirsName + "/";
                String os = System.getProperty("os.name");
                if (os.toLowerCase().startsWith("win")) {
                    filePath = "D://files/" + mkdirsName+"/";
                }
                String path = filePath + "/" + DateTimeHelper.getYear(new Date()) + "/" + DateTimeHelper.getMonth(new Date()) + "/"+DateTimeHelper.getDay()+ "/" + fileName;
                String imgPath = mkdirsName + "/" + DateTimeHelper.getYear(new Date()) + "/" + DateTimeHelper.getMonth(new Date()) + "/"+DateTimeHelper.getDay()+ "/" + fileName;
                File dest = new File(path);
                // 检查父级目录是否存在，不存在则创建
                if (!dest.getParentFile().exists()) {
                    dest.getParentFile().mkdirs();
                }
                // 存入临时文件
                file.transferTo(dest);
                fileNames.add(fileName);

                long fileSize = file.getSize();
                // 转换为MB
                double megabytes = (double) fileSize / (1024 * 1024);
                // 格式化为两位小数
                DecimalFormat df = new DecimalFormat("#.##");
                String resultSize = df.format(megabytes);
                FileBean bean = new FileBean();
                bean.setFileName(fileName);
                bean.setFilePath(imgPath);
                bean.setFileSize(resultSize);
                bean.setUserId(UserUtil.getLoginUser().getId()+"");
                bean.setUserName(UserUtil.getLoginUser().getUsername());
                bean.setType("process");
                bean.setRemark(b.getRemark());
                bean.setAssociaId(b.getAssociaId());
                service.insertFile(bean);
            } catch (IOException e) {
                fileNames.add("Failed to upload " + file.getOriginalFilename());
            }
        }
        return fileNames;
    }

    /**
     * 工程进度管理导出
     * @param request
     * @param response
     * @param page
     */
    @RequestMapping(value = "/exportPhysicalCheckResult", method = RequestMethod.GET)
    @ApiOperation(value = "工程进度管理-导出")
    public void exportPayroll(HttpServletRequest request, HttpServletResponse response, PageTableRequest page) throws ParseException {
        ProgressBean b = new ProgressBean();
        b.setKeyWord(request.getParameter("keyword"));
        b.setOrgId(request.getParameter("orgId"));
        b.setVoltageLevelId(request.getParameter("voltageLevelId"));
        List<ProgressBean> list = service.getExportList(b);
        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        String[] excelHeader = {"序号","分公司","工程名称","计划开工日期","计划完工日期","工序"
                ,"设计工作量","完成工作量","完成百分比","项目总体进度"};
        int[] ds_format = {2, 2, 2, 2, 2, 2, 2, 2, 2, 2};
        String fileName = "项目进度详情";
        if (list != null) {
            int i = 0;
            for (ProgressBean bean : list){
                i++;
                Map<String, Object> map = new HashMap<>(100);
                map.put("序号",i);
                map.put("分公司",bean.getOrgName());
                map.put("工程名称",bean.getProName());
                map.put("计划开工日期",bean.getStartTime());
                map.put("计划完工日期",bean.getEndTime());
//                String proStatus = "0".equals(bean.getProStatus()) ? "在建" : "已完工";
//                map.put("项目状态", proStatus);
                mapList.add(map);
            }
        }
        try {
            MergeExcelUtils.export(fileName, fileName, excelHeader, excelHeader, ds_format, null, mapList, request,
                    response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
