package com.test.test.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.test.common.utils.DateUtils;
import com.test.common.utils.SecurityUtils;
import com.test.common.utils.StringUtils;
import com.test.test.domain.UiAutomation;
import com.test.test.domain.UiHighSetting;
import com.test.test.domain.UiSceneSteps;
import com.test.test.domain.qo.*;
import com.test.test.domain.vo.UiAutomationVO;
import com.test.test.domain.vo.UiHighSettingVO;
import com.test.test.domain.vo.UiSceneStepsVO;
import com.test.test.mapper.UiAutomationMapper;
import com.test.test.mapper.UiHighSettingMapper;
import com.test.test.mapper.UiSceneStepsMapper;
import com.test.test.service.ITestGroupService;
import com.test.test.service.IUiAutomationService;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * ui自动化Service业务层处理
 *
 * @author test
 * @date 2025-04-22
 */
@Service
public class UiAutomationServiceImpl implements IUiAutomationService {
    @Resource
    private UiAutomationMapper uiAutomationMapper;
    @Resource
    private ITestGroupService testGroupService;
    @Resource
    private UiHighSettingMapper uiHighSettingMapper;
    @Resource
    private UiSceneStepsMapper uiSceneStepsMapper;

    private final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 查询ui自动化
     *
     * @param id ui自动化主键
     * @return ui自动化
     */
    @Override
    public UiAutomationVO selectUiAutomationById(Long id) {
        UiAutomationVO uiAutomationVO = new UiAutomationVO();
        UiAutomation automation = uiAutomationMapper.selectUiAutomationById(id);
        BeanUtils.copyProperties(automation, uiAutomationVO);

        List<UiSceneSteps> uiSceneStepsList = uiSceneStepsMapper.selectUiSceneStepsById(id);
        for (UiSceneSteps uiSceneSteps : uiSceneStepsList) {
            UiSceneStepsVO uiSceneStepsVO = new UiSceneStepsVO();
            BeanUtils.copyProperties(uiSceneSteps, uiSceneStepsVO);
            uiAutomationVO.getUiSceneStepsVOList().add(uiSceneStepsVO);
            List<UiHighSetting> uiHighSettings = uiHighSettingMapper.selectUiHighSettingById(uiSceneSteps.getId());
            for (UiHighSetting uiHighSetting : uiHighSettings) {
                UiHighSettingVO uiHighSettingVO = new UiHighSettingVO();
                BeanUtils.copyProperties(uiHighSetting, uiHighSettingVO);
                // 转换assertionJson 断言
                if (StringUtils.isNotBlank(uiHighSetting.getAssertionJson())) {
                    List<AssertionQO> assertionList = null;
                    try {
                        assertionList = objectMapper.readValue(
                                uiHighSetting.getAssertionJson(),
                                new TypeReference<List<AssertionQO>>() {
                                }
                        );
                        List<AssertionQO> popupTexts = new ArrayList<>();
                        List<AssertionQO> elementAssertions = new ArrayList<>();
                        List<AssertionQO> dropdownBoxes = new ArrayList<>();
                        List<AssertionQO> webTitles = new ArrayList<>();
                        for (AssertionQO extractionQO : assertionList) {
                            if ("1".equals(extractionQO.getAssertionType())) {
                                popupTexts.add(extractionQO);
                            } else if ("2".equals(extractionQO.getAssertionType())) {
                                elementAssertions.add(extractionQO);
                            } else if ("3".equals(extractionQO.getAssertionType())) {
                                dropdownBoxes.add(extractionQO);
                            } else if ("4".equals(extractionQO.getAssertionType())) {
                                webTitles.add(extractionQO);
                            }
                        }
                        uiHighSettingVO.getAssertionQOList().setPopupTexts(popupTexts);
                        uiHighSettingVO.getAssertionQOList().setElementAssertions(elementAssertions);
                        uiHighSettingVO.getAssertionQOList().setDropdownBoxes(dropdownBoxes);
                        uiHighSettingVO.getAssertionQOList().setWebTitles(webTitles);
                        // 转换extractionDataJson  数据提取
                        if (StringUtils.isNotBlank(uiHighSetting.getExtractionDataJson())) {
                            List<DataExtractionQO> extractionData = null;
                            extractionData = objectMapper.readValue(
                                    uiHighSetting.getExtractionDataJson(),
                                    new TypeReference<List<DataExtractionQO>>() {
                                    }
                            );
                            List<DataExtractionQO> windowExtractions = new ArrayList<>();
                            List<DataExtractionQO> elementExtractions = new ArrayList<>();
                            for (DataExtractionQO extractionQO : extractionData) {
                                if ("1".equals(extractionQO.getInformationType())) {
                                    windowExtractions.add(extractionQO);
                                } else if ("2".equals(extractionQO.getInformationType())) {
                                    elementExtractions.add(extractionQO);
                                }
                            }
                            uiHighSettingVO.getDataExtractionQOList().setWindowExtractions(windowExtractions);
                            uiHighSettingVO.getDataExtractionQOList().setElementExtractions(elementExtractions);
                        }
                        // 转换otherSetting 其他设置
                        if (StringUtils.isNotBlank(uiHighSetting.getOtherSetting())) {
                            OtherSettingsQO otherSettings = objectMapper.readValue(
                                    uiHighSetting.getOtherSetting(),
                                    OtherSettingsQO.class
                            );
                            uiHighSettingVO.setOtherSettingsQO(otherSettings);
                        }
                    } catch (JsonProcessingException e) {
                        throw new RuntimeException(e);
                    }

                }
                uiSceneStepsVO.getUiHighSettingVOList().add(uiHighSettingVO);
            }
        }
        return uiAutomationVO;
    }


