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

import com.alibaba.fastjson.JSONArray;
import com.bonus.hn.bearing.capacity.backstage.companypro.entity.ProjectManagerBean;
import com.bonus.hn.bearing.capacity.backstage.dataindex.entity.DataHomeBean;
import com.bonus.hn.bearing.capacity.backstage.dataindex.entity.ProjectBean;
import com.bonus.hn.bearing.capacity.backstage.dataindex.entity.ToolsBean;
import com.bonus.hn.bearing.capacity.backstage.dataindex.service.DataIndexService;
import com.bonus.hn.bearing.capacity.backstage.manager.annotation.LogAnnotation;
import com.bonus.hn.bearing.capacity.backstage.manager.model.SysUser;
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.RnProjectBindBean;
import com.bonus.hn.bearing.capacity.backstage.project.entity.TowerProjectBean;
import com.bonus.hn.bearing.capacity.backstage.teamset.entity.ResourceSetBean;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
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.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xliu
 * @date 2023/11/10 13:26
 */
@RestController
@RequestMapping("/dataIndex")
public class DataIndexController {

    @Resource
    private DataIndexService dataIndexService;

    @LogAnnotation
    @PostMapping("getProjectStatus")
    @ApiOperation(value = "获取工程在建状态")
    public R getProjectStatus(ProjectBean bean){
        bean.setLevel(UserUtil.getLoginUser().getLevel());
        bean.setOrgId(UserUtil.getLoginUser().getOrgId());
        System.err.println("ProjectBean="+bean);
        ProjectBean projectBean = dataIndexService.getProjectStatus(bean);
        return projectBean != null ? R.okTable(projectBean, 1):R.failTable("暂无数据");
    }

    @LogAnnotation
    @PostMapping("getBranchOfficeTeamStatus")
    @ApiOperation(value = "分公司团队 (投入/闲置)")
    public R getBranchOfficeTeamStatus(ProjectBean bean){
        bean.setLevel(UserUtil.getLoginUser().getLevel());
        bean.setOrgId(UserUtil.getLoginUser().getOrgId());
        System.err.println("ProjectBean="+bean);
        ProjectBean projectBean = dataIndexService.getBranchOfficeTeamStatus(bean);
        System.err.println("getBranchOfficeTeamStatus="+projectBean);
        return projectBean != null ? R.okTable(projectBean, 1):R.failTable("暂无数据");
    }

    @LogAnnotation
    @PostMapping("getSubTeamStatus")
    @ApiOperation(value = "数据概览分包班组")
    public R getSubTeamStatus(ProjectBean bean){
        System.err.println("ProjectBean="+bean);
        ProjectBean projectBean = dataIndexService.getSubTeamStatus(bean);
        return projectBean != null ? R.okTable(projectBean, 1):R.failTable("暂无数据");
    }

    @LogAnnotation
    @PostMapping("getOwnTeamStatus")
    @ApiOperation(value = "数据概览自有班组")
    public R getOwnTeamStatus(ProjectBean bean){
        System.err.println("ProjectBean="+bean);
        ProjectBean projectBean = dataIndexService.getOwnTeamStatus(bean);
        return projectBean != null ? R.okTable(projectBean, 1):R.failTable("暂无数据");
    }

    @LogAnnotation
    @PostMapping("getToolStatus")
    @ApiOperation(value = "数据概览设备工机具")
    public R getToolStatus(ProjectBean bean){
        System.err.println("ProjectBean="+bean);
        ProjectBean projectBean = dataIndexService.getToolStatus(bean);
        return projectBean != null ? R.okTable(projectBean, 1):R.failTable("暂无数据");
    }


    @LogAnnotation
    @PostMapping("getSubTeamType")
    @ApiOperation(value = "获取分包班组类型")
    public R getSubTeamType(ProjectBean bean){
        System.err.println("ProjectBean="+bean);
        ProjectBean projectBean = dataIndexService.getSubTeamType(bean);
        return projectBean != null ? R.okTable(projectBean, 1):R.failTable("暂无数据");
    }

    @LogAnnotation
    @PostMapping("getProjectProgress")
    @ApiOperation(value = "获取项目进度信息")
    public R getProjectProgress(DataHomeBean bean){
        Map<String, List<String>> list = dataIndexService.getProjectProgress(bean);
        return list.size() >0 ? R.okTable(JSONArray.toJSON(list).toString(), list.size()):R.failTable("暂无数据");
    }

