package com.bonus.gs.sub.evaluate.evaluate.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bonus.gs.sub.evaluate.evaluate.beans.SetTemplateBean;
import com.bonus.gs.sub.evaluate.evaluate.beans.SubClassBean;
import com.bonus.gs.sub.evaluate.evaluate.dao.SetTemplateDao;
import com.bonus.gs.sub.evaluate.manager.utils.AjaxRes;
import com.bonus.gs.sub.evaluate.manager.utils.GlobalConst;
import com.bonus.gs.sub.evaluate.manager.utils.UserUtil;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: SetTemplateServiceImpl
 * @author: tqzhang
 * @Date: 2024/12/18 15:09
 * @version: 1.0
 * @description: 模板配置
 */
@Service("setTemplateService")
public class SetTemplateServiceImpl implements SetTemplateService {
    @Resource
    private SetTemplateDao dao;

    /**
     * 获取模板列表
     *
     * @param o
     * @return
     */
    @Override
    public List<SetTemplateBean> getTemplateList(SetTemplateBean o) {
        return dao.getTemplateList(o);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxRes addTemplate(SetTemplateBean o) {
        AjaxRes ar = new AjaxRes();
        try {
            int code = dao.checkIsExistTemplateName(o);
            if (code > 0) {
                ar.setRes(GlobalConst.FAIL);
                ar.setResMsg("模板名称已存在");
                return ar;
            }
            o.setCreateUser(UserUtil.getLoginUser().getUsername());
            o.setCreateUserId(String.valueOf(UserUtil.getLoginUser().getId()));
            if (o.getId() == null || o.getId().isEmpty() || "0".equals(o.getId())) {
                dao.addTemplate(o);
            } else {
                o.setVersion(String.valueOf(Integer.parseInt(o.getVersion()) + 1));
                dao.updateTemplate(o);
            }
            String jsonTxt = o.getJsonTxt();
            if (jsonTxt != null && !"".equals(jsonTxt)) {
               List<SetTemplateBean> templateBeans = convertJsonToBeans(jsonTxt);
                for (SetTemplateBean templateBean : templateBeans) {
                     templateBean.setTemplateId(o.getId());
                     templateBean.setParentId(o.getId());
                     templateBean.setTemplateName(o.getName());
                     templateBean.setVersion(StringUtils.isEmpty(o.getVersion()) ? "1" : o.getVersion());
                     templateBean.setChildNum(templateBean.getSubClass().size() + "");
                     dao.addTemplateDetails(templateBean);
                     List<SubClassBean> subClassBeans = templateBean.getSubClass();
                     for (SubClassBean subClassBean : subClassBeans) {
                          subClassBean.setParentId(templateBean.getId());
                          subClassBean.setTemplateId(o.getId());
                          subClassBean.setTemplateName(o.getName());
                          subClassBean.setId(templateBean.getId());
                          subClassBean.setVersion(StringUtils.isEmpty(o.getVersion()) ? "1" : o.getVersion());
                          dao.addTwoLevelTemplateDetails(subClassBean);
                     }
                }
            }
            ar.setRes(GlobalConst.SUCCEED);
            if (o.getId() == null || o.getId().isEmpty() || "0".equals(o.getId())) {
                ar.setResMsg("添加成功");
            } else {
                ar.setResMsg("修改成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            ar.setRes(GlobalConst.FAIL);
            if (o.getId() == null || "".equals(o.getId())) {
                ar.setResMsg("添加失败");
            } else {
                ar.setResMsg("修改失败");
            }
            return ar;
        }
        return ar;
    }

    @Override
    public Integer changeEnable(SetTemplateBean o) {
        // 先全部改为未启用状态
        dao.setTemplatePass();
        // 再把当前模板改成启用
        return dao.changeEnable(o);
    }

    public static List<SetTemplateBean> convertJsonToBeans(String jsonString) {
        JSONArray jsonArray = JSONArray.parseArray(jsonString);
        List<SetTemplateBean> templateBeans = new ArrayList<>();

        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            SetTemplateBean templateBean = new SetTemplateBean();
            templateBean.setIndexName(jsonObject.getString("indexName"));
            templateBean.setStandardScore(jsonObject.getInteger("standardScore"));
            templateBean.setTotal(jsonObject.getString("total"));
            templateBean.setCollectType(jsonObject.getString("collect"));

            JSONArray subClassArray = jsonObject.getJSONArray("subClass");
            List<SubClassBean> subClassBeans = new ArrayList<>();
            for (int j = 0; j < subClassArray.size(); j++) {
                JSONObject subClassObject = subClassArray.getJSONObject(j);
                SubClassBean subClassBean = new SubClassBean();
                subClassBean.setSubIndexName(subClassObject.getString("subIndexName"));
                subClassBean.setSubStandardScore(subClassObject.getString("subStandardScore"));
                subClassBean.setResponsibleDepartment(subClassObject.getString("responsibleDepartment"));
                subClassBean.setSubIndexDefinition(subClassObject.getString("subIndexDefinition"));
                subClassBean.setSubIntegralStandard(subClassObject.getString("subIntegralStandard"));
                subClassBean.setSub(subClassObject.getString("sub"));
                subClassBeans.add(subClassBean);
            }
            templateBean.setSubClass(subClassBeans);
            templateBeans.add(templateBean);
        }
        return templateBeans;
    }
}