    public List<UiHighSettingVO> getUiHighSettingVOList(Long stepsId) {
        List<UiHighSettingVO> uiHighSettingVOList = new ArrayList<>();
        List<UiHighSetting> uiHighSettings = uiHighSettingMapper.selectUiHighSettingById(stepsId);
        for (UiHighSetting uiHighSetting : uiHighSettings) {
            UiHighSettingVO uiHighSettingVO = new UiHighSettingVO();
            BeanUtils.copyProperties(uiHighSetting, uiHighSettingVO);
            // 转换assertionJson 断言
            if (StringUtils.isNotBlank(uiHighSetting.getAssertionJson())) {
                List<AssertionQO> assertionList = null;
                try {
                    assertionList = objectMapper.readValue(
                            uiHighSetting.getAssertionJson(),
                            new TypeReference<List<AssertionQO>>() {
                            }
                    );
                    List<AssertionQO> popupTexts = new ArrayList<>();
                    List<AssertionQO> elementAssertions = new ArrayList<>();
                    List<AssertionQO> dropdownBoxes = new ArrayList<>();
                    List<AssertionQO> webTitles = new ArrayList<>();
                    for (AssertionQO extractionQO : assertionList) {
                        if ("1".equals(extractionQO.getAssertionType())) {
                            popupTexts.add(extractionQO);
                        } else if ("2".equals(extractionQO.getAssertionType())) {
                            elementAssertions.add(extractionQO);
                        } else if ("3".equals(extractionQO.getAssertionType())) {
                            dropdownBoxes.add(extractionQO);
                        } else if ("4".equals(extractionQO.getAssertionType())) {
                            webTitles.add(extractionQO);
                        }
                    }
                    uiHighSettingVO.getAssertionQOList().setPopupTexts(popupTexts);
                    uiHighSettingVO.getAssertionQOList().setElementAssertions(elementAssertions);
                    uiHighSettingVO.getAssertionQOList().setDropdownBoxes(dropdownBoxes);
                    uiHighSettingVO.getAssertionQOList().setWebTitles(webTitles);
                    // 转换extractionDataJson  数据提取
                    if (StringUtils.isNotBlank(uiHighSetting.getExtractionDataJson())) {
                        List<DataExtractionQO> extractionData = null;
                        extractionData = objectMapper.readValue(
                                uiHighSetting.getExtractionDataJson(),
                                new TypeReference<List<DataExtractionQO>>() {
                                }
                        );
                        List<DataExtractionQO> windowExtractions = new ArrayList<>();
                        List<DataExtractionQO> elementExtractions = new ArrayList<>();
                        for (DataExtractionQO extractionQO : extractionData) {
                            if ("1".equals(extractionQO.getInformationType())) {
                                windowExtractions.add(extractionQO);
                            } else if ("2".equals(extractionQO.getInformationType())) {
                                elementExtractions.add(extractionQO);
                            }
                        }
                        uiHighSettingVO.getDataExtractionQOList().setWindowExtractions(windowExtractions);
                        uiHighSettingVO.getDataExtractionQOList().setElementExtractions(elementExtractions);
                    }
                    // 转换otherSetting 其他设置
                    if (StringUtils.isNotBlank(uiHighSetting.getOtherSetting())) {
                        OtherSettingsQO otherSettings = objectMapper.readValue(
                                uiHighSetting.getOtherSetting(),
                                OtherSettingsQO.class
                        );
                        uiHighSettingVO.setOtherSettingsQO(otherSettings);
                    }
                    uiHighSettingVOList.add(uiHighSettingVO);
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }

            }
        }
        return uiHighSettingVOList;
    }

