package com.ygtx.web.controller.system;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.github.pagehelper.util.StringUtil;
import com.ygtx.common.core.domain.entity.SysRole;
import com.ygtx.common.core.domain.entity.SysUser;
import com.ygtx.common.core.domain.model.LoginUser;
import com.ygtx.common.utils.SecurityUtils;
import com.ygtx.system.service.ISysRoleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ygtx.common.annotation.Log;
import com.ygtx.common.core.controller.BaseController;
import com.ygtx.common.core.domain.AjaxResult;
import com.ygtx.common.core.page.TableDataInfo;
import com.ygtx.common.enums.BusinessType;
import com.ygtx.common.utils.poi.ExcelUtil;
import com.ygtx.system.domain.SysPost;
import com.ygtx.system.domain.SysPostHomePage;
import com.ygtx.system.service.ISysPostService;
import com.ygtx.system.service.ISysPostHomePageService;

/**
 * 首页配置Controller
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/postHomePage")
public class SysPostHomePageController extends BaseController
{
    private static final Logger logger = LoggerFactory.getLogger(SysPostHomePageController.class);

    @Autowired
    private ISysPostHomePageService sysPostHomePageService;

    @Autowired
    private ISysPostService sysPostService;

    @Autowired
    private ISysRoleService sysRoleService;

    /**
     * 查询首页配置列表
     */
    @PreAuthorize("@ss.hasPermi('system:postHomePage:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysPostHomePage sysPostHomePage)
    {
        startPage();
        List<SysPostHomePage> list = sysPostHomePageService.selectSysPostHomePageList(sysPostHomePage);
        return getDataTable(list);
    }

    /**
     * 查询岗位列表
     */
    @PreAuthorize("@ss.hasPermi('system:postHomePage:list')")
    @GetMapping("/postList")
    public AjaxResult postList(SysPost sysPost)
    {
        sysPost.setStatus("0");
        List<SysPost> list = sysPostService.selectPostList(sysPost);
        return AjaxResult.success(list);
    }

    /**
     * 查询角色列表
     */
    @PreAuthorize("@ss.hasPermi('system:postHomePage:list')")
    @GetMapping("/roleList")
    public AjaxResult roleList(SysRole sysRole)
    {
        sysRole.setStatus("0");
        sysRole.setDelFlag("0");
        List<SysRole> list = sysRoleService.selectRoleList(sysRole);
        return AjaxResult.success(list);
    }

    /**
     * 导出首页配置列表
     */
    @PreAuthorize("@ss.hasPermi('system:postHomePage:export')")
    @Log(title = "首页配置", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysPostHomePage sysPostHomePage)
    {
        List<SysPostHomePage> list = sysPostHomePageService.selectSysPostHomePageList(sysPostHomePage);
        ExcelUtil<SysPostHomePage> util = new ExcelUtil<SysPostHomePage>(SysPostHomePage.class);
        util.exportExcel(response, list, "首页配置数据");
    }

    /**
     * 获取首页配置详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:postHomePage:query')")
    @GetMapping(value = "/{postId}")
    public AjaxResult getInfo(@PathVariable("postId") Long postId)
    {
        return AjaxResult.success(sysPostHomePageService.selectSysPostHomePageById(postId));
    }

    /**
     * 新增首页配置
     */
    @PreAuthorize("@ss.hasPermi('system:postHomePage:add')")
    @Log(title = "首页配置", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysPostHomePage sysPostHomePage)
    {
        try {
            // 设置创建者信息
            String username = getUsername();
            sysPostHomePage.setCreateBy(username);

            int result = sysPostHomePageService.insertSysPostHomePage(sysPostHomePage);
            if (result > 0) {
                return AjaxResult.success("操作成功");
            } else {
                return AjaxResult.error("操作失败");
            }
        } catch (Exception e) {
            logger.error("新增首页配置失败", e);
            return AjaxResult.error("操作失败: " + e.getMessage());
        }
    }

    /**
     * 修改首页配置
     */
    @PreAuthorize("@ss.hasPermi('system:postHomePage:edit')")
    @Log(title = "首页配置", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysPostHomePage sysPostHomePage)
    {
        try {
            // 设置更新者信息
            String username = getUsername();
            sysPostHomePage.setUpdateBy(username);

            int result = sysPostHomePageService.updateSysPostHomePage(sysPostHomePage);
            if (result > 0) {
                return AjaxResult.success("操作成功");
            } else {
                return AjaxResult.error("操作失败");
            }
        } catch (Exception e) {
            logger.error("修改首页配置失败", e);
            return AjaxResult.error("操作失败: " + e.getMessage());
        }
    }

    /**
     * 删除首页配置
     */
    @PreAuthorize("@ss.hasPermi('system:postHomePage:remove')")
    @Log(title = "首页配置", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String ids)
    {
        // 将字符串转换为Long数组
        String[] idArray = ids.split(",");
        Long[] idsArray = new Long[idArray.length];
        for (int i = 0; i < idArray.length; i++) {
            idsArray[i] = Long.parseLong(idArray[i]);
        }
        return toAjax(sysPostHomePageService.deleteSysPostHomePageByIds(idsArray));
    }

    @GetMapping("/getHomePage")
    public AjaxResult getHomePage()
    {
        List<SysRole> roleList = sysRoleService.selectRolesByUserName(getUsername());
        if (!roleList.isEmpty()) {
            Integer roleSort = null;
            Long userHighRoleId = null;
            for (SysRole sysRole : roleList) {
                if (roleSort==null || (sysRole.getRoleSort()!=null && roleSort>sysRole.getRoleSort())) {
                    roleSort = sysRole.getRoleSort();
                    userHighRoleId = sysRole.getRoleId();
                }
            }
            if (userHighRoleId!=null) {
                SysPostHomePage postHomePage = new SysPostHomePage();
                postHomePage.setStatus("0");
                List<SysPostHomePage> list = sysPostHomePageService.selectSysPostHomePageList(postHomePage);
                if (!list.isEmpty()) {
                    for (SysPostHomePage homePage : list) {
                        if (StringUtil.isNotEmpty(homePage.getHomePageType()) && !homePage.getHomePageType().equals("-1")) {
                            String[] roleIdStrings = homePage.getPostIds().split(",");
                            for (String roleStr : roleIdStrings) {
                                if (Long.parseLong(roleStr) == userHighRoleId) {
                                    return AjaxResult.success(homePage);
                                }
                            }
                        }
                    }
                }
            }
        }

        // 如果没有具体岗位匹配，尝试匹配默认配置（postIds包含-1的记录）
        SysPostHomePage defaultPostHomePage = new SysPostHomePage();
        defaultPostHomePage.setStatus("0");
        List<SysPostHomePage> allList = sysPostHomePageService.selectSysPostHomePageList(defaultPostHomePage);
        for (SysPostHomePage config : allList) {
            if (config.getPostIds() != null && config.getPostIds().contains("-1")) {
                return AjaxResult.success(config);
            }
        }
        return AjaxResult.success();
    }
}
