package com.ozs.web.controller.plan;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ozs.common.annotation.Log;
import com.ozs.common.constant.ModularConstans;
import com.ozs.common.core.controller.BaseController;
import com.ozs.common.core.domain.AjaxResult;
import com.ozs.common.core.domain.entity.SysDept;
import com.ozs.common.core.domain.model.LoginUser;
import com.ozs.common.enums.BusinessType;
import com.ozs.common.enums.DataIsDelete;
import com.ozs.common.exception.ServiceException;
import com.ozs.common.exception.base.BaseException;
import com.ozs.common.core.domain.entity.SysProcurementStandard;
import com.ozs.common.utils.DateUtils;
import com.ozs.common.utils.PageUtils;
import com.ozs.common.utils.StringUtils;
import com.ozs.common.utils.file.FileUtils;
import com.ozs.common.utils.poi.ExcelUtil;
import com.ozs.framework.web.service.TokenService;
import com.ozs.plan.doman.PlanYears;
import com.ozs.plan.doman.vo.requestVo.PlanYearsStandardVo;
import com.ozs.plan.doman.vo.responseVo.PlanYearsResponseVo;
import com.ozs.plan.service.PlanYearsService;
import com.ozs.plan.service.impl.PlanYearsServiceImpl;
import com.ozs.pm.doman.PmAuditDeptRef;
import com.ozs.system.service.ISysDeptService;
import com.ozs.system.service.SysProcurementStandardService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.ObjectUtils;
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.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 年度计划信息控制层
 *
 * @author buzhanyi
 */
@Api(tags = "年度计划")
@Slf4j
@RestController
@RequestMapping("/plan/planYears")
public class PlanYearsController extends BaseController {
    @Autowired
    private PlanYearsService planYearsService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private ISysDeptService iSysDeptService;
    @Autowired
    private SysProcurementStandardService sysProcurementStandardService;


