package com.yunzhupaas.integrate.controller;


import cn.hutool.core.util.ObjectUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import com.yunzhupaas.base.ActionResult;
import com.yunzhupaas.base.controller.SuperController;
import com.yunzhupaas.base.vo.DownloadVO;
import com.yunzhupaas.base.vo.PageListVO;
import com.yunzhupaas.base.vo.PaginationVO;
import com.yunzhupaas.config.ConfigValueUtil;
import com.yunzhupaas.constant.MsgCode;
import com.yunzhupaas.emnus.ModuleTypeEnum;
import com.yunzhupaas.exception.WorkFlowException;
import com.yunzhupaas.integrate.entity.IntegrateEntity;
import com.yunzhupaas.integrate.entity.IntegrateQueueEntity;
import com.yunzhupaas.integrate.job.IntegrateJobUtil;
import com.yunzhupaas.integrate.model.integrate.*;
import com.yunzhupaas.integrate.model.nodeJson.IntegrateModel;
import com.yunzhupaas.integrate.service.IntegrateQueueService;
import com.yunzhupaas.integrate.service.IntegrateService;
import com.yunzhupaas.integrate.util.IntegrateHttpModel;
import com.yunzhupaas.integrate.util.IntegrateUtil;
import com.yunzhupaas.permission.entity.UserEntity;
import com.yunzhupaas.permission.service.UserService;
import com.yunzhupaas.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Slf4j
@Tag(name = "集成助手", description = "Integrate")
@RestController
@RequestMapping("/api/visualdev/Integrate")
public class IntegrateController extends SuperController<IntegrateService, IntegrateEntity> {

    @Autowired
    private UserService userService;
    
    @Autowired
    private DataFileExport fileExport;
    @Autowired
    private ConfigValueUtil configValueUtil;
    @Autowired
    private IntegrateService integrateService;
    @Autowired
    private IntegrateQueueService integrateQueueService;
    @Autowired
    private IntegrateUtil integrateUtil;
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 列表
     *
     * @return
     */
    @Operation(summary = "列表")
    @GetMapping
    public ActionResult<PageListVO<IntegrateListVO>> list(IntegratePagination pagination) {
        List<IntegrateEntity> data = integrateService.getList(pagination);
        List<String> userId = data.stream().map(t -> t.getCreatorUserId()).collect(Collectors.toList());
        List<UserEntity> userEntities = userService.getUserName(userId);
        List<IntegrateListVO> resultList = new ArrayList<>();
        for (IntegrateEntity entity : data) {
            IntegrateListVO vo = JsonUtil.getJsonToBean(entity, IntegrateListVO.class);
            UserEntity creatorUser = userEntities.stream().filter(t -> t.getId().equals(entity.getCreatorUserId())).findFirst().orElse(null);
            vo.setCreatorUser(creatorUser != null ? creatorUser.getRealName() + "/" + creatorUser.getAccount() : "");
            resultList.add(vo);
        }
        PaginationVO paginationVO = JsonUtil.getJsonToBean(pagination, PaginationVO.class);
        return ActionResult.page(resultList, paginationVO);
    }

    /**
     * 信息
     *
     * @param id 主键值
     * @return
     */
    @Operation(summary = "获取信息")
    @Parameters({
            @Parameter(name = "id", description = "主键", required = true)
    })
    @GetMapping("/{id}")
    public ActionResult info(@PathVariable("id") String id) {
        IntegrateEntity entity = integrateService.getInfo(id);
        if (entity == null) {
            return ActionResult.fail(MsgCode.FA001.get());
        }
        IntegrateInfoVO vo = JsonUtil.getJsonToBean(entity, IntegrateInfoVO.class);
        return ActionResult.success(vo);
    }

    /**
     * 新建
     *
     * @param integrateCrForm 实体对象
     * @return
     */
    @Operation(summary = "添加")
    @Parameters({
            @Parameter(name = "integrateCrForm", description = "实体对象", required = true)
    })
    @PostMapping
    public ActionResult create(@RequestBody @Valid IntegrateCrForm integrateCrForm) {
        IntegrateEntity entity = JsonUtil.getJsonToBean(integrateCrForm, IntegrateEntity.class);
        if (integrateService.isExistByFullName(entity.getFullName(), entity.getId())) {
            return ActionResult.fail(MsgCode.EXIST001.get());
        }
        if (integrateService.isExistByEnCode(entity.getEnCode(), entity.getId())) {
            return ActionResult.fail(MsgCode.EXIST002.get());
        }
        String id = RandomUtil.uuId();
        entity.setId(id);
        integrateService.create(entity);
        return ActionResult.success(MsgCode.SU001.get(), id);
    }

    /**
     * 更新
     *
     * @param id 主键值
     * @return
     */
    @Operation(summary = "修改")
    @Parameters({
            @Parameter(name = "id", description = "主键值", required = true),
            @Parameter(name = "integrateUpForm", description = "实体对象", required = true)
    })
    @PutMapping("/{id}")
    public ActionResult update(@PathVariable("id") String id, @RequestBody IntegrateUpForm integrateUpForm) {
        IntegrateEntity positionEntity = integrateService.getInfo(id);
        if (positionEntity == null) {
            return ActionResult.fail(MsgCode.FA002.get());
        }
        IntegrateEntity entity = JsonUtil.getJsonToBean(integrateUpForm, IntegrateEntity.class);
        if (integrateService.isExistByFullName(entity.getFullName(), id)) {
            return ActionResult.fail(MsgCode.EXIST001.get());
        }
        if (integrateService.isExistByEnCode(entity.getEnCode(), id)) {
            return ActionResult.fail(MsgCode.EXIST002.get());
        }
        boolean flag = integrateService.update(id, entity,false);
        if (flag == false) {
            return ActionResult.fail(MsgCode.FA002.get());
        }
        return ActionResult.success(MsgCode.SU004.get(), id);
    }

