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

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.LineProjectBean;
import com.bonus.hn.bearing.capacity.backstage.project.service.LineProjectService;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.UnexpectedRollbackException;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

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/6 14:47   线路工程管理
 */
@RestController
@RequestMapping("linePro")
public class  LineProjectController {

    @Resource
    private LineProjectService service;

    @LogAnnotation
    @PostMapping("getFirmContentList")
    @ApiOperation(value = "线路工程-列表")
    public R getFirmList(LineProjectBean o){
        List<LineProjectBean> list = service.getFirmList(o);
        return list.size() > 0 ? R.okTable(list, list.size()):R.failTable("暂无数据");
    }

    @LogAnnotation
    @PostMapping("tree")
    @ApiOperation(value = "工程管理-线路工程-项目部树")
    public List<LineProjectBean> getProjectTree(LineProjectBean o) {
        return service.getProjectTree(o);
    }

    @RequestMapping(value = "addProjectInfo", method = RequestMethod.POST)
    @ResponseBody
    @PreAuthorize("hasAuthority('sysFirmContent:add')")
    @ApiOperation(value = "工程管理-线路工程-新增")
    public AjaxRes addProjectInfo(@RequestBody LineProjectBean bean) throws Exception {
        AjaxRes ar = new AjaxRes();
        int cb = service.addProjectInfo(bean);
        ar.setFailMsg(GlobalConst.DATA_FAIL);
        if(cb>0){
            ar.setFailMsg(GlobalConst.INIT_SUCCEED);
            if (cb == 3){
                ar.setFailMsg("该项目部下已存在改工程");
            }
        }
        return  ar;
    }

    @RequestMapping(value = "getListProject", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "工程管理-线路工程-查询人员信息")
    public AjaxRes getListProject(String id){
        AjaxRes ar = new AjaxRes();
        LineProjectBean lineProjectBean = service.getListProject(id);
        Map<String, Object> map = new HashMap<>(100);
        if(lineProjectBean !=null){
            map.put("lineProjectBean",lineProjectBean);
        }
        ar.setSucceed(map,GlobalConst.DATA_SUCCEED);
        return ar;
    }

    @RequestMapping(value = "updateProject", method = RequestMethod.POST)
    @ResponseBody
    @PreAuthorize("hasAuthority('sysFirmContent:update')")
    @ApiOperation(value = "工程管理-线路工程-修改")
    public AjaxRes updateProject(@RequestBody LineProjectBean bean) throws Exception {
        AjaxRes ar = new AjaxRes();
        int cb = service.updateProject(bean);
        ar.setFailMsg(GlobalConst.DATA_FAIL);
        if(cb>0){
            ar.setFailMsg(GlobalConst.INIT_SUCCEED);
            if (cb == 3){
                ar.setFailMsg("该项目部下已存在改工程");
            }
        }
        return  ar;
    }

    @RequestMapping(value = "delProjectById", method = RequestMethod.POST)
    @ResponseBody
    @PreAuthorize("hasAuthority('sysFirmContent:delete')")
    @ApiOperation(value = "工程管理-线路工程-删除")
    public AjaxRes delProjectById(String id) throws Exception {
        AjaxRes ar = new AjaxRes();
        String cb = service.delProjectById(id);
        if("0".equals(cb)){
            ar.setFailMsg(GlobalConst.DATA_FAIL);
        }else if("1".equals(cb)){
            ar.setFailMsg(GlobalConst.DATA_SUCCEED);
        }else {
            ar.setFailMsg(cb);
        }
        return ar;
    }

    @RequestMapping(value = "upCompletedById", method = RequestMethod.POST)
    @ResponseBody
    @PreAuthorize("hasAuthority('sysFirmContent:completed')")
    @ApiOperation(value = "工程管理-线路工程-完工状态变更")
    public AjaxRes upCompletedById(String id) throws Exception {
        AjaxRes ar = new AjaxRes();
        String cb = service.upCompletedById(id);
        if ("0".equals(cb)){
            ar.setFailMsg(GlobalConst.DATA_FAIL);
        }else if ("1".equals(cb)){
            ar.setFailMsg(GlobalConst.DATA_SUCCEED);
        }else {
            ar.setFailMsg(cb);
        }
        return  ar;
    }

    @RequestMapping(value = "upForcedUnbinding", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "工程管理-线路工程-完工状态强制解绑变更")
    @Transactional(rollbackFor = Exception.class)
    public AjaxRes upForcedUnbinding(String id)  {
        AjaxRes ar = new AjaxRes();
        try{
            String cb = service.upForcedUnbinding(id);
            if ("0".equals(cb)){
                ar.setFailMsg(GlobalConst.DATA_FAIL);
            }else if ("1".equals(cb)){
                ar.setFailMsg(GlobalConst.DATA_SUCCEED);
            }else {
                ar.setFailMsg(cb);
            }
        }catch (NullPointerException | UnexpectedRollbackException e) {

            ar.setFailMsg(GlobalConst.DATA_FAIL);

        }
        return  ar;
    }

    /**
     * 线路工程导出
     * @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 {
        LineProjectBean b = new LineProjectBean();
        b.setKeyWord(request.getParameter("keyword"));
        b.setOrgId(request.getParameter("orgId"));
        b.setVolLevelIds(request.getParameter("volLevelIds"));
        b.setStatusId(request.getParameter("statusId"));
        List<LineProjectBean> list = service.getFirmList(b);
        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        String[] excelHeader = {"序号","分公司","工程名称","工程简称","电压等级(KV)","线路长度(km)"
                ,"计划起止时间","计划结束时间","项目地址","项目部","项目状态"};
        int[] ds_format = {2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2};
        String fileName = "工程汇总清单";
        if (list != null) {
            int i = 0;
            for (LineProjectBean bean : list){
                i++;
                Map<String, Object> map = new HashMap<>(100);
                map.put("序号",i);
                map.put("分公司",bean.getBranchName());
                map.put("工程名称",bean.getTitle());
                map.put("工程简称",bean.getShortName());
                map.put("电压等级(KV)",bean.getVolLevel());
                map.put("线路长度(km)",bean.getLineLength());
                map.put("计划起止时间",bean.getStartTime());
                map.put("计划结束时间",bean.getEndTime());
                map.put("项目地址",bean.getProAddress());
                map.put("项目部",bean.getProName());
                String proStatus = "0".equals(bean.getProStatus()) ? "在建" : "已完工";
                map.put("项目状态", proStatus);
                mapList.add(map);
            }
        }
        try {
            ExcelUtils.export(fileName, fileName, excelHeader, excelHeader, ds_format, null, mapList, request,
                    response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @LogAnnotation
    @PostMapping("getPermissionList")
    @ApiOperation(value = "个人权限-列表")
    public R getPermissionList(){
        String id = UserUtil.getLoginUser().getId().toString();
        List<String> list = service.getPermissionList(id);
        return !list.isEmpty() ? R.okTable(list, list.size()):R.failTable("暂无数据");
    }



}
