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

import cn.hutool.json.JSON;
import com.alibaba.fastjson.JSONArray;
import com.bonus.gs.sub.evaluate.evaluate.beans.PersonBean;
import com.bonus.gs.sub.evaluate.evaluate.dao.PersonDao;
import com.bonus.gs.sub.evaluate.manager.utils.AesCbcUtils;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

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

/**
 * @ClassName: PersonServiceImpl
 * @author: tqzhang
 * @Date: 2024/12/20 9:28
 * @version: 1.0
 * @description:
 */
@Service("personService")
@Slf4j
public class PersonServiceImpl implements PersonService {
    @Resource
    private PersonDao dao;
    @Resource
    private BCryptPasswordEncoder passwordEncoder;

    @Value("${user.password}")
    private String password;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxRes addPersonInfo(PersonBean o) {
        AjaxRes ar = new AjaxRes();
        try {
            String personList = o.getPersonList();
            List<PersonBean> list = JSONArray.parseArray(personList, PersonBean.class);
            list.forEach(personBean -> {
                personBean.setSex("男".equals(personBean.getSex()) ? "1" : "0");
                personBean.setPassword(passwordEncoder.encode(password));
               // personBean.setEvaluatePassWord(AesCbcUtils.encrypt(password));
                personBean.setEvaluatePassWord(password);
            });
            for (PersonBean personBean : list) {
                dao.addPersonInfo(personBean);
            }
            dao.addPersonRole(list);
            dao.updateOldUser(list);
            ar.setSucceed(GlobalConst.SAVE_SUCCEED);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            ar.setFailMsg("添加失败");
        }
        return ar;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxRes updatePerson(PersonBean o) {
        AjaxRes ar = new AjaxRes();
        try {
            dao.deletePersonRole(o.getId());
            dao.updatePerson(o);
            dao.addPersonRoleById(o);
            ar.setSucceed(GlobalConst.UPDATE_SUCCEED);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            ar.setFailMsg("修改失败");
        }
        return ar;
    }
}
