package org.jeecg.modules.flowpath.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.flowpath.convert.FlowPathConvert;
import org.jeecg.modules.flowpath.dto.ItdmCreateRunFlowPath;
import org.jeecg.modules.flowpath.entity.ItdmFlowPathStep;
import org.jeecg.modules.flowpath.entity.ItdmRunFlowPath;
import org.jeecg.modules.flowpath.entity.ItdmRunFlowPathStep;
import org.jeecg.modules.flowpath.service.IItdmFlowPathService;
import org.jeecg.modules.flowpath.service.IItdmFlowPathStepService;
import org.jeecg.modules.flowpath.service.IItdmRunFlowPathService;
import org.jeecg.modules.flowpath.service.IItdmRunFlowPathStepService;
import org.jeecg.modules.flowpath.vo.ItdmRunFlowPathInfoVO;
import org.jeecg.modules.flowpath.vo.ItdmRunFlowPathStepVO;
import org.jeecg.modules.itdmFirstPage.entity.ItdmTask;
import org.jeecg.modules.itdmFirstPage.service.IItdmTaskService;
import org.jeecg.modules.system.service.impl.SysBaseApiImpl;
import org.jeecg.modules.weituo.entity.ItdmWeituoInfo;
import org.jeecg.modules.weituo.service.IItdmWeituoInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 运行流程表
 * @Author: jeecg-boot
 * @Date: 2023-07-20
 * @Version: V1.0
 */
@Api(tags = "运行流程表")
@RestController
@RequestMapping("/flowpath/itdmRunFlowPath")
@Slf4j
public class ItdmRunFlowPathController extends JeecgController<ItdmRunFlowPath, IItdmRunFlowPathService> {
    @Autowired
    private IItdmRunFlowPathService itdmRunFlowPathService;
    @Autowired
    private IItdmFlowPathService itdmFlowPathService;

    @Autowired
    private IItdmRunFlowPathStepService itdmRunFlowPathStepService;
    @Autowired
    private IItdmFlowPathStepService iItdmFlowPathStepService;

    @Autowired
    private IItdmWeituoInfoService iItdmWeituoInfoService;


    @Autowired
    private SysBaseApiImpl sysBaseApi;

    @Autowired
    @SuppressWarnings("all")
    private IItdmTaskService taskService;


    //@AutoLog(value = "运行流程表-分页列表查询")
    @ApiOperation(value = "运行流程表-分页列表查询", notes = "运行流程表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<ItdmRunFlowPath>> queryPageList(ItdmRunFlowPath itdmRunFlowPath,
                                                        @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                        @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                        HttpServletRequest req) {
        QueryWrapper<ItdmRunFlowPath> queryWrapper = QueryGenerator.initQueryWrapper(itdmRunFlowPath, req.getParameterMap());
        Page<ItdmRunFlowPath> page = new Page<ItdmRunFlowPath>(pageNo, pageSize);
        IPage<ItdmRunFlowPath> pageList = itdmRunFlowPathService.page(page, queryWrapper);
        pageList.setRecords(pageList.getRecords().stream().peek(i -> {

            ItdmRunFlowPathStep select = itdmRunFlowPathStepService.getBaseMapper().selectOne(Wrappers.lambdaQuery(ItdmRunFlowPathStep.class)
                    .eq(ItdmRunFlowPathStep::getRunFlowPath, i.getId())
                    .eq(ItdmRunFlowPathStep::getFlowPathSetp, i.getDqSetp())

            );

            LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            List<String> strings = StringUtils.isNotBlank(select.getUserIds()) ?
                    Arrays.stream(select.getUserIds().split(",")).collect(Collectors.toList()) :
                    new ArrayList<>();
            List<String> roleIds = sysBaseApi.getRoleIdsByUsername(user.getUsername());

            i.setIsokview(strings.contains(user.getUsername()) || roleIds.contains(select.getRoleId()));


            boolean x = iItdmFlowPathStepService.getBaseMapper().exists(Wrappers.lambdaQuery(ItdmFlowPathStep.class)
                    .eq(ItdmFlowPathStep::getId, i.getDqSetp())
                    .eq(ItdmFlowPathStep::getSort, "1")

            );
            i.setIsbohuiview(!x && (strings.contains(user.getUsername()) || roleIds.contains(select.getRoleId())));
        }).collect(Collectors.toList()));
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param itdmRunFlowPath
     * @return
     */
    @AutoLog(value = "运行流程表-添加")
    @ApiOperation(value = "运行流程表-添加", notes = "运行流程表-添加")
    //@RequiresPermissions("org.jeecg.modules:itdm_run_flow_path:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody ItdmCreateRunFlowPath itdmRunFlowPath) {
        if(itdmRunFlowPath.getUserName()!=null){
            itdmRunFlowPathService.createRunFlowPath(itdmRunFlowPath);
            return Result.OK("添加成功！");
        }else return Result.error("请选择第一步操作人！");
    }

