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.model.LoginUser;
import com.ozs.common.enums.BusinessType;
import com.ozs.common.enums.DataIsDelete;
import com.ozs.common.utils.DateUtils;
import com.ozs.common.utils.PageUtils;
import com.ozs.common.utils.poi.ExcelUtil;
import com.ozs.framework.web.service.TokenService;
import com.ozs.plan.doman.PlanQuarter;
import com.ozs.plan.doman.vo.requestVo.PlanQuarterStandardVo;
import com.ozs.plan.doman.vo.responseVo.PlanQuarterResponseVo;
import com.ozs.plan.service.PlanQuarterService;
import com.ozs.plan.service.impl.PlanQuarterServiceImpl;
import com.ozs.system.service.ISysDeptService;
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.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 季度计划信息控制层
 *
 * @author buzhanyi
 */
@Api(tags = "季度计划")
@RestController
@Slf4j
@RequestMapping("/plan/quarter")
public class PlanQuarterController extends BaseController {
    @Autowired
    private PlanQuarterService quarterService;
    @Autowired
    private PlanQuarterServiceImpl quarterServiceImpl;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private ISysDeptService iSysDeptService;

    @ApiOperation(value = "查询季度计划")
    @PostMapping("/list")
    @Log(title = ModularConstans.planQuarter, businessType = BusinessType.QUERY)
    @PreAuthorize("@ss.hasPermi('plan:quarter:list')")
    public AjaxResult list(@RequestBody PlanQuarterStandardVo vo, HttpServletRequest request) {
        List<PlanQuarterResponseVo> planQuarterList = new ArrayList<>();
        try {
            LoginUser loginUser = tokenService.getLoginUser(request);
            LambdaQueryWrapper<PlanQuarter> lw = new LambdaQueryWrapper<>();
            if (!loginUser.getUserId().equals(Long.valueOf("1"))) {
                lw.eq(PlanQuarter::getPurchaseDeptId, loginUser.getDeptId());
            }
            lw.eq(PlanQuarter::getPlanType, "0");
            lw.eq(PlanQuarter::getDelFlay, DataIsDelete.DataNOTDelete.getCode());
            if (!ObjectUtils.isEmpty(vo.getProjectName())) {
                lw.like(PlanQuarter::getProjectName, vo.getProjectName());
            }
            if (!ObjectUtils.isEmpty(vo.getPurchaseServices())) {
                lw.eq(PlanQuarter::getPurchaseServices, vo.getPurchaseServices());
            }
            if (!ObjectUtils.isEmpty(vo.getProjectStatus())) {
                lw.eq(PlanQuarter::getProjectStatus, vo.getProjectStatus());
            }
            if (!ObjectUtils.isEmpty(vo.getParams())) {
                if (!ObjectUtils.isEmpty(vo.getParams().get("beginTime"))) {
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM");
                    Date ofMonth = dateFormat.parse(vo.getParams().get("beginTime").toString() + "-01");
                    lw.ge(PlanQuarter::getPlanDemandSubTime, ofMonth);
                }
                if (!ObjectUtils.isEmpty(vo.getParams().get("endTime"))) {
                    SimpleDateFormat dateFormaH = new SimpleDateFormat("yyyy-MM");
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    SimpleDateFormat dateFormatT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
                    Date ofMonth = DateUtils.getLastDayOfMonth(dateFormaH.parse(vo.getParams().get("endTime").toString()));
                    Date parse = dateFormatT.parse(dateFormat.format(ofMonth) + " 23:59:59:999");
                    lw.le(PlanQuarter::getPlanDemandSubTime, parse);
                }
            }
            lw.orderBy(true, false, PlanQuarter::getCreateTime);
            List<PlanQuarter> list = quarterService.list(lw);
            planQuarterList = quarterServiceImpl.changeTo(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Page pages = PageUtils.getPages(vo.getPageNum().intValue(), vo.getPageSize().intValue(), planQuarterList);

        return AjaxResult.success(pages);
    }

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

    @ApiOperation(value = "导出季度计划数据")
    @Log(title = ModularConstans.planQuarter, businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('plan:quarter:exportPlan')")
    @PostMapping("/exportPlan")
    public void exportPlan(HttpServletResponse response, @RequestBody PlanQuarterStandardVo quarterStandardVo, HttpServletRequest request) throws Exception {
        LoginUser loginUser = tokenService.getLoginUser(request);
        List<PlanQuarterResponseVo> list = quarterService.selectPlanQuarterListEXP(quarterStandardVo, loginUser);
        ExcelUtil<PlanQuarterResponseVo> util = new ExcelUtil<>(PlanQuarterResponseVo.class);
        util.exportExcel(response, list, "季度计划数据");
    }

    @ApiOperation(value = "导出季度计划数据(审核单位)")
    @PostMapping("/exportPlanExamine")
    @PreAuthorize("@ss.hasPermi('plan:quarter:exportPlanExamine')")
    @Log(title = ModularConstans.planQuarter, businessType = BusinessType.EXPORT)
    public void exportPlanExamine(HttpServletResponse response, @RequestBody PlanQuarterStandardVo quarterStandardVo, HttpServletRequest request) throws Exception {
        LoginUser loginUser = tokenService.getLoginUser(request);
        List<PlanQuarterResponseVo> list = quarterService.selectPlanQuarterExamineListEXP(quarterStandardVo, loginUser);
        ExcelUtil<PlanQuarterResponseVo> util = new ExcelUtil<>(PlanQuarterResponseVo.class);
        util.exportExcel(response, list, "季度计划数据(审核单位)");
    }

    @ApiOperation(value = "创建季度计划")
    @PostMapping("/add")
    @PreAuthorize("@ss.hasPermi('plan:quarter:add')")
    @Log(title = ModularConstans.planQuarter, businessType = BusinessType.INSERT)
    public AjaxResult add(@RequestBody PlanQuarterStandardVo quarterStandardVo, HttpServletRequest request) {
        //获取采购单位-
        LoginUser loginUser = tokenService.getLoginUser(request);
        quarterStandardVo.setPurchaseDeptId(String.valueOf(loginUser.getDeptId()));
        quarterStandardVo.setCreated(String.valueOf(loginUser.getUserId()));
        return quarterService.insertPlanQuarter(quarterStandardVo);
    }

    @ApiOperation(value = "修改季度计划")
    @PostMapping("/update")
    @PreAuthorize("@ss.hasPermi('plan:quarter:update')")
    @Log(title = ModularConstans.planQuarter, businessType = BusinessType.UPDATE)
    public AjaxResult update(@RequestBody PlanQuarterStandardVo quarterStandardVo, HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        quarterStandardVo.setUpdated(String.valueOf(loginUser.getUserId()));
        return quarterService.update(quarterStandardVo);
    }

    @ApiOperation(value = "提交季度计划")
    @PostMapping("/commit")
    //@PreAuthorize("@ss.hasPermi('plan:quarter:commit')")
    @Log(title = ModularConstans.planQuarter, businessType = BusinessType.UPDATE)
    public AjaxResult commit(@RequestBody PlanQuarterStandardVo quarterStandardVo) {
        return quarterService.commit(quarterStandardVo);
    }

    @ApiOperation(value = "删除季度计划")
    @PostMapping("/delete")
    @PreAuthorize("@ss.hasPermi('plan:quarter:delete')")
    @Log(title = ModularConstans.planQuarter, businessType = BusinessType.DELETE)
    public AjaxResult delete(@RequestBody PlanQuarterStandardVo quarterStandardVo) {
        return quarterService.deletePlanQuarterById(quarterStandardVo.getPlanPracticalId());
    }

    @ApiOperation(value = "根据id获取季度计划信息")
    @PostMapping("/view")
    //@PreAuthorize("@ss.hasPermi('plan:quarter:view')")
    @Log(title = ModularConstans.planQuarter, businessType = BusinessType.QUERY)
    public AjaxResult view(@RequestBody PlanQuarterStandardVo quarterStandardVo) {
        return quarterService.view(quarterStandardVo);
    }

    @ApiOperation(value = "审核季度计划通过")
    @PostMapping("/reviewTo")
    //@PreAuthorize("@ss.hasPermi('plan:quarter:reviewTo')")
    @Log(title = ModularConstans.planQuarter, businessType = BusinessType.UPDATE)
    public AjaxResult reviewTo(@RequestBody PlanQuarterStandardVo quarterStandardVo, HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        quarterStandardVo.setUpdated(String.valueOf(loginUser.getUserId()));
        return quarterService.reviewTo(quarterStandardVo);
    }

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

    @ApiOperation(value = "申请修改季度计划")
    @PostMapping("/appUpdate")
    @PreAuthorize("@ss.hasPermi('plan:quarter:appUpdate')")
    @Log(title = ModularConstans.planQuarter, businessType = BusinessType.UPDATE)
    public AjaxResult appUpdate(@RequestBody PlanQuarterStandardVo quarterStandardVo) {
        return quarterService.appUpdate(quarterStandardVo);
    }

    @ApiOperation(value = "处理申请修改季度计划（或临时计划）")
    @PostMapping("/handleAppUpdate")
    @PreAuthorize("@ss.hasPermi('plan:quarter:handleAppUpdate')")
    @Log(title = ModularConstans.planQuarter, businessType = BusinessType.UPDATE)
    public AjaxResult handleAppUpdate(@RequestBody PlanQuarterStandardVo quarterStandardVo) {
        return quarterService.handleAppUpdate(quarterStandardVo);
    }

    @ApiOperation(value = "申请撤销季度计划")
    @PostMapping("/appDelete")
    @PreAuthorize("@ss.hasPermi('plan:quarter:appDelete')")
    @Log(title = ModularConstans.planYear, businessType = BusinessType.UPDATE)
    public AjaxResult appDelete(@RequestBody PlanQuarterStandardVo quarterStandardVo) {
        return quarterService.appDelete(quarterStandardVo);
    }

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

    @ApiOperation(value = "发函催告")
    @PostMapping("/sendLetter")
    //@PreAuthorize("@ss.hasPermi('plan:quarter:sendLetter')")
    @Log(title = ModularConstans.planQuarter, businessType = BusinessType.UPDATE)
    public AjaxResult sendLetter(@RequestBody PlanQuarterStandardVo quarterStandardVo) {
        return quarterService.sendLetter(quarterStandardVo);
    }

    @ApiOperation(value = "上传计划关联文件后保存文件信息")
    @PostMapping("/upLoadPlanFile")
    @PreAuthorize("@ss.hasPermi('plan:quarter:upLoadPlanFile')")
    @Log(title = ModularConstans.planQuarter, businessType = BusinessType.OTHER)
    public AjaxResult upLoadPlanFile(@RequestBody PlanQuarterStandardVo quarterStandardVo) {
        return quarterService.upLoadPlanFile(quarterStandardVo);
    }

    //季度计划不能自己创建
    //@ApiOperation(value = "导入季度计划数据")
    //@PostMapping("/importData")
    //@PreAuthorize("@ss.hasPermi('plan:quarter:importData')")
    //@Log(title = ModularConstans.planQuarter, businessType = BusinessType.INSERT)
    //public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
    //    ExcelUtil<PlanQuarterStandardVo> util = new ExcelUtil<>(PlanQuarterStandardVo.class);
    //    List<PlanQuarterStandardVo> quarter = util.importExcel(file.getInputStream());
    //    //获取采购单位-
    //    LoginUser loginUser = getLoginUser();
    //    String message = quarterService.importPlanQuarter(quarter, updateSupport, loginUser);
    //    return success(message);
    //}

    //季度计划不能进行导入
    //@ApiOperation("模板下载")
    //@GetMapping("/downloaExcel")
    //public void downloadZip(HttpServletResponse response) {
    //    try {
    //        InputStream resourceAsStream = this.getClass().getResourceAsStream("/template/planQuarter.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 = "导入年度计划数据")
    @PostMapping("/importPlanYearsData")
    @PreAuthorize("@ss.hasPermi('plan:quarter:importPlanYearsData')")
    @Log(title = ModularConstans.planQuarter, businessType = BusinessType.INSERT)
    public AjaxResult importPlanYearsData(@RequestBody List<Long> planYearIds) throws Exception {
        if (ObjectUtils.isEmpty(planYearIds)) {
            return error("请选择要创建的计划！");
        }
        return quarterService.importPlanYearsData(planYearIds);
    }

}
