package com.ruoyi.cms.controller.cms;

import java.util.List;

import com.ruoyi.common.core.domain.entity.Industry;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
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.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.ruoyi.cms.service.IIndustryService;
import com.ruoyi.common.core.page.TableDataInfo;

import javax.servlet.http.HttpServletResponse;

/**
 * 行业Controller
 * 
 * @author LishunDong
 * @date 2024-11-12
 */
@RestController
@RequestMapping("/cms/industry")
@Api(tags = "后台：行业管理")
public class IndustryController extends BaseController
{
    @Autowired
    private IIndustryService industryService;

    /**
     * 查询行业列表
     */
    @ApiOperation("查询行业列表")
    @PreAuthorize("@ss.hasPermi('cms:industry:list')")
    @GetMapping("/list")
    public TableDataInfo list(Industry industry)
    {
        startPage();
        List<Industry> list = industryService.selectIndustryList(industry);
        return getDataTable(list);
    }
    @ApiOperation("行业树结构")
//    @PreAuthorize("@ss.hasPermi('cms:industry:list')")
    @GetMapping("/treeselect")
    public AjaxResult treeselect(Industry industry)
    {
        List<Industry> industryList = industryService.selectIndustryList(industry);
        return success(industryService.buildIndustryTreeSelect(industryList));
    }
    /**
     * 导出行业列表
     */
    @ApiOperation("导出行业列表")
    @PreAuthorize("@ss.hasPermi('cms:industry:export')")
    @Log(title = "行业", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Industry industry)
    {
        List<Industry> list = industryService.selectIndustryList(industry);
        ExcelUtil<Industry> util = new ExcelUtil<Industry>(Industry.class);
        util.exportExcel(response, list, "行业数据");
    }

    /**
     * 获取行业详细信息
     */
    @ApiOperation("获取行业详细信息")
    @PreAuthorize("@ss.hasPermi('cms:industry:query')")
    @GetMapping(value = "/{industryId}")
    public AjaxResult getInfo(@PathVariable("industryId") Long industryId)
    {
        return success(industryService.selectIndustryByIndustryId(industryId));
    }

    /**
     * 新增行业
     */
    @ApiOperation("新增行业")
    @PreAuthorize("@ss.hasPermi('cms:industry:add')")
    @Log(title = "行业", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Industry industry)
    {
        return toAjax(industryService.insertIndustry(industry));
    }

    /**
     * 修改行业
     */
    @ApiOperation("修改行业")
    @PreAuthorize("@ss.hasPermi('cms:industry:edit')")
    @Log(title = "行业", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Industry industry)
    {
        return toAjax(industryService.updateIndustry(industry));
    }

    /**
     * 删除行业
     */
    @ApiOperation("删除行业")
    @PreAuthorize("@ss.hasPermi('cms:industry:remove')")
    @Log(title = "行业", businessType = BusinessType.DELETE)
	@DeleteMapping("/{industryId}")
    public AjaxResult remove(@PathVariable Long industryId)
    {
        if (industryService.hasChildByIndustryId(industryId))
        {
            return warn("存在子行业,不允许删除");
        }
        Long[] industryIds = {industryId};
        return toAjax(industryService.deleteIndustryByIndustryIds(industryIds));
    }
    @GetMapping("/import")
    public AjaxResult importData()
    {
        industryService.importData();
        return success();
    }

