package com.yunzhupaas.bsc.controller;


import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import com.yunzhupaas.base.ActionResult;
import com.yunzhupaas.base.UserInfo;
import com.yunzhupaas.exception.DataException;
import com.yunzhupaas.permission.entity.UserEntity;
import com.yunzhupaas.constant.MsgCode;
import com.yunzhupaas.bsc.service.*;
import com.yunzhupaas.bsc.entity.*;
import com.yunzhupaas.util.*;
import com.yunzhupaas.bsc.model.projecttype.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.yunzhupaas.flowable.entity.TaskEntity;
import jakarta.validation.Valid;
import java.util.*;
import com.yunzhupaas.model.ExcelModel;
import com.yunzhupaas.excel.ExcelExportStyler;
import com.yunzhupaas.excel.ExcelHelper;
import com.yunzhupaas.annotation.YunzhupaasField;
import com.yunzhupaas.base.vo.PageListVO;
import com.yunzhupaas.base.vo.PaginationVO;
import com.yunzhupaas.base.vo.DownloadVO;
import com.yunzhupaas.config.ConfigValueUtil;
import com.yunzhupaas.base.entity.ProvinceEntity;
import java.io.IOException;
import java.util.stream.Collectors;
import com.yunzhupaas.flowable.entity.TaskEntity;
import com.yunzhupaas.exception.WorkFlowException;
import com.yunzhupaas.model.visualJson.UploaderTemplateModel;
import com.yunzhupaas.base.util.FormExecelUtils;
import org.springframework.transaction.annotation.Transactional;

/**
 * 项目分类
 * @版本： V5.2.7
 * @版权： Copyright @ 2025  深圳市乐程软件有限公司版权所有
 * @作者： 深圳市乐程软件有限公司
 * @日期： 2026-05-19
 */
@Slf4j
@RestController
@Tag(name = "项目分类" , description = "1")
@RequestMapping("/api/bc/ProjectType")
public class ProjectTypeController {

    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private UserProvider userProvider;

    @Autowired
    private ProjectTypeService projectTypeService;



