package cn.estsh.i3plus.ext.mes.apiservice.controller.base.bu3;

import cn.estsh.i3plus.ext.mes.api.base.bu3.ISxAssistOutAndEnterService;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesAssistOutAndEnter;
import cn.estsh.i3plus.ext.mes.pojo.model.bu3.SxAssistOutAndEnterModel;
import cn.estsh.i3plus.ext.mes.pojo.model.bu3.SxAssistOutAndEnterReportModel;
import cn.estsh.i3plus.ext.mes.pojo.util.MesExtConstWords;
import cn.estsh.i3plus.ext.mes.pojo.util.MesExtEnumUtil;
import cn.estsh.i3plus.platform.common.exception.ImppExceptionEnum;
import cn.estsh.i3plus.platform.common.tool.TimeTool;
import cn.estsh.i3plus.platform.common.util.CommonConstWords;
import cn.estsh.i3plus.pojo.base.common.Pager;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.enumutil.ResourceEnumUtil;
import cn.estsh.impp.framework.base.controller.MesBaseController;
import cn.estsh.impp.framework.boot.auth.AuthUtil;
import cn.estsh.impp.framework.boot.exception.ImppBusiException;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
import cn.estsh.impp.framework.boot.util.ResultBean;
import cn.estsh.impp.framework.boot.util.ValidatorBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Calendar;
import java.util.Objects;

/**
 * @Author: wangjie
 * @CreateDate: 2021/01/19 15:37
 * @Description:
 **/
@RestController
@RequestMapping(CommonConstWords.BASE_URL_MES)
@Api(tags = "援交控制层")
public class SxAssistOutAndEnterController extends MesBaseController {

    @Autowired
    private ISxAssistOutAndEnterService assistOutAndEnterService;