    /**
     * 查询ui自动化列表
     *
     * @param uiAutomation ui自动化
     * @return ui自动化
     */
    @Override
    public List<UiAutomation> selectUiAutomationList(UiAutomationQO uiAutomation) {
        uiAutomation.setDelFlag("0");
        //这里要递归查询子元素
        Long groupId = uiAutomation.getGroupId();
        if (groupId != null) {
            List<Long> allChildIds = testGroupService.getAllChildIds(groupId, "automation");
            uiAutomation.setGroupIds(allChildIds);
        }
        // 查询元素列表
        List<UiAutomation> uiAutomations = uiAutomationMapper.selectUiAutomationListNew(uiAutomation);

        return uiAutomations;
    }

    /**
     * 新增ui自动化
     *
     * @param uiAutomationDataQO ui自动化
     * @return 结果
     */
    @Override
    @Transactional
    public Long insertUiAutomation(UiAutomationDataQO uiAutomationDataQO) {
        UiAutomation uiAutomation = new UiAutomation();
        BeanUtils.copyProperties(uiAutomationDataQO, uiAutomation);
        //新增ui自动化表
        uiAutomation.setCreateTime(DateUtils.getNowDate());
        uiAutomation.setUpdateTime(DateUtils.getNowDate());
        uiAutomation.setCreateBy(SecurityUtils.getUsername());
        uiAutomation.setUpdateBy(SecurityUtils.getUsername());
        uiAutomation.setDutyBy(SecurityUtils.getUsername());
        uiAutomation.setDelFlag(0);
        uiAutomation.setCrontabStatus(0); //未开启
        uiAutomationMapper.insertUiAutomation(uiAutomation);
        Long automationId = uiAutomation.getId();
        //新增场景步骤
        List<UiSceneStepsQO> uiSceneStepsQOList = uiAutomationDataQO.getUiSceneStepsVOList();
        for (UiSceneStepsQO uiSceneStepsQO : uiSceneStepsQOList) {
            UiSceneSteps uiSceneSteps = new UiSceneSteps();
            BeanUtils.copyProperties(uiSceneStepsQO, uiSceneSteps);
            uiSceneSteps.setAutomationId(automationId);
            uiSceneSteps.setUpdateBy(SecurityUtils.getUsername());
            uiSceneSteps.setUpdateTime(DateUtils.getNowDate());
            uiSceneSteps.setCreateTime(DateUtils.getNowDate());
            uiSceneSteps.setCreateBy(SecurityUtils.getUsername());
            uiSceneSteps.setDelFlag(0);
            uiSceneStepsMapper.insertUiSceneSteps(uiSceneSteps);
            Long stepsId = uiSceneSteps.getId();
            //高级设置
            List<UiHighSettingQO> uiHighSettingQOList = uiSceneStepsQO.getUiHighSettingVOList();
            for (UiHighSettingQO uiHighSettingQO : uiHighSettingQOList) {
                UiHighSetting uiHighSetting = new UiHighSetting();
                BeanUtils.copyProperties(uiHighSettingQO, uiHighSetting);
                uiHighSetting.setSceneStepsId(stepsId);
                uiHighSetting.setDelFlag(0);
                uiHighSetting.setUpdateBy(SecurityUtils.getUsername());
                uiHighSetting.setUpdateTime(DateUtils.getNowDate());
                uiHighSetting.setCreateBy(SecurityUtils.getUsername());
                uiHighSetting.setCreateTime(DateUtils.getNowDate());
                try {
                    List<DataExtractionQO> combinedList1 = new ArrayList<>();
                    // 安全添加 windowExtractions
                    if (uiHighSettingQO.getDataExtractionQOList() != null &&
                            uiHighSettingQO.getDataExtractionQOList().getWindowExtractions() != null) {
                        combinedList1.addAll(uiHighSettingQO.getDataExtractionQOList().getWindowExtractions());
                    }
                    // 安全添加 elementExtractions
                    if (uiHighSettingQO.getDataExtractionQOList() != null &&
                            uiHighSettingQO.getDataExtractionQOList().getElementExtractions() != null) {
                        combinedList1.addAll(uiHighSettingQO.getDataExtractionQOList().getElementExtractions());
                    }
                    //数据提取
                    String jsonStr = objectMapper.writeValueAsString(combinedList1);
                    if (jsonStr != null) {
                        uiHighSetting.setExtractionDataJson(jsonStr);
                    }
                    List<AssertionQO> combinedList2 = new ArrayList<>();
                    // 安全添加 popupTexts
                    if (uiHighSettingQO.getAssertionQOList() != null &&
                            uiHighSettingQO.getAssertionQOList().getPopupTexts() != null) {
                        combinedList2.addAll(uiHighSettingQO.getAssertionQOList().getPopupTexts());
                    }
                    // 安全添加 elementAssertions
                    if (uiHighSettingQO.getAssertionQOList() != null &&
                            uiHighSettingQO.getAssertionQOList().getElementAssertions() != null) {
                        combinedList2.addAll(uiHighSettingQO.getAssertionQOList().getElementAssertions());
                    }
                    // 安全添加 dropdownBoxes
                    if (uiHighSettingQO.getAssertionQOList() != null &&
                            uiHighSettingQO.getAssertionQOList().getDropdownBoxes() != null) {
                        combinedList2.addAll(uiHighSettingQO.getAssertionQOList().getDropdownBoxes());
                    }
                    // 安全添加 webTitles
                    if (uiHighSettingQO.getAssertionQOList() != null &&
                            uiHighSettingQO.getAssertionQOList().getWebTitles() != null) {
                        combinedList2.addAll(uiHighSettingQO.getAssertionQOList().getWebTitles());
                    }
                    jsonStr = objectMapper.writeValueAsString(combinedList2);
                    if (jsonStr != null) {
                        uiHighSetting.setAssertionJson(jsonStr);
                    }
                    //其他设置
                    if (uiHighSettingQO.getOtherSettingsQO() != null) {
                        jsonStr = objectMapper.writeValueAsString(uiHighSettingQO.getOtherSettingsQO());
                        uiHighSetting.setOtherSetting(jsonStr);
                    }
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
                uiHighSettingMapper.insertUiHighSetting(uiHighSetting);
            }
        }
        //修改步骤数
        UiAutomation automationUpdate = new UiAutomation();
        automationUpdate.setId(automationId);
        automationUpdate.setStepsNumber(uiSceneStepsQOList.size());
        uiAutomationMapper.updateUiAutomation(automationUpdate);
        return automationId;
    }


    /**
     * 修改ui自动化
     *
     * @param uiAutomationDataQO ui自动化
     * @return 结果
     */
    @Override
    @Transactional
    public Long updateUiAutomation(UiAutomationDataQO uiAutomationDataQO) {
        UiAutomation automationUpdate = new UiAutomation();
        automationUpdate.setUpdateBy(SecurityUtils.getUsername());
        automationUpdate.setUpdateTime(DateUtils.getNowDate());
        BeanUtils.copyProperties(uiAutomationDataQO, automationUpdate);
        //修改场景
        uiAutomationMapper.updateUiAutomation(automationUpdate);
        //修改场景步骤 先删除 再新增
        uiSceneStepsMapper.deleteUiSceneStepsById(uiAutomationDataQO.getId());
        //修改高级设置 先删除 再新增
        UiSceneSteps uiSceneStepsDelete = new UiSceneSteps();
        uiSceneStepsDelete.setAutomationId(uiAutomationDataQO.getId());
        uiSceneStepsDelete.setDelFlag(0);
        List<UiSceneSteps> uiSceneStepsList = uiSceneStepsMapper.selectUiSceneStepsList(uiSceneStepsDelete);
        for (UiSceneSteps sceneSteps : uiSceneStepsList) {
            uiHighSettingMapper.deleteUiHighSettingById(sceneSteps.getId());
        }
        for (UiSceneStepsQO uiSceneStepsQO : uiAutomationDataQO.getUiSceneStepsVOList()) {
            UiSceneSteps uiSceneSteps = new UiSceneSteps();
            BeanUtils.copyProperties(uiSceneStepsQO, uiSceneSteps);
            uiSceneSteps.setAutomationId(uiAutomationDataQO.getId());
            uiSceneSteps.setUpdateBy(SecurityUtils.getUsername());
            uiSceneSteps.setUpdateTime(DateUtils.getNowDate());
            uiSceneSteps.setCreateTime(DateUtils.getNowDate());
            uiSceneSteps.setCreateBy(SecurityUtils.getUsername());
            uiSceneSteps.setDelFlag(0);
            uiSceneStepsMapper.insertUiSceneSteps(uiSceneSteps);
            Long stepsId = uiSceneSteps.getId();
            for (UiHighSettingQO uiHighSettingQO : uiSceneStepsQO.getUiHighSettingVOList()) {
                UiHighSetting uiHighSetting = new UiHighSetting();
                BeanUtils.copyProperties(uiHighSettingQO, uiHighSetting);
                uiHighSetting.setDelFlag(0);
                uiHighSetting.setSceneStepsId(stepsId);
                uiHighSetting.setUpdateBy(SecurityUtils.getUsername());
                uiHighSetting.setUpdateTime(DateUtils.getNowDate());
                uiHighSetting.setCreateBy(SecurityUtils.getUsername());
                uiHighSetting.setCreateTime(DateUtils.getNowDate());
                try {
                    List<DataExtractionQO> combinedList1 = new ArrayList<>();
                    // 安全添加 windowExtractions
                    if (uiHighSettingQO.getDataExtractionQOList() != null &&
                            uiHighSettingQO.getDataExtractionQOList().getWindowExtractions() != null) {
                        combinedList1.addAll(uiHighSettingQO.getDataExtractionQOList().getWindowExtractions());
                    }
                    // 安全添加 elementExtractions
                    if (uiHighSettingQO.getDataExtractionQOList() != null &&
                            uiHighSettingQO.getDataExtractionQOList().getElementExtractions() != null) {
                        combinedList1.addAll(uiHighSettingQO.getDataExtractionQOList().getElementExtractions());
                    }
                    //数据提取
                    String jsonStr = objectMapper.writeValueAsString(combinedList1);
                    if (jsonStr != null) {
                        uiHighSetting.setExtractionDataJson(jsonStr);
                    }
                    // 断言
                    List<AssertionQO> combinedList2 = new ArrayList<>();
                    // 安全添加 popupTexts
                    if (uiHighSettingQO.getAssertionQOList() != null &&
                            uiHighSettingQO.getAssertionQOList().getPopupTexts() != null) {
                        combinedList2.addAll(uiHighSettingQO.getAssertionQOList().getPopupTexts());
                    }
                    // 安全添加 elementAssertions
                    if (uiHighSettingQO.getAssertionQOList() != null &&
                            uiHighSettingQO.getAssertionQOList().getElementAssertions() != null) {
                        combinedList2.addAll(uiHighSettingQO.getAssertionQOList().getElementAssertions());
                    }
                    // 安全添加 dropdownBoxes
                    if (uiHighSettingQO.getAssertionQOList() != null &&
                            uiHighSettingQO.getAssertionQOList().getDropdownBoxes() != null) {
                        combinedList2.addAll(uiHighSettingQO.getAssertionQOList().getDropdownBoxes());
                    }
                    // 安全添加 webTitles
                    if (uiHighSettingQO.getAssertionQOList() != null &&
                            uiHighSettingQO.getAssertionQOList().getWebTitles() != null) {
                        combinedList2.addAll(uiHighSettingQO.getAssertionQOList().getWebTitles());
                    }
                    jsonStr = objectMapper.writeValueAsString(combinedList2);
                    if (jsonStr != null) {
                        uiHighSetting.setAssertionJson(jsonStr);
                    }
                    //其他设置
                    if (uiHighSettingQO.getOtherSettingsQO() != null) {
                        jsonStr = objectMapper.writeValueAsString(uiHighSettingQO.getOtherSettingsQO());
                        uiHighSetting.setOtherSetting(jsonStr);
                    }
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
                uiHighSettingMapper.insertUiHighSetting(uiHighSetting);
            }

        }
        //修改步骤数
        automationUpdate = new UiAutomation();
        automationUpdate.setId(uiAutomationDataQO.getId());
        automationUpdate.setStepsNumber(uiAutomationDataQO.getUiSceneStepsVOList().size());
        uiAutomationMapper.updateUiAutomation(automationUpdate);
        return uiAutomationDataQO.getId();
    }

    /**
     * 批量删除ui自动化
     *
     * @param ids 需要删除的ui自动化主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUiAutomationByIds(Long[] ids) {
        //删除场景步骤和高级设置
        for (Long id : ids) {
            UiSceneSteps uiSceneSteps = new UiSceneSteps();
            uiSceneSteps.setAutomationId(id);
            uiSceneSteps.setDelFlag(0);
            List<UiSceneSteps> uiSceneStepsList = uiSceneStepsMapper.selectUiSceneStepsList(uiSceneSteps);
            for (UiSceneSteps sceneSteps : uiSceneStepsList) {
                uiHighSettingMapper.deleteUiHighSettingById(sceneSteps.getId());
            }
            uiSceneStepsMapper.deleteUiSceneStepsById(id);
        }
        return uiAutomationMapper.deleteUiAutomationByIds(ids);
    }

    /**
     * 删除ui自动化信息
     *
     * @param id ui自动化主键
     * @return 结果
     */
    @Override
    public int deleteUiAutomationById(Long id) {
        return uiAutomationMapper.deleteUiAutomationById(id);
    }
}