    /**
     * 编辑
     *
     * @param itdmRunFlowPath
     * @return
     */
    @AutoLog(value = "运行流程表-编辑")
    @ApiOperation(value = "运行流程表-编辑", notes = "运行流程表-编辑")
    //@RequiresPermissions("org.jeecg.modules:itdm_run_flow_path:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody ItdmRunFlowPath itdmRunFlowPath) {
        itdmRunFlowPathService.updateById(itdmRunFlowPath);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "运行流程表-通过id删除")
    @ApiOperation(value = "运行流程表-通过id删除", notes = "运行流程表-通过id删除")
    //@RequiresPermissions("org.jeecg.modules:itdm_run_flow_path:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {

        //查询对应的运行流程对象
        ItdmRunFlowPath runFlowPath = itdmRunFlowPathService.getById(id);
        int sort = Integer.parseInt(iItdmFlowPathStepService.getById(runFlowPath.getDqSetp()).getSort());
        //委托id
        if(runFlowPath!=null){
            Map<String, Object> weituoMap = new HashMap<>();
            weituoMap.put("weituo_no",runFlowPath.getWeituoNo());
            String weituoId = iItdmWeituoInfoService.listByMap(weituoMap).get(0).getId();

            //流程步骤表——12步
            List<ItdmFlowPathStep> stepList = iItdmFlowPathStepService.list();
            //删除对应的任务
            for(ItdmFlowPathStep step : stepList){
                int sort1 = Integer.parseInt(step.getSort());
                if(sort1<=sort){
                    ItdmTask task = new ItdmTask();
                    task.setWeituoId(weituoId);
                    task.setTaskContent(step.getName());
                    QueryWrapper<ItdmTask> queryWrapper = new QueryWrapper<>(task);
                    ItdmTask dTask = taskService.getOne(queryWrapper);
                    taskService.removeById(dTask);
                }
            }
        }

        itdmRunFlowPathService.removeById(id);
        itdmRunFlowPathStepService.remove(Wrappers.lambdaQuery(ItdmRunFlowPathStep.class).eq(ItdmRunFlowPathStep::getRunFlowPath, id));

        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "运行流程表-批量删除")
    @ApiOperation(value = "运行流程表-批量删除", notes = "运行流程表-批量删除")
    //@RequiresPermissions("org.jeecg.modules:itdm_run_flow_path:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {

        for (String id : Arrays.asList(ids.split(","))){
            //查询对应的运行流程对象
            ItdmRunFlowPath runFlowPath = itdmRunFlowPathService.getById(id);
            if(runFlowPath!=null){
                int sort = Integer.parseInt(iItdmFlowPathStepService.getById(runFlowPath.getDqSetp()).getSort());
                //委托id
                Map<String, Object> weituoMap = new HashMap<>();
                weituoMap.put("weituo_no",runFlowPath.getWeituoNo());
                String weituoId = iItdmWeituoInfoService.listByMap(weituoMap).get(0).getId();

                //流程步骤表——12步
                List<ItdmFlowPathStep> stepList = iItdmFlowPathStepService.list();
                //删除对应的任务
                for(ItdmFlowPathStep step : stepList){
                    int sort1 = Integer.parseInt(step.getSort());
                    if(sort1<=sort){
                        ItdmTask task = new ItdmTask();
                        task.setWeituoId(weituoId);
                        task.setTaskContent(step.getName());
                        QueryWrapper<ItdmTask> queryWrapper = new QueryWrapper<>(task);
                        ItdmTask dTask = taskService.getOne(queryWrapper);
                        taskService.removeById(dTask);
                    }
                }
            }

        }


        this.itdmRunFlowPathService.removeByIds(Arrays.asList(ids.split(",")));
        itdmRunFlowPathStepService.remove(Wrappers.lambdaQuery(ItdmRunFlowPathStep.class)
                .in(ItdmRunFlowPathStep::getRunFlowPath, Arrays.asList(ids.split(","))));


        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "运行流程表-通过id查询")
    @ApiOperation(value = "运行流程表-通过id查询", notes = "运行流程表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<ItdmRunFlowPathInfoVO> queryById(@RequestParam(name = "id", required = true) String id) {
        ItdmRunFlowPath itdmRunFlowPath = itdmRunFlowPathService.getById(id);
        if (itdmRunFlowPath == null) {
            return Result.error("未找到对应数据");
        }

        List<ItdmRunFlowPathStep> list = itdmRunFlowPathStepService.
                list(Wrappers.lambdaQuery(ItdmRunFlowPathStep.class).eq(ItdmRunFlowPathStep::getRunFlowPath, id));

        boolean x = iItdmFlowPathStepService.getBaseMapper().exists(Wrappers.lambdaQuery(ItdmFlowPathStep.class)

                .eq(ItdmFlowPathStep::getId, itdmRunFlowPath.getDqSetp())
                .eq(ItdmFlowPathStep::getSort, "1")

        );
        ItdmWeituoInfo weituoInfo = iItdmWeituoInfoService.getBaseMapper().selectOne(Wrappers.lambdaQuery(ItdmWeituoInfo.class).eq(
                ItdmWeituoInfo::getWeituoNo, itdmRunFlowPath.getWeituoNo()
        ));

        List<ItdmRunFlowPathStepVO> vos = new ArrayList<>();
        for (ItdmRunFlowPathStep i : list) {
            LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            List<String> strings = StringUtils.isNotBlank(i.getUserIds()) ?
                    Arrays.stream(i.getUserIds().split(",")).collect(Collectors.toList()) :
                    new ArrayList<>();
            List<String> roleIds = sysBaseApi.getRoleIdsByUsername(user.getUsername());

            LoginUser loginUser = sysBaseApi.getUserByName(i.getFqUser());
            if (strings.contains(user.getUsername()) || roleIds.contains(i.getRoleId())) {


                ItdmRunFlowPathStepVO itdmRunFlowPathStepVO = FlowPathConvert.INSTANCE.to(i, true, i.getFlowPathSetp().equals(itdmRunFlowPath.getDqSetp()), x && i.getFlowPathSetp().equals(itdmRunFlowPath.getDqSetp()) ? weituoInfo : null);


                itdmRunFlowPathStepVO.setFqUserName(loginUser != null ? loginUser.getRealname() : "");




                vos.add(itdmRunFlowPathStepVO);
            } else {

                ItdmRunFlowPathStepVO itdmRunFlowPathStepVO=  FlowPathConvert.INSTANCE.to(i, false, i.getFlowPathSetp().equals(itdmRunFlowPath.getDqSetp()), x && i.getFlowPathSetp().equals(itdmRunFlowPath.getDqSetp()) ? weituoInfo : null);

                itdmRunFlowPathStepVO.setFqUserName(loginUser != null ? loginUser.getRealname() : "");

                vos.add(itdmRunFlowPathStepVO);

            }


        }

        return Result.OK(new ItdmRunFlowPathInfoVO(itdmRunFlowPath, vos.stream().sorted(Comparator.comparingInt(o -> Integer.parseInt(o.getSort()))).collect(Collectors.toList())));
    }

    /**
     * 导出excel
     *
     * @param request
     * @param itdmRunFlowPath
     */
    //@RequiresPermissions("org.jeecg.modules:itdm_run_flow_path:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ItdmRunFlowPath itdmRunFlowPath) {
        return super.exportXls(request, itdmRunFlowPath, ItdmRunFlowPath.class, "运行流程表");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    //@RequiresPermissions("itdm_run_flow_path:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, ItdmRunFlowPath.class);
    }


}