    @ApiOperation(value = "查询年度计划")
    @PostMapping("/list")
    @PreAuthorize("@ss.hasPermi('plan:planYears:list')")
    @Log(title = ModularConstans.planYear, businessType = BusinessType.QUERY)
    public AjaxResult list(@RequestBody PlanYearsStandardVo vo, HttpServletRequest request) {
        List<PlanYearsResponseVo> planYearsList = new ArrayList<>();
        try {
            LambdaQueryWrapper<PlanYears> lw = new LambdaQueryWrapper<PlanYears>();
            LoginUser loginUser = tokenService.getLoginUser(request);
            if (!loginUser.getUserId().equals(Long.valueOf("1"))) {
                lw.eq(PlanYears::getPurchaseDeptId, loginUser.getDeptId());
            }
            if (!ObjectUtils.isEmpty(vo.getProjectName())) {
                lw.like(PlanYears::getProjectName, vo.getProjectName());
            }
            if (!ObjectUtils.isEmpty(vo.getPurchaseServices())) {
                lw.eq(PlanYears::getPurchaseServices, vo.getPurchaseServices());
            }
            if (!ObjectUtils.isEmpty(vo.getProjectStatus())) {
                lw.eq(PlanYears::getProjectStatus, vo.getProjectStatus());
            }
            if (!ObjectUtils.isEmpty(vo.getBeginTime())) {
                lw.ge(PlanYears::getPlanDemandSubTime, vo.getBeginTime());
            }
            if (!ObjectUtils.isEmpty(vo.getEndTime())) {
                Date ofMonth = DateUtils.getLastDayOfMonth(vo.getEndTime());
                SimpleDateFormat dateFormatT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                Date parse = dateFormatT.parse(dateFormat.format(ofMonth) + " 23:59:59:999");
                lw.le(PlanYears::getPlanDemandSubTime, parse);
            }
            lw.eq(PlanYears::getDelFlay, DataIsDelete.DataNOTDelete.getCode());
            lw.orderBy(true, false, PlanYears::getCreateTime);
            List<PlanYears> planYears = planYearsService.list(lw);
            planYearsList = planYearsService.changeTo(planYears);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Page pages = PageUtils.getPages(vo.getPageNum().intValue(), vo.getPageSize().intValue(), planYearsList);

        return AjaxResult.success(pages);
    }

    @ApiOperation(value = "审核单位查询年度计划")
    @PostMapping("/examineList")
    @PreAuthorize("@ss.hasPermi('plan:planYears:examineList')")
    @Log(title = ModularConstans.planYear, businessType = BusinessType.QUERY)
    public AjaxResult examineList(@RequestBody PlanYearsStandardVo vo, HttpServletRequest request) {
        List<PlanYearsResponseVo> planYearsList = new ArrayList<>();
        try {
            LoginUser loginUser = tokenService.getLoginUser(request);
            vo.setPurchaseDeptId(String.valueOf(loginUser.getDeptId()));
            vo.setCreated(String.valueOf(loginUser.getUserId()));
            List<PlanYears> planYears = planYearsService.queryPage(vo);
            if (!ObjectUtils.isEmpty(planYears) && !ObjectUtils.isEmpty(planYears.size())) {
                planYearsList = planYearsService.changeTo(planYears);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        Page pages = PageUtils.getPages(vo.getPageNum().intValue(), vo.getPageSize().intValue(), planYearsList);
        return AjaxResult.success(pages);
    }

    @ApiOperation(value = "导出年度计划数据")
    @PostMapping("/exportPlan")
    @PreAuthorize("@ss.hasPermi('plan:planYears:exportPlan')")
    @Log(title = ModularConstans.planYear, businessType = BusinessType.EXPORT)
    public void exportPlan(HttpServletResponse response, @RequestBody PlanYearsStandardVo yearsStandardVo, HttpServletRequest request) throws Exception {
        LoginUser loginUser = tokenService.getLoginUser(request);
        List<PlanYearsResponseVo> list = planYearsService.selectPlanYearsListEXP(yearsStandardVo, loginUser);
        ExcelUtil<PlanYearsResponseVo> util = new ExcelUtil<>(PlanYearsResponseVo.class);
        util.exportExcel(response, list, "年度计划数据");
    }

    @ApiOperation(value = "导出年度计划数据(审核单位)")
    @PreAuthorize("@ss.hasPermi('plan:planYears:exportPlanExamine')")
    @PostMapping("/exportPlanExamine")
    @Log(title = ModularConstans.planYear, businessType = BusinessType.EXPORT)
    public void exportPlanExamine(HttpServletResponse response, @RequestBody PlanYearsStandardVo yearsStandardVo, HttpServletRequest request) throws Exception {
        LoginUser loginUser = tokenService.getLoginUser(request);
        List<PlanYearsResponseVo> list = planYearsService.selectPlanYearsExamineListEXP(yearsStandardVo, loginUser);
        ExcelUtil<PlanYearsResponseVo> util = new ExcelUtil<>(PlanYearsResponseVo.class);
        util.exportExcel(response, list, "年度计划数据(审核单位)");
    }

    @ApiOperation(value = "创建年度计划")
    @PostMapping("/add")
    @PreAuthorize("@ss.hasPermi('plan:planYears:add')")
    @Log(title = ModularConstans.planYear, businessType = BusinessType.INSERT)
    public AjaxResult add(@RequestBody PlanYearsStandardVo yearsStandardVo, HttpServletRequest request) {
        //获取采购单位-
        LoginUser loginUser = tokenService.getLoginUser(request);
        yearsStandardVo.setPurchaseDeptId(String.valueOf(loginUser.getDeptId()));
        yearsStandardVo.setCreated(String.valueOf(loginUser.getUserId()));
        return planYearsService.insertPlanYears(yearsStandardVo);
    }

    @ApiOperation(value = "修改年度计划")
    @PostMapping("/update")
    @PreAuthorize("@ss.hasPermi('plan:planYears:update')")
    @Log(title = ModularConstans.planYear, businessType = BusinessType.UPDATE)
    public AjaxResult update(@RequestBody PlanYearsStandardVo yearsStandardVo, HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        yearsStandardVo.setPurchaseDeptId(String.valueOf(loginUser.getDeptId()));
        yearsStandardVo.setUpdated(String.valueOf(loginUser.getUserId()));
        return planYearsService.update(yearsStandardVo);
    }

    @ApiOperation(value = "提交年度计划")
    @PostMapping("/commit")
    @PreAuthorize("@ss.hasPermi('plan:planYears:commit')")
    @Log(title = ModularConstans.planYear, businessType = BusinessType.UPDATE)
    public AjaxResult commit(@RequestBody PlanYearsStandardVo yearsStandardVo) {
        return planYearsService.commit(yearsStandardVo);
    }

    @ApiOperation(value = "删除年度计划")
    @PostMapping("/delete")
    @PreAuthorize("@ss.hasPermi('plan:planYears:delete')")
    @Log(title = ModularConstans.planYear, businessType = BusinessType.DELETE)
    public AjaxResult delete(@RequestBody PlanYearsStandardVo yearsStandardVo) {
        return planYearsService.deletePlanYearsById(yearsStandardVo.getPlanYearId());
    }

    @ApiOperation(value = "根据id获取年度计划信息")
    @PostMapping("/view")
//    @PreAuthorize("@ss.hasPermi('plan:planYears:view')")   首页调用的接口不需要权限
    @Log(title = ModularConstans.planYear, businessType = BusinessType.QUERY)
    public AjaxResult view(@RequestBody PlanYearsStandardVo yearsStandardVo) {
        return planYearsService.view(yearsStandardVo);
    }

    @ApiOperation(value = "填写采购服务站")
    @PostMapping("/adPurchaseServices")
    //@PreAuthorize("@ss.hasPermi('plan:planYears:adPurchaseServices')")
    @Log(title = ModularConstans.planYear, businessType = BusinessType.UPDATE)
    public AjaxResult adPurchaseServices(@RequestBody PlanYearsStandardVo yearsStandardVo) {
        return planYearsService.adPurchaseServices(yearsStandardVo);
    }

    @ApiOperation(value = "审核年度计划通过")
    @PostMapping("/reviewTo")
    @Log(title = ModularConstans.planYear, businessType = BusinessType.UPDATE)
//    @PreAuthorize("@ss.hasPermi('plan:planYears:reviewTo')")  首页调用注释
    public AjaxResult reviewTo(@RequestBody PlanYearsStandardVo yearsStandardVo, HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        yearsStandardVo.setUpdated(String.valueOf(loginUser.getUserId()));
        return planYearsService.reviewTo(yearsStandardVo);
    }

    @ApiOperation(value = "审核年度计划退回")
    @PostMapping("/reviewReturn")
    @PreAuthorize("@ss.hasPermi('plan:planYears:reviewReturn')")
    @Log(title = ModularConstans.planYear, businessType = BusinessType.UPDATE)
    public AjaxResult reviewReturn(@RequestBody PlanYearsStandardVo yearsStandardVo, HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        yearsStandardVo.setUpdated(String.valueOf(loginUser.getUserId()));
        return planYearsService.reviewReturn(yearsStandardVo);
    }

    @ApiOperation(value = "申请修改年度计划")
    @PostMapping("/appUpdate")
    @PreAuthorize("@ss.hasPermi('plan:planYears:appUpdate')")
    @Log(title = ModularConstans.planYear, businessType = BusinessType.UPDATE)
    public AjaxResult appUpdate(@RequestBody PlanYearsStandardVo yearsStandardVo) {
        return planYearsService.appUpdate(yearsStandardVo);
    }

    @ApiOperation(value = "申请撤销年度计划")
    @PostMapping("/appDelete")
    @PreAuthorize("@ss.hasPermi('plan:planYears:appDelete')")
    @Log(title = ModularConstans.planYear, businessType = BusinessType.UPDATE)
    public AjaxResult appDelete(@RequestBody PlanYearsStandardVo yearsStandardVo) {
        return planYearsService.appDelete(yearsStandardVo);
    }

    @ApiOperation(value = "处理申请撤销年度计划")
    @PostMapping("/handleApp")
    @PreAuthorize("@ss.hasPermi('plan:planYears:handleApp')")
    @Log(title = ModularConstans.planYear, businessType = BusinessType.UPDATE)
    public AjaxResult handleApp(@RequestBody PlanYearsStandardVo yearsStandardVo) {
        return planYearsService.handleApp(yearsStandardVo);
    }

    @ApiOperation(value = "发函催告")
    @PostMapping("/sendLetter")
//    @PreAuthorize("@ss.hasPermi('plan:planYears:sendLetter')")   首页调用注释
    @Log(title = ModularConstans.planYear, businessType = BusinessType.UPDATE)
    public AjaxResult sendLetter(@RequestBody PlanYearsStandardVo yearsStandardVo) {
        return planYearsService.sendLetter(yearsStandardVo);
    }

    @ApiOperation(value = "上传计划关联文件后保存文件信息")
    @PostMapping("/upLoadPlanFile")
    @PreAuthorize("@ss.hasPermi('plan:planYears:upLoadPlanFile')")
    @Log(title = ModularConstans.planYear, businessType = BusinessType.OTHER)
    public AjaxResult upLoadPlanFile(@RequestBody PlanYearsStandardVo yearsStandardVo) {
        return planYearsService.upLoadPlanFile(yearsStandardVo);
    }
    //
    //@ApiOperation(value = "下载计划关联文件")
    //@PostMapping("/downLoadPlanFile")
    //public AjaxResult downLoadPlanFile(@RequestBody PlanYearsStandardVo yearsStandardVo) {
    //    return planYearsService.downLoadPlanFile(yearsStandardVo);

    @ApiOperation(value = "导入年度计划数据")
    @PostMapping("/importData")
    @PreAuthorize("@ss.hasPermi('plan:planYears:importData')")
    @Log(title = ModularConstans.planYear, businessType = BusinessType.INSERT)
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<PlanYearsStandardVo> util = new ExcelUtil<>(PlanYearsStandardVo.class);
        List<PlanYearsStandardVo> planYears = util.importExcel(file.getInputStream());
        //获取采购单位-
        LoginUser loginUser = getLoginUser();
        String message = planYearsService.importPlanYears(planYears, updateSupport, loginUser);
        return success(message);
    }

    @ApiOperation(value = "系统首页计划管理")
    @GetMapping("/planYearsTotal")
    @PreAuthorize("@ss.hasPermi('plan:planYears:planYearsTotal')")
    @Log(title = ModularConstans.planYear, businessType = BusinessType.QUERY)
    public AjaxResult planYearsTotal() {
        return success(planYearsService.count());
    }

    @ApiOperation("模板下载")
    @GetMapping("/downloaExcel")
    public void downloadZip(HttpServletResponse response) {
        try {
            InputStream resourceAsStream = this.getClass().getResourceAsStream("/template/planYears.xlsx");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, "年度计划导入模板.xlsx");
            FileUtils.writeBytesByInput(resourceAsStream, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    @ApiOperation(value = "获取采购服务站")
    @GetMapping("/getProcurementService")
    @Log(title = ModularConstans.planYear, businessType = BusinessType.QUERY)
    public AjaxResult getProcurementService(@RequestParam("projectType") String projectType,
                                            @RequestParam("evaluation") BigDecimal evaluation) {
        //获取当前登录人的部门ID
        LoginUser loginUser = getLoginUser();
        List<String> list = new ArrayList<>();
        list.add("网空采购站");
        if (StringUtils.isNull(loginUser) || StringUtils.isNull(loginUser.getDeptId())) {
            return error("当前登陆过期，请重新登录！");
        }
        Long deptId = loginUser.getDeptId();
        // 获取当前登陆人的部门名称
        SysDept sysDept = iSysDeptService.selectById(deptId);
        if (StringUtils.isNull(sysDept) || StringUtils.isNull(sysDept.getDeptName())) {
            return error("当前登陆人没有部门信息，请核对数据！");
        }

        String str = sysDept.getPurchaseServices();
        if (!ObjectUtils.isEmpty(evaluation) && !ObjectUtils.isEmpty(projectType)) {
            String[] ancestors = sysDept.getAncestors().split(",");
            //当前用户的部门，是否允许提交（不在规定等级范围不可提交）
            //查询当前用户的部门是否有上级，是否需要上级及祖级进行审核
            Long cdeptId = null;
            Long bdeptId = null;
            String deptLevel = null;
            if (ancestors.length == 2) { //C级
                deptLevel = "C";
            } else if (ancestors.length == 3) { //B级
                deptLevel = "B";
                cdeptId = Long.valueOf(ancestors[2]);
            } else if (ancestors.length == 4) { //A级
                deptLevel = "A";
                cdeptId = Long.valueOf(ancestors[2]);
                bdeptId = Long.valueOf(ancestors[3]);
            }
            if (!Arrays.asList("A", "B", "C").contains(deptLevel)) {
                return success(list);
            }

            switch (deptLevel) {
                case "A":
                    LambdaQueryWrapper<SysProcurementStandard> queryWrapperA = new LambdaQueryWrapper<>();
                    queryWrapperA.eq(SysProcurementStandard::getDeptId, deptId);
                    queryWrapperA.eq(SysProcurementStandard::getCategory, projectType.equals("2") ? "1" : projectType.equals("1") ? "2" : projectType);
                    List<SysProcurementStandard> sysProcurementStandardsListA = sysProcurementStandardService.list(queryWrapperA);
                    if (ObjectUtils.isEmpty(sysProcurementStandardsListA)) {
                        throw new ServiceException("部门id为" + deptId + "的部门采购标准未进行初始化！");
                    }
                    //A不限额就自己审核
                    SysProcurementStandard sA = sysProcurementStandardsListA.get(0);
                    if (sA.getState().equals(Integer.valueOf(0))) {
                        //采用初始化数据
                    } else {
                        //A限额了判断是否超额，不超额就自己审。超额了追加上级
                        BigDecimal maximum = sA.getMaximum();
                        if (maximum.compareTo(evaluation) == 1) {
                            //采用初始化数据
                        } else {
                            //A限额了，找B
                            SysDept b = iSysDeptService.selectById(bdeptId);
                            LambdaQueryWrapper<SysProcurementStandard> queryWrapperB = new LambdaQueryWrapper<>();
                            queryWrapperB.eq(SysProcurementStandard::getDeptId, bdeptId);
                            queryWrapperB.eq(SysProcurementStandard::getCategory, projectType.equals("2") ? "1" : projectType.equals("1") ? "2" : projectType);
                            List<SysProcurementStandard> sysProcurementStandardsListB = sysProcurementStandardService.list(queryWrapperB);
                            //B不限额，B审
                            if (ObjectUtils.isEmpty(sysProcurementStandardsListB)) {
                                throw new ServiceException("部门id为" + bdeptId + "的部门采购标准未进行初始化！");
                            }
                            SysProcurementStandard sB = sysProcurementStandardsListB.get(0);
                            if (sB.getState().equals(Integer.valueOf(0))) {
                                //refB采用初始化数据

                                str = b.getPurchaseServices();
                            } else {
                                //B限额了判断是否超额，不超额就自己审。超额了追加C级
                                str = b.getPurchaseServices();
                                BigDecimal maximumB = sB.getMaximum();
                                //B超额
                                if (maximumB.compareTo(evaluation) == -1) {
                                    SysDept c = iSysDeptService.selectById(cdeptId);
                                    str = c.getPurchaseServices();
                                }
                            }
                        }
                    }
                    break;
                case "B":
                    // B的判断  最少插入1条。最多插入2条
                    SysDept b = iSysDeptService.selectById(deptId);
                    LambdaQueryWrapper<SysProcurementStandard> queryWrapperB = new LambdaQueryWrapper<>();
                    queryWrapperB.eq(SysProcurementStandard::getDeptId, deptId);
                    queryWrapperB.eq(SysProcurementStandard::getCategory, projectType.equals("2") ? "1" : projectType.equals("1") ? "2" : projectType);
                    List<SysProcurementStandard> sysProcurementStandardsListB = sysProcurementStandardService.list(queryWrapperB);
                    //B不限额，B审
                    if (ObjectUtils.isEmpty(sysProcurementStandardsListB)) {
                        throw new ServiceException("部门id为" + deptId + "的部门采购标准未进行初始化！");
                    }
                    SysProcurementStandard sB = sysProcurementStandardsListB.get(0);
                    if (sB.getState() == 0) {

                        str = b.getPurchaseServices();
                    } else {
                        //B限额了判断是否超额，不超额就自己审。超额了追加C级
                        BigDecimal maximumB = sB.getMaximum();
                        //B不超额B审
                        if (maximumB.compareTo(evaluation) == 1) {
                            str = b.getPurchaseServices();
                        } else {
                            SysDept c = iSysDeptService.selectById(cdeptId);
                            str = c.getPurchaseServices();
                        }
                    }

                    break;
                default:
                    SysDept c = iSysDeptService.selectById(deptId);
                    str = c.getPurchaseServices();

            }
        }

        if (!org.apache.commons.lang3.StringUtils.isBlank(str)) {
            list.add(str);
        }
        return success(list);
    }
}