    /**
    * 列表
    *
    * @param projectTypePagination
    * @return
    */
    @Operation(summary = "获取列表")
    @PostMapping("/getList")
    public ActionResult list(@RequestBody ProjectTypePagination projectTypePagination)throws Exception{
        List<ProjectTypeEntity> list= projectTypeService.getList(projectTypePagination);
        List<Map<String, Object>> realList=new ArrayList<>();
        for (ProjectTypeEntity entity : list) {
        Map<String, Object> projectTypeMap=JsonUtil.entityToMap(entity);
        projectTypeMap.put("id", projectTypeMap.get("project_type_id"));
        //副表数据
        //子表数据
            realList.add(projectTypeMap);
        }
        //数据转换
        boolean isPc = "pc".equals(ServletUtil.getHeader("yunzhupaas-origin" ));
        realList = generaterSwapUtil.swapDataList(realList, ProjectTypeConstant.getFormData(), ProjectTypeConstant.getColumnData(), projectTypePagination.getModuleId(),isPc?false:false);

        if(isPc){
            //分组和树形的树形数据转换
            realList = generaterSwapUtil.swapDataList(realList, ProjectTypeConstant.getColumnData(), "project_type_id");
        }
        for (Map<String, Object> map : realList) {
            Object object = map.get("children");
            if (ObjectUtil.isNotNull(object) && object instanceof List) {
                // ✅ 直接转换为原对象，不创建新对象
                @SuppressWarnings("unchecked")
                List<Map<String, Object>> children = (List<Map<String, Object>>) object;
                for (Map<String, Object> child : children) {
                    Object pidIdObj = child.get("pid_id");
                    if (pidIdObj != null && !"".equals(pidIdObj.toString())) {
                        ProjectTypeEntity entity = projectTypeService.getInfo(pidIdObj.toString());
                        if (entity != null) {
                            child.put("pid", entity.getProjectTypeName());
                        }
                    }
                }
            }
        }
        //返回对象
        PageListVO vo = new PageListVO();
        vo.setList(realList);
        PaginationVO page = JsonUtil.getJsonToBean(projectTypePagination, PaginationVO.class);
        vo.setPagination(page);
        return ActionResult.success(vo);
    }
    /**
    * 创建
    *
    * @param projectTypeForm
    * @return
    */
    @PostMapping()
    @Operation(summary = "创建")
    public ActionResult create(@RequestBody @Valid ProjectTypeForm projectTypeForm) throws Exception {
        String b = projectTypeService.checkForm(projectTypeForm,0);
        if (StringUtil.isNotEmpty(b)){
            return ActionResult.fail(b );
        }
        try{
            projectTypeService.saveOrUpdate(projectTypeForm, null ,true);
        }catch(Exception e){
            return ActionResult.fail(MsgCode.FA028.get());
        }
        return ActionResult.success(MsgCode.SU001.get());
    }
    /**
    * 删除
    * @param id
    * @return
    */
    @Operation(summary = "删除")
    @DeleteMapping("/{id}")
    @Transactional
    public ActionResult delete(@PathVariable("id") String id,@RequestParam(name = "forceDel",defaultValue = "false") boolean forceDel) throws Exception{
        ProjectTypeEntity entity= projectTypeService.getInfo(id);
        if(entity!=null){
            //主表数据删除
            projectTypeService.delete(entity);
        }
        return ActionResult.success(MsgCode.SU003.get());
    }
    /**
    * 批量删除
    * @param obj
    * @return
    */
    @DeleteMapping("/batchRemove")
    @Transactional
    @Operation(summary = "批量删除")
    public ActionResult batchRemove(@RequestBody Object obj){
    Map<String, Object> objectMap = JsonUtil.entityToMap(obj);
    List<String> idList = JsonUtil.getJsonToList(objectMap.get("ids"), String.class);
    String errInfo = "";
    List<String> successList = new ArrayList<>();
        for (String allId : idList){
            try {
                this.delete(allId,false);
                successList.add(allId);
            } catch (Exception e) {
                errInfo = e.getMessage();
            }
        }
        if (successList.size() == 0 && StringUtil.isNotEmpty(errInfo)){
            return ActionResult.fail(errInfo);
        }
        return ActionResult.success(MsgCode.SU003.get());
    }
    /**
    * 编辑
    * @param id
    * @param projectTypeForm
    * @return
    */
    @PutMapping("/{id}")
    @Operation(summary = "更新")
    public ActionResult update(@PathVariable("id") String id,@RequestBody @Valid ProjectTypeForm projectTypeForm,
                                @RequestParam(value = "isImport", required = false) boolean isImport){
        ProjectTypeEntity entity= projectTypeService.getInfo(id);
        if(entity!=null){
            projectTypeForm.setProjectTypeId(String.valueOf(entity.getProjectTypeId()));

            if (!isImport) {
                String b =  projectTypeService.checkForm(projectTypeForm,1);
                if (StringUtil.isNotEmpty(b)){
                    return ActionResult.fail(b );
                }
            }

            try{
                projectTypeService.saveOrUpdate(projectTypeForm,id,false);
            }catch (DataException e1){
                return ActionResult.fail(e1.getMessage());
            }catch(Exception e){
                return ActionResult.fail(MsgCode.FA029.get());
            }
            return ActionResult.success(MsgCode.SU004.get());
        }else{
            return ActionResult.fail(MsgCode.FA002.get());
        }
    }
    /**
    * 表单信息(详情页)
    * 详情页面使用-转换数据
    * @param id
    * @return
    */
    @Operation(summary = "表单信息(详情页)")
    @GetMapping("/detail/{id}")
    public ActionResult detailInfo(@PathVariable("id") String id){
        ProjectTypeEntity entity= projectTypeService.getInfo(id);
        if(entity==null){
            return ActionResult.fail(MsgCode.FA001.get());
        }
        Map<String, Object> projectTypeMap=JsonUtil.entityToMap(entity);
        projectTypeMap.put("id", projectTypeMap.get("project_type_id"));
        //副表数据
        //子表数据
        boolean isPc = "pc".equals(ServletUtil.getHeader("yunzhupaas-origin" ));
        projectTypeMap = generaterSwapUtil.swapDataDetail(projectTypeMap,ProjectTypeConstant.getFormData(),"824397917879010373",isPc?false:false);
        //子表数据
        if (StringUtil.isNotEmpty(entity.getPid())){
            ProjectTypeEntity entitys= projectTypeService.getInfo(entity.getPid());
            projectTypeMap.put("pid", entitys.getProjectTypeName());

        }
        return ActionResult.success(projectTypeMap);
    }
    /**
    * 获取详情(编辑页)
    * 编辑页面使用-不转换数据
    * @param id
    * @return
    */
    @Operation(summary = "信息")
    @GetMapping("/{id}")
    public ActionResult info(@PathVariable("id") String id){
        ProjectTypeEntity entity= projectTypeService.getInfo(id);
        if(entity==null){
            return ActionResult.fail(MsgCode.FA001.get());
        }
        Map<String, Object> projectTypeMap=JsonUtil.entityToMap(entity);
        projectTypeMap.put("id", projectTypeMap.get("project_type_id"));
        //副表数据
        //子表数据
        projectTypeMap = generaterSwapUtil.swapDataForm(projectTypeMap,ProjectTypeConstant.getFormData(),ProjectTypeConstant.TABLEFIELDKEY,ProjectTypeConstant.TABLERENAMES);
        return ActionResult.success(projectTypeMap);
    }
    /**
     * 树状列表查询
     * @return
     */
    @Operation(summary = "树状列表查询")
    @GetMapping("/getTreeList")
    public ActionResult getTreeList(){
        List<Map<String, Object>> treeList= projectTypeService.getTreeList();
        return ActionResult.success(treeList);
    }


}