    /**
     * 修改行业父级代码
     * select * from industry where length(remark)=1 order by order_num;
     * select * from industry where length(remark)=3 and remark like 'A%' order by order_num;
     * select * from industry where length(remark)=4 and remark like 'A01%' order by order_num;
     * select * from industry where length(remark)=5 and remark like 'A011%' order by order_num;
     */
    @PostMapping("/updateParentHierarchy")
    @Transactional(rollbackFor = Exception.class)
    public void updateParentHierarchy() {
        // 第一层：所有1位长度的大类（orderNum=1 → LENGTH(remark)=1），无前缀过滤（包含20个大类）
        Industry queryLevel1 = new Industry();
        queryLevel1.setOrderNum(1L); // 对应 SQL：LENGTH(remark)=1
        List<Industry> level1List = industryService.selectIndustryList(queryLevel1);

        if (level1List.isEmpty()) {
            throw new RuntimeException("未查询到1位长度的大类数据");
        }
        System.out.println("共查询到 " + level1List.size() + " 个1位大类，开始更新层级关系...");

        // 遍历每个1位大类，处理其下的3位子级
        for (Industry level1 : level1List) {
            Long level1Id = level1.getIndustryId();
            String level1Remark = level1.getRemark();

            // 跳过无效数据（ID或remark为空）
            if (level1Id == null || level1Remark == null) {
                System.out.println("跳过无效大类：ID=" + level1Id + "，remark=" + level1Remark);
                continue;
            }
            System.out.println("处理大类：remark=" + level1Remark + "，ID=" + level1Id);

            // 第二层：3位长度（orderNum=3） + 前缀=当前大类remark（比如" B"→"B%"）
            Industry queryLevel2 = new Industry();
            queryLevel2.setOrderNum(3L); // LENGTH(remark)=3
            queryLevel2.setRemark(level1Remark); // remark like 'B%'（自动匹配当前大类前缀）
            List<Industry> level2List = industryService.selectIndustryList(queryLevel2);

            if (level2List.isEmpty()) {
                System.out.println("大类 " + level1Remark + " 无3位子级，跳过");
                continue;
            }

            // 遍历3位子级，处理其下的4位孙级
            for (Industry level2 : level2List) {
                Long level2Id = level2.getIndustryId();
                String level2Remark = level2.getRemark();

                if (level2Id == null || level2Remark == null) {
                    continue;
                }

                // 第三层：4位长度（orderNum=4） + 前缀=当前3位子级remark（比如"B02"→"B02%"）
                Industry queryLevel3 = new Industry();
                queryLevel3.setOrderNum(4L); // LENGTH(remark)=4
                queryLevel3.setRemark(level2Remark); // remark like 'B02%'
                List<Industry> level3List = industryService.selectIndustryList(queryLevel3);

                if (level3List.isEmpty()) {
                    // 无4位孙级，直接更新3位子级的父ID=1位大类ID
                    updateParentId(level2Id, level1Id);
                    continue;
                }

                // 遍历4位孙级，处理其下的5位曾孙级
                for (Industry level3 : level3List) {
                    Long level3Id = level3.getIndustryId();
                    String level3Remark = level3.getRemark();

                    if (level3Id == null || level3Remark == null) {
                        continue;
                    }

                    // 第四层：5位长度（orderNum=5） + 前缀=当前4位孙级remark（比如"B021"→"B021%"）
                    Industry queryLevel4 = new Industry();
                    queryLevel4.setOrderNum(5L); // LENGTH(remark)=5
                    queryLevel4.setRemark(level3Remark); // remark like 'B021%'
                    List<Industry> level4List = industryService.selectIndustryList(queryLevel4);

                    // 更新5位曾孙级的父ID=4位孙级ID
                    for (Industry level4 : level4List) {
                        if (level4.getIndustryId() != null && level4.getRemark() != null) {
                            updateParentId(level4.getIndustryId(), level3Id);
                            System.out.println("更新5位数据：" + level4.getRemark() + " → 父ID=" + level3Id);
                        }
                    }

                    // 更新4位孙级的父ID=3位子级ID
                    updateParentId(level3Id, level2Id);
                    System.out.println("更新4位数据：" + level3Remark + " → 父ID=" + level2Id);
                }

                // 更新3位子级的父ID=1位大类ID
                updateParentId(level2Id, level1Id);
                System.out.println("更新3位数据：" + level2Remark + " → 父ID=" + level1Id);
            }
        }
        System.out.println("层级关系更新完成！");
    }

    /**
     * 修改行业父级代码
     * @param targetIndustryId
     * @param parentId
     */
    private void updateParentId(Long targetIndustryId, Long parentId) {
        Industry updateIndustry = new Industry();
        updateIndustry.setIndustryId(targetIndustryId);
        updateIndustry.setParentId(parentId);
        industryService.updateIndustry(updateIndustry);
    }
}