    @LogAnnotation
    @PostMapping("getReal")
    @ApiOperation(value = "获取实名制信息")
    @ResponseBody
    public R getReal(ProjectBean bean){
        System.err.println("ProjectBean="+bean);
        Map<String, Object> list = dataIndexService.getReal();
        return list.size() >0 ? R.okTable(JSONArray.toJSON(list).toString(), list.size()):R.failTable("暂无数据");
    }


    @LogAnnotation
    @PostMapping("getTool")
    @ApiOperation(value = "获取机具信息")
    @ResponseBody
    public R getTool(ProjectBean bean){
        System.err.println("ProjectBean="+bean);
        Map<String, Object> list = dataIndexService.getTool();
        return list.size() >0 ? R.okTable(JSONArray.toJSON(list).toString(), list.size()):R.failTable("暂无数据");
    }

    @LogAnnotation
    @PostMapping("getToolList")
    @ApiOperation(value = "工机具库-列表")
    public R getToolList(ProjectBean o){
        List<ProjectBean> list = dataIndexService.getToolList(o);
        return list.size() > 0 ? R.okTable(list, list.size()):R.failTable("暂无数据");
    }
    /**
     * 工机具库清单导出
     * @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 {
        ProjectBean b = new ProjectBean();
        b.setKeyWord(request.getParameter("keyword"));
        b.setDictKey(request.getParameter("dictKey"));
        b.setDeviceName(request.getParameter("deviceName"));
        List<ProjectBean> list = dataIndexService.getToolList(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};
        String fileName = "工机具库清单";
        if (list != null) {
            int i = 0;
            for (ProjectBean bean : list){
                i++;
                Map<String, Object> map = new HashMap<>(100);
                map.put("序号",i);
                map.put("工序",bean.getToolsProcesName());
                map.put("设备名称",bean.getToolsName());
                map.put("规格型号",bean.getToolsModel());
                map.put("单位",bean.getToolsUnit());
                map.put("总数量",bean.getToolsNum());
                String useNumString = bean.getUseNum();
                int useNum = useNumString != null ? Integer.parseInt(useNumString) : 0;
                map.put("正在使用数量",bean.getUseNum());
                int RemainNum = Integer.parseInt(bean.getToolsNum()) - useNum;
                map.put("库存数量",RemainNum);
                map.put("备注",bean.getNotes());
                mapList.add(map);
            }
        }
        try {
            ExcelUtils.export(fileName, fileName, excelHeader, excelHeader, ds_format, null, mapList, request,
                    response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 文件上传请求
     */
    @LogAnnotation
    @PostMapping("/toolListImport")
    @ApiOperation(value = "设备工机具-文件导入")
    public AjaxRes toolListImport(@RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException {
        AjaxRes ar = new AjaxRes();
        try {
            String code = dataIndexService.toolListImport(request,file);
            if ("导入成功".equals(code)){
                ar.setSucceedMsg("导入成功");
            }else{
                ar.setFailMsg(code);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ar;
    }

    @RequestMapping(value = "addToolInfo", method = RequestMethod.POST)
    @ResponseBody
    @PreAuthorize("hasAuthority('sysTool:add')")
    @ApiOperation(value = "工机具库-新增")
    public AjaxRes addToolInfo(@RequestBody ProjectBean bean) throws Exception {
        AjaxRes ar = new AjaxRes();
        int cb = dataIndexService.addToolInfo(bean);
        ar.setFailMsg(GlobalConst.DATA_FAIL);
        if(cb>0){
            ar.setFailMsg(GlobalConst.INIT_SUCCEED);
        }
        return  ar;
    }

    @RequestMapping(value = "updateTool", method = RequestMethod.POST)
    @ResponseBody
    @PreAuthorize("hasAuthority('sysTool:update')")
    @ApiOperation(value = "工机具库-修改")
    public AjaxRes updateTool(@RequestBody ProjectBean bean) throws Exception {
        AjaxRes ar = new AjaxRes();
        int cb = dataIndexService.updateTool(bean);
        ar.setFailMsg(GlobalConst.DATA_FAIL);
        if(cb>0){
            ar.setFailMsg(GlobalConst.INIT_SUCCEED);
        }
        return  ar;
    }

    @RequestMapping(value = "getListTool", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "工机具库-查询机具信息")
    public AjaxRes getListTool(String id){
        AjaxRes ar = new AjaxRes();
        ProjectBean projectBean = dataIndexService.getListTool(id);
        Map<String, Object> map = new HashMap<>(100);
        if(projectBean !=null){
            map.put("projectBean",projectBean);
        }
        ar.setSucceed(map,GlobalConst.DATA_SUCCEED);
        return ar;
    }

    @RequestMapping(value = "delToolsById", method = RequestMethod.POST)
    @ResponseBody
    @PreAuthorize("hasAuthority('sysTool:del')")
    @ApiOperation(value = "工机具库-删除")
    public AjaxRes delToolsById(String id){
        AjaxRes ar = new AjaxRes();
        int cb = dataIndexService.delToolsById(id);
        ar.setFailMsg(GlobalConst.DATA_FAIL);
        if(cb>0){
            ar.setFailMsg(GlobalConst.DATA_SUCCEED);
        }else if(cb == 0) {
            ar.setFailMsg(GlobalConst.DATA_UNTIE);
        }
        return  ar;
    }

    @LogAnnotation
    @PostMapping("getActiveList")
    @ApiOperation(value = "正在使用的设备-列表")
    public R getActiveList(ProjectBean o){
        List<ProjectBean> list = dataIndexService.getActiveList(o);
        return list.size() > 0 ? R.okTable(list, list.size()):R.failTable("暂无数据");
    }
    /**
     * 工机具正在使用设备清单导出
     * @param request
     * @param response
     * @param page
     */
    @RequestMapping(value = "/exportPhysicalCheckResults", method = RequestMethod.GET)
    @ApiOperation(value = "工机具正在使用设备清单-导出")
    public void exportPayrolls(HttpServletRequest request, HttpServletResponse response, PageTableRequest page) throws ParseException {
        ProjectBean b = new ProjectBean();
        b.setKeyWord(request.getParameter("keyword"));
        b.setDictKey(request.getParameter("dictKey"));
        b.setDeviceName(request.getParameter("deviceName"));
        List<ProjectBean> list = dataIndexService.getToolLists(b);
        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        String[] excelHeader = {"序号","工序","设备名称","规格型号","单位","项目部"
                ,"分公司"};
        int[] ds_format = {2, 2, 2, 2, 2, 2, 2};
        String fileName = "工机具正在使用设备清单";
        if (list != null) {
            int i = 0;
            for (ProjectBean bean : list){
                i++;
                Map<String, Object> map = new HashMap<>(100);
                map.put("序号",i);
                map.put("工序",bean.getToolsProcesName());
                map.put("设备名称",bean.getToolsName());
                map.put("规格型号",bean.getToolsModel());
                map.put("单位",bean.getToolsUnit());
                map.put("项目部",bean.getProName());
                map.put("分公司",bean.getBranchName());
                mapList.add(map);
            }
        }
        try {
            ExcelUtils.export(fileName, fileName, excelHeader, excelHeader, ds_format, null, mapList, request,
                    response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @LogAnnotation
    @PostMapping("delActiveById")
    @PreAuthorize("hasAuthority('sysActive:untie')")
    @ApiOperation(value = "正在使用的设备-解绑")
    public AjaxRes delActiveById(ProjectBean bean) {
        AjaxRes ar = new AjaxRes();
        int cb  = dataIndexService.delActiveById(bean);
        if(cb > 0){
            ar.setSucceedMsg(GlobalConst.DATA_SUCCEED);
        }else {
            ar.setFailMsg(GlobalConst.DATA_FAIL);
        }
        return ar;
    }

    @LogAnnotation
    @PostMapping("addActive")
    @PreAuthorize("hasAuthority('sysActive:bind')")
    @ApiOperation(value = "实名制工程绑定-绑定")
    public AjaxRes addActive(@RequestBody ProjectBean bean) {
        AjaxRes ar = new AjaxRes();
        int result  = dataIndexService.addActive(bean);
        if(result==1){
            ar.setSucceedMsg(GlobalConst.DATA_SUCCEED);
        }else {
            ar.setFailMsg(GlobalConst.DATA_FAIL);
        }
        return ar;
    }

    @RequestMapping(value = "getSurplusQuantity", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "工机具库-剩余未绑定数量")
    public AjaxRes getSurplusQuantity(String id){
        AjaxRes ar = new AjaxRes();
        ProjectBean sysUser = dataIndexService.getSurplusQuantity(id);
        Map<String, Object> map = new HashMap<>(100);
        if(sysUser !=null){
            map.put("sysUser",sysUser);
        }
        ar.setSucceed(map,GlobalConst.DATA_SUCCEED);
        return ar;
    }

}