    /**
     * 删除
     *
     * @param id 主键值
     * @return
     */
    @Operation(summary = "删除")
    @Parameters({
            @Parameter(name = "id", description = "主键值", required = true)
    })
    @DeleteMapping("/{id}")
    public ActionResult delete(@PathVariable("id") String id) {
        IntegrateEntity entity = integrateService.getInfo(id);
        if (entity != null) {
            integrateService.delete(entity);
            return ActionResult.success(MsgCode.SU003.get());
        }
        return ActionResult.fail(MsgCode.FA003.get());
    }

    /**
     * 复制功能
     *
     * @param id 主键值
     * @return
     */
    @Operation(summary = "复制功能")
    @Parameters({
            @Parameter(name = "id", description = "主键"),
    })
    @PostMapping("/{id}/Actions/Copy")
    public ActionResult copyInfo(@PathVariable("id") String id) throws Exception {
        IntegrateEntity entity = integrateService.getInfo(id);
        entity.setEnabledMark(0);
        String copyNum = UUID.randomUUID().toString().substring(0, 5);
        entity.setFullName(entity.getFullName() + ".副本" + copyNum);
        entity.setLastModifyTime(null);
        entity.setLastModifyUserId(null);
        entity.setId(RandomUtil.uuId());
        entity.setEnCode(entity.getEnCode() + copyNum);
        entity.setCreatorTime(new Date());
        entity.setEnabledMark(0);
        entity.setCreatorUserId(UserProvider.getUser().getUserId());
        integrateService.create(entity);
        return ActionResult.success(MsgCode.SU007.get());
    }

    /**
     * 更新功能状态
     *
     * @param id 主键值
     * @return
     */
    @Operation(summary = "更新功能状态")
    @Parameters({
            @Parameter(name = "id", description = "主键"),
    })
    @PutMapping("/{id}/Actions/State")
    public ActionResult update(@PathVariable("id") String id) {
        IntegrateEntity entity = integrateService.getInfo(id);
        if (entity != null) {
            if (entity.getEnabledMark() == null || "1".equals(String.valueOf(entity.getEnabledMark()))) {
                entity.setEnabledMark(0);
            } else {
                entity.setEnabledMark(1);
            }
            boolean flag = integrateService.update(entity.getId(), entity,true);
            if (flag == false) {
                return ActionResult.fail(MsgCode.FA002.get());
            }
        }
        return ActionResult.success(MsgCode.SU004.get());
    }

    /**
     * 导出
     *
     * @param id 主键
     * @return
     */
    @Operation(summary = "导出")
    @PostMapping("/{id}/Actions/Export")
    @Parameters({
            @Parameter(name = "id", description = "主键", required = true),
    })
    public ActionResult<DownloadVO> exportData(@PathVariable("id") String id) {
        IntegrateEntity entity = integrateService.getInfo(id);
        DownloadVO downloadVO = fileExport.exportFile(entity, configValueUtil.getTemporaryFilePath(), entity.getFullName(), ModuleTypeEnum.BASE_INTEGRATE.getTableName());
        return ActionResult.success(downloadVO);
    }

    /**
     * 导入
     *
     * @param file 文件
     * @return
     */
    @Operation(summary = "导入")
    @PostMapping(value = "/Actions/Import", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ActionResult ImportData(@RequestPart("file") MultipartFile file,@RequestParam("type") Integer type) throws WorkFlowException {
        //判断是否为.json结尾
        if (FileUtil.existsSuffix(file, ModuleTypeEnum.BASE_INTEGRATE.getTableName())) {
            return ActionResult.fail(MsgCode.IMP002.get());
        }
        try {
            String fileContent = FileUtil.getFileContent(file);
            IntegrateEntity entity = JsonUtil.getJsonToBean(fileContent, IntegrateEntity.class);
            return integrateService.ImportData(entity, type);
        } catch (Exception e) {
            throw new WorkFlowException(MsgCode.IMP004.get());
        }
    }

    /**
     * 集成助手事件触发
     * @param model
     * @return
     */
    @PostMapping(value = "/execute")
    public ActionResult execute(@RequestBody IntegrateHttpModel model) {
        integrateUtil.integrates(model.getDataInfoVOList(),model.getUserInfo());
        return ActionResult.success();
    }

    /**
     * 集成助手定时触发
     * @param model
     * @return
     */
    @PostMapping(value = "/executeQuery")
    public ActionResult executeQuery(@RequestBody IntegrateHttpModel model) {
        IntegrateModel integrateModel = JsonUtil.getJsonToBean(model, IntegrateModel.class);
        if(ObjectUtil.isNotEmpty(model.getId())){
            IntegrateQueueEntity entity = integrateQueueService.getById(model.getId());
            if(ObjectUtil.isNotEmpty(entity)) {
                integrateUtil.integrate(entity, model.getUserInfo());
            }
        }
        IntegrateJobUtil.removeIntegrate(integrateModel, redisUtil);
        return ActionResult.success();
    }

}

