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.InitiateEvaluateBean;
import com.bonus.gs.sub.evaluate.evaluate.beans.SubBean;
import com.bonus.gs.sub.evaluate.evaluate.beans.SubClassBean;
import com.bonus.gs.sub.evaluate.evaluate.dao.InitiateEvaluateDao;
import com.bonus.gs.sub.evaluate.manager.model.SysUser;
import com.bonus.gs.sub.evaluate.manager.utils.AjaxRes;
import com.bonus.gs.sub.evaluate.manager.utils.GlobalConst;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.sql.SQLType;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 * @ClassName: InitiateEvaluateServiceImpl
 * @author: tqzhang
 * @Date: 2024/12/19 9:12
 * @version: 1.0
 * @description:
 */
@Service("initiateEvaluateService")
@Slf4j
public class InitiateEvaluateServiceImpl implements InitiateEvaluateService {
    @Resource
    private InitiateEvaluateDao dao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteInitiateEvaluateById(String id) {
        try {
            int deleteCount = dao.deleteInitiateEvaluateById(id);
            if (deleteCount > 0) {
                return dao.deleteInitiateEvaluateLink(id);
            } else {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return 0;
            }
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return 0;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxRes submitInitiateEvaluate(InitiateEvaluateBean o) {
        AjaxRes ar = new AjaxRes();
        System.out.println("submitInitiateEvaluate:" + o);
        try {
            String subInfo = o.getSubInfo();
            JSONArray jsonArray = JSONArray.parseArray(subInfo);
            int count = dao.checkIsExistEvaluate(o);
            if (count > 0) {
                ar.setFailMsg("当前事业部在"+o.getEvaluateDate()+"已经发起过评价，请勿重复发起!!!");
                return ar;
            }
            //判断是否已经发起过评价
            dao.deleteInitiateLink(o.getId());
            String json = dao.getTemplationJson(o.getTemplateId());
            JSONArray templationArr = JSONArray.parseArray(json);
            //循环templationArr 获取responsibleDepartment对其进行整合
            Set<String> deptSet = new HashSet<>();
            for (int i = 0; i < templationArr.size(); i++) {
                JSONObject jsonObject = templationArr.getJSONObject(i);
                if (jsonObject.containsKey("subClass")) {
                    JSONArray subClassArray = jsonObject.getJSONArray("subClass");
                    for (int j = 0; j < subClassArray.size(); j++) {
                        JSONObject subClassObject = subClassArray.getJSONObject(j);
                        String[] departments = subClassObject.getString("responsibleDepartment").split(",");
                        deptSet.addAll(Arrays.asList(departments));
                    }
                }
            }
            String[] arr = deptSet.toArray(new String[0]);
            System.out.println("arr:" + Arrays.toString(arr));
            if (arr.length == 0) {
                ar.setFailMsg("评价模板中没有负责部门，请重新选择");
                return ar;
            }
            List<String > idsList = new ArrayList<>();
            List<String > deptIdList = new ArrayList<>();
            for (String deptId : arr) {
                if ("0".equals(deptId)) {
                    List<SysUser> sysUsers = dao.getProUserIdByDeptId(jsonArray);
                    String ids = sysUsers.stream()
                            .map(sysUser -> sysUser.getId().toString())
                            .collect(Collectors.joining(","));
                    if (StringUtils.isBlank(ids)) {
                        ar.setFailMsg("部门下没有评价人员，请重新选择");
                        return ar;
                    }
                    idsList.add(ids);
                    deptIdList.add(deptId);
//                    dao.insertPjTaskEvaluate(o.getId(), ids, deptId, "1");
                }else if("-1".equals(deptId)){
                    List<SysUser> sysUsers = dao.getBusinessDivisionUserIdByDeptId(o.getOrgId());
                    String ids = sysUsers.stream()
                            .map(sysUser -> sysUser.getId().toString())
                            .collect(Collectors.joining(","));
                    if (StringUtils.isBlank(ids)) {
                        ar.setFailMsg("事业部下没有评价人员，请重新选择");
                        return ar;
                    }
                    idsList.add(ids);
                    deptIdList.add(deptId);
//                    dao.insertPjTaskEvaluate(o.getId(), ids, deptId, "1");
                }else {
                    // arr删除值为0的元素
                    String[] arr1 = Arrays.stream(arr).filter(s -> !s.equals("0")).toArray(String[]::new);
                    List<SysUser> sysUsers = dao.getUserIdByDeptId(deptId);
                    String ids = sysUsers.stream()
                            .map(sysUser -> sysUser.getId().toString())
                            .collect(Collectors.joining(","));
                    if (StringUtils.isBlank(ids)) {
                        ar.setFailMsg("部门下没有人员，请重新选择");
                        return ar;
                    }
                    idsList.add(ids);
                    deptIdList.add(deptId);
                }
            }
            SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM");
            SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy年MM月");
            String formattedDate = outputFormat.format(inputFormat.parse(o.getEvaluateDate()));
            o.setTemplateTitle(formattedDate + "外包商对标考核统计表");
            if ("add".equals(o.getType())) {
                dao.insertInitiateEvaluate(o);
                dao.insertInitiateEvaluateLink(jsonArray, o.getId());
            } else {
                dao.updateInitiateEvaluate(o);
                dao.insertInitiateEvaluateLink(jsonArray, o.getId());
            }
            dao.deletePjTaskEvaluate(o.getId());
            List<String> uniqueIdsList = new ArrayList<>();
            idsList.stream()
                    .map(ids -> Arrays.stream(ids.split(",")).distinct().collect(Collectors.joining(",")))
                    .forEach(uniqueIdsList::add);
            List<String> uniqueDeptIdList = deptIdList.stream().distinct().collect(Collectors.toList());
            IntStream.range(0, uniqueIdsList.size()).forEach(i -> dao.insertPjTaskEvaluate(o.getId(), uniqueIdsList.get(i),
                    uniqueDeptIdList.get(i), ("0".equals(uniqueDeptIdList.get(i)) || "-1".equals(uniqueDeptIdList.get(i))) ? "1" : "0"));
            ar.setRes(GlobalConst.SUCCEED);
        } catch (Exception e) {
            log.error(e.toString(),e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            ar.setFailMsg(GlobalConst.DATA_FAIL);
            return ar;
        }
        return ar;
    }

    @Override
    public AjaxRes getInitiateEvaluateDetails(InitiateEvaluateBean bean) {
        AjaxRes ar = new AjaxRes();
        InitiateEvaluateBean result = dao.getInitiateEvaluateDetails(bean);
        List<SubBean> subList = dao.getSubInfo(result.getId());
        result.setSubList(subList);
        ar.setSucceed(result);
        return ar;
    }
}