    @GetMapping(value = "/sx-ext/assist-out-and-enter/query")
    @ApiOperation(value = "按条件分页查询援交信息")
    public ResultBean queryAssistOutAndEnterByPager(SxAssistOutAndEnterModel assistOutAndEnter, Pager pager) {
        try {
            assistOutAndEnter.setOrganizeCode(AuthUtil.getOrganize().getOrganizeCode());
            return ResultBean.success("查询成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode())
                    .setListPager(assistOutAndEnterService.queryAssistOutAndEnterByPager(assistOutAndEnter, pager));
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value = "/sx-ext/assist-out-and-enter/query-by-month-and-prod-technology")
    @ApiOperation(value = "根据月份查询责任部门为生成技术的援出信息 EAM获取MES数据")
    public ResultBean queryAssistOutListByMonthAndContainProdTechnology(@RequestParam("checkYearMonth") String checkYearMonth, @RequestParam("organizeCode") String organizeCode) {
        try {
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode())
                    .setResultList(assistOutAndEnterService.queryAssistOutListByMonthAndContainProdTechnology(checkYearMonth + MesExtConstWords.DATE_DD_01, TimeTool.timeCalc(TimeTool.stringParseToDate(checkYearMonth, MesExtConstWords.DATE_FORMAT_YM), Calendar.MONTH, 1, MesExtConstWords.DATE_FORMAT_YM) + MesExtConstWords.DATE_DD_01, organizeCode));
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value = "/sx-ext/assist-out-and-enter/query-by-time-interval")
    @ApiOperation(value = "根据时间区间查询责任部门为生成技术的援出信息 EAM获取MES数据2")
    public ResultBean queryAssistOutListByTimeInterval(
            @RequestParam("startTime") String startTime,
            @RequestParam("endTime") String endTime,
            @RequestParam("organizeCode") String organizeCode) {
        try {
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode())
                    .setResultList(assistOutAndEnterService.queryAssistOutListByMonthAndContainProdTechnology(startTime, endTime, organizeCode));
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value = "/sx-ext/assist-out-and-enter/query-by-workCenterCode")
    @ApiOperation(value = "根据月份查询责任部门为生成技术的援出信息 EAM获取MES数据")
    public ResultBean queryAssistOutListByMonthWorkCenterCode(@RequestParam("influenceDateStart") String influenceDateStart,
                                                              @RequestParam("influenceDateEnd")String influenceDateEnd,
                                                              @RequestParam("workCenterCode") String workCenterCode,
                                                              @RequestParam("organizeCode") String organizeCode) {
        try {
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode())
                    .setResultList(assistOutAndEnterService.queryAssistOutListByMonthWorkCenterCode( influenceDateStart,influenceDateEnd, workCenterCode,organizeCode));
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @PostMapping(value = "/sx-ext/assist-out-and-enter/insert")
    @ApiOperation(value = "新增援交信息")
    public ResultBean insertAssistOutAndEnter(MesAssistOutAndEnter assistOutAndEnter) {
        try {
            ValidatorBean.beginValid(assistOutAndEnter)
                    .notNull(MesExtConstWords.WORK_CENTER_CODE, assistOutAndEnter.getWorkCenterCode())
                    .notNull(MesExtConstWords.ASSIST_OUT_AND_ENTER_DETAIL, assistOutAndEnter.getAssistOutAndEnterDetail())
                    .notNull(MesExtConstWords.OWNER_DEPARTMENT, assistOutAndEnter.getOwnerDepartment())
                    .notNull(MesExtConstWords.WORK_CONTENT, assistOutAndEnter.getWorkContent())
                    .notNull(MesExtConstWords.START_TIME, assistOutAndEnter.getStartTime())
                    .notNull(MesExtConstWords.END_TIME, assistOutAndEnter.getEndTime())
                    .notNull(MesExtConstWords.INFLUENCE_NUMBER, assistOutAndEnter.getInfluenceNumber())
                    .notNull(MesExtConstWords.TAKE_ON, assistOutAndEnter.getTakeOn())
                    .notNull(MesExtConstWords.PERSON_RESPONSIBLE, assistOutAndEnter.getPersonResponsible())
                    .notNull(MesExtConstWords.RESPONSIBLE_MINISTER, assistOutAndEnter.getResponsibleMinister())
                    .notNull(MesExtConstWords.TAKE_ON_USER_NAME, assistOutAndEnter.getTakeOnUserName())
                    .notNull(MesExtConstWords.PERSON_RESPONSIBLE_USER_NAME, assistOutAndEnter.getPersonResponsibleUserName())
                    .notNull(MesExtConstWords.RESPONSIBLE_MINISTER_USER_NAME, assistOutAndEnter.getResponsibleMinisterUserName());

            assistOutAndEnter.setOrganizeCode(AuthUtil.getOrganize().getOrganizeCode());
            assistOutAndEnter.setCreateUser(AuthUtil.getSessionUser().getUserName());
            assistOutAndEnterService.insertAssistOutAndEnter(assistOutAndEnter);

            return ResultBean.success("新增成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @PostMapping(value = "/sx-ext/assist-out-and-enter/update")
    @ApiOperation(value = "更新援交信息")
    public ResultBean updateAssistOutAndEnter(SxAssistOutAndEnterModel assistOutAndEnter) {
        try {
            ValidatorBean.beginValid(assistOutAndEnter)
                    .notNull(MesExtConstWords.ID, assistOutAndEnter.getIdStr())
                    .notNull(MesExtConstWords.WORK_CENTER_CODE, assistOutAndEnter.getWorkCenterCode())
                    .notNull(MesExtConstWords.ASSIST_OUT_AND_ENTER_DETAIL, assistOutAndEnter.getAssistOutAndEnterDetail())
                    .notNull(MesExtConstWords.OWNER_DEPARTMENT, assistOutAndEnter.getOwnerDepartment())
                    .notNull(MesExtConstWords.WORK_CONTENT, assistOutAndEnter.getWorkContent())
                    .notNull(MesExtConstWords.START_TIME, assistOutAndEnter.getStartTime())
                    .notNull(MesExtConstWords.END_TIME, assistOutAndEnter.getEndTime())
                    .notNull(MesExtConstWords.INFLUENCE_NUMBER, assistOutAndEnter.getInfluenceNumber())
                    .notNull(MesExtConstWords.TAKE_ON, assistOutAndEnter.getTakeOn())
                    .notNull(MesExtConstWords.PERSON_RESPONSIBLE, assistOutAndEnter.getPersonResponsible())
                    .notNull(MesExtConstWords.RESPONSIBLE_MINISTER, assistOutAndEnter.getResponsibleMinister())
                    .notNull(MesExtConstWords.TAKE_ON_USER_NAME, assistOutAndEnter.getTakeOnUserName())
                    .notNull(MesExtConstWords.PERSON_RESPONSIBLE_USER_NAME, assistOutAndEnter.getPersonResponsibleUserName())
                    .notNull(MesExtConstWords.RESPONSIBLE_MINISTER_USER_NAME, assistOutAndEnter.getResponsibleMinisterUserName());

            assistOutAndEnter.setOrganizeCode(AuthUtil.getOrganize().getOrganizeCode());
            assistOutAndEnter.setModifyUser(AuthUtil.getSessionUser().getUserName());
            assistOutAndEnterService.updateAssistOutAndEnter(assistOutAndEnter);
            return ResultBean.success("修改成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @PutMapping(value = "/sx-ext/assist-out-and-enter/status-update")
    @ApiOperation(value = "根据id启用或禁用援交信息")
    public ResultBean updateAssistOutAndEnterValidById(String[] idStrArr, Integer status) {
        try {
            if (null == idStrArr) {
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail("请选择需要操作的资源。")
                        .build();
            }
            assistOutAndEnterService.updateAssistOutAndEnterValidById(idStrArr, status, AuthUtil.getSessionUser().getUserName());
            return ResultBean.success("修改成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @PutMapping(value = "/sx-ext/assist-out-and-enter/delete")
    @ApiOperation(value = "根据id删除援交信息")
    public ResultBean deleteAssistOutAndEnterById(String[] idStrArr) {
        try {
            if (null == idStrArr) {
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail("请选择需要操作的资源。")
                        .build();
            }
            assistOutAndEnterService.deleteAssistOutAndEnterById(idStrArr, AuthUtil.getSessionUser().getUserName());
            return ResultBean.success("删除成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @PutMapping(value = "/sx-ext/assist-out-and-enter/confirm")
    @ApiOperation(value = "根据id确认援交信息")
    public ResultBean doConfirmAssistOutAndEnterById(String[] idStrArr,Integer level,Integer liabilityAttribution) {
        try {
            ValidatorBean.checkNotNull(idStrArr, "请选择需要操作的资源");
            ValidatorBean.checkNotNull(level, "请选择确认的级别");

            if (MesExtEnumUtil.ASSIST_OUT_AND_ENTER_CONFIRM_LEVEL.valueOfDescription(level) == null) {
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail("请选择正确的确认级别！")
                        .build();
            }

            //担当确认完后需选择责任归属
            if (Objects.equals(MesExtEnumUtil.ASSIST_OUT_AND_ENTER_CONFIRM_LEVEL.TAKE_ON.getValue(), level)) ValidatorBean.checkNotNull(liabilityAttribution, "请选择责任归属");
            if (Objects.equals(MesExtEnumUtil.ASSIST_OUT_AND_ENTER_CONFIRM_LEVEL.TAKE_ON.getValue(), level) && liabilityAttribution != null && MesExtEnumUtil.LIABILITY_ATTRIBUTION.valueOfDescription(liabilityAttribution) == null) {
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail("请选择正确的责任归属！")
                        .build();
            }

            assistOutAndEnterService.doConfirmAssistOutAndEnterById(idStrArr, AuthUtil.getOrganize().getOrganizeCode(),
                    AuthUtil.getSessionUser().getUserName(), AuthUtil.getSessionUser().getUser().getUserLoginName(),level,liabilityAttribution);
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @PostMapping(value = "/sx-ext/assist-out-and-enter/report")
    @ApiOperation(value = "援交报表")
    public ResultBean doAssistOutAndEnterReport(@RequestBody SxAssistOutAndEnterReportModel data) {
        try {
            ValidatorBean.beginValid(data)
                    .notNull(MesExtConstWords.START_TIME, data.getStartTime())
                    .notNull(MesExtConstWords.END_TIME, data.getEndTime());
            data.setOrganizeCode(AuthUtil.getOrganize().getOrganizeCode());
            return ResultBean.success("查询成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode())
                    .setResultObject(assistOutAndEnterService.doAssistOutAndEnterReport(data));
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value = "/sx-ext/assist-out-and-enter/report-detail")
    @ApiOperation(value = "援交报表明细数据")
    public ResultBean queryAssistOutAndEnterReportDetailList(SxAssistOutAndEnterModel model) {
        try {
            model.setOrganizeCode(AuthUtil.getOrganize().getOrganizeCode());
            return ResultBean.success("查询成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode())
                    .setResultList(assistOutAndEnterService.queryAssistOutAndEnterReportDetailList(model));
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @PostMapping(value = "/sx-ext/assist-out-and-enter/report-download")
    @ApiOperation(value = "援交报表导出")
    public ResultBean doDownLoadAssistOutAndEnterReport(HttpServletResponse resp, @RequestBody SxAssistOutAndEnterReportModel data) {
        try {
            ValidatorBean.beginValid(data)
                    .notNull(MesExtConstWords.START_TIME, data.getStartTime())
                    .notNull(MesExtConstWords.END_TIME, data.getEndTime());
            data.setOrganizeCode(AuthUtil.getOrganize().getOrganizeCode());
            assistOutAndEnterService.doDownLoadAssistOutAndEnterReport(resp, data);
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

//    @PostMapping(value = "/sx-ext/assist-out-and-enter/hand-confirm-by-month")
//    @ApiOperation(value = "援交记录按月手动确认")
//    public ResultBean doAssistOutAndEnterAutoConfirm(String date) {
//        try {
//            if (!checkDate(date))
//                throw ImppExceptionBuilder.newInstance()
//                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
//                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
//                        .setErrorDetail("入参必要参数date[%s]异常,日期格式[%s]", date, MesExtConstWords.DATE_FORMAT_YM)
//                        .build();
//
//            Integer count = assistOutAndEnterService.doAssistOutAndEnterAutoConfirm(AuthUtil.getOrganize().getOrganizeCode(), AuthUtil.getSessionUser().getUserName(),
//                    date + MesExtConstWords.DATE_DD_01, TimeTool.timeCalc(TimeTool.stringParseToDate(date, MesExtConstWords.DATE_FORMAT_YM), Calendar.MONTH, 1, MesExtConstWords.DATE_FORMAT_YM) + MesExtConstWords.DATE_DD_01);
//            return ResultBean.success("操作成功").setResultObject(String.format("日期[%s]手动完成确认[%s]条援交记录", date, count)).setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
//        } catch (ImppBusiException busExcep) {
//            return ResultBean.fail(busExcep);
//        } catch (Exception e) {
//            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
//        }
//    }

    @PostMapping(value = "/sx-ext/assist-out-and-enter/report/responsible-minister-confirm")
    @ApiOperation(value = "援交报表部长确认")
    public ResultBean doReportResponsibleMinisterConfirm(@RequestBody SxAssistOutAndEnterReportModel data) {
        try {
            ValidatorBean.beginValid(data)
                    .notNull(MesExtConstWords.START_TIME, data.getStartTime())
                    .notNull(MesExtConstWords.END_TIME, data.getEndTime())
                    .notNull(MesExtConstWords.OWNER_DEPARTMENT_ARR, data.getOwnerDepartmentArr());
            data.setOrganizeCode(AuthUtil.getOrganize().getOrganizeCode());
            data.setUserLoginName(AuthUtil.getSessionUser().getUser().getUserLoginName());
            assistOutAndEnterService.doReportResponsibleMinisterConfirm(data);
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @PostMapping(value = "/sx-ext/assist-out-and-enter/auto-confirm-job")
    @ApiOperation(value = "援交job自动确认")
    public ResultBean autoConfirmJob(@RequestBody SxAssistOutAndEnterModel data) {
        try {
            String dateYm = TimeTool.getToday().substring(0, 7);
            data.setInfluenceDateStart(getBeforeMonthFirstDay(dateYm));
            data.setInfluenceDateEnd(dateYm+MesExtConstWords.DATE_DD_01);
            if (Objects.equals(data.getLevel(), MesExtEnumUtil.ASSIST_OUT_AND_ENTER_CONFIRM_LEVEL.TAKE_ON.getValue()) ||
                    Objects.equals(data.getLevel(), MesExtEnumUtil.ASSIST_OUT_AND_ENTER_CONFIRM_LEVEL.PERSON_IN_CHARGE.getValue())){
                data.setConfirm(false);
            }else if (Objects.equals(data.getLevel(), MesExtEnumUtil.ASSIST_OUT_AND_ENTER_CONFIRM_LEVEL.RESPONSIBLE_MINISTERGE.getValue())) {
                data.setResponsibleMinistergeConfirmBool(false);
            }
            assistOutAndEnterService.doAssistOutAndEnterAutoConfirm(data);
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    private String getBeforeMonthFirstDay(String dateYm) {
        return TimeTool.timeCalc(TimeTool.stringParseToDate(dateYm, MesExtConstWords.DATE_FORMAT_YM), Calendar.MONTH, -1, MesExtConstWords.DATE_FORMAT_YM) + MesExtConstWords.DATE_DD_01;
    }




    private Boolean checkDate(String date) {
        if (StringUtils.isEmpty(date)) return false;
        if (!TimeTool.checkDateFormat(date, MesExtConstWords.DATE_FORMAT_YM)) return false;
        return true;
    }

}
