package com.org.web.person.service;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.org.system.config.security.Md5PasswordEncoder;
import com.org.system.entity.SysRole;
import com.org.system.entity.SysUser;
import com.org.system.enums.YesOrNoState;
import com.org.system.service.SysDataDictionaryItemService;
import com.org.system.service.SysUserRoleService;
import com.org.system.service.SysUserService;
import com.org.utils.SecurityUtil;
import com.org.utils.exception.CustomException;
import com.org.web.person.domain.BcPersonFamily;
import com.org.web.person.domain.BcPersonService;
import com.org.web.person.mapper.BcPersonServiceMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class BcPersonServiceService extends ServiceImpl<BcPersonServiceMapper, BcPersonService> {


    @Autowired
    SysUserService sysUserService;

    @Autowired
    SysUserRoleService sysUserRoleService;

    @Autowired
    BcPersonFamilyService familyService;

    @Autowired
    SysDataDictionaryItemService sysDataDictionaryItemService;


    @Transactional(rollbackFor = Exception.class)
    public boolean executeSaveOrUpdate(BcPersonService person) {
        log.info("BcPersonServiceService - executeSaveOrUpdate person:{}", person);
        if (null == person.getId()) {
            return executeSave(person);
        } else {
            return executeUpdate(person);
        }
    }


    // 新增人员
    private boolean executeSave(BcPersonService person) {

        // 新建用户
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(person, sysUser);
        sysUser.setUserName(person.getIdCardNo());
        sysUser.setNickName(person.getName());

        sysUser.setSalt(DigestUtil.md5Hex(sysUser.getUserName()));
        Md5PasswordEncoder md5PasswordEncoder = Md5PasswordEncoder.getInstance();
        md5PasswordEncoder.setSalt(sysUser.getSalt());
        sysUser.setPassword(md5PasswordEncoder.encode(SysUser.DEFAULT_PASSWORD));

        sysUser.setStatus(1);
        sysUser.setCreateTime(new Date());
        sysUser.setIsDelete(YesOrNoState.NO.getState());
        sysUserService.save(sysUser);

        // 保存用户角色信息
        sysUserRoleService.save(sysUser.getId(), CollectionUtil.newArrayList(SysRole.SERVICE_ROLE));


        // 新增人员信息
        person.setId(sysUser.getId()); // 人员的id为sysUser的id
        person.setCreateTime(new Date());
        person.setIsDelete(YesOrNoState.NO.getState());
        this.save(person);

        // 新增家庭成员子表数据
        familyService.executeSaveOrUpdate(person.getId(), person.getFamilyList());

        return true;
    }

    private boolean executeUpdate(BcPersonService person) {
        person.setUpdateBy(SecurityUtil.getUserId());
        person.setUpdateTime(new Date());

        BcPersonService oldPerson = getById(person.getId());
        if (ObjectUtil.isNull(oldPerson)) {
            throw new CustomException("人员不存在");
        }

        // 修改用户
        SysUser sysUser = sysUserService.getById(person.getId());
        if (ObjectUtil.isNull(sysUser)) {
            throw new CustomException("未查询到用户信息");
        }

        sysUser.setUserName(person.getIdCardNo());
        sysUser.setNickName(person.getName());
        sysUser.setName(person.getName());
        sysUser.setIdCardNo(person.getIdCardNo());
        sysUser.setPhone(person.getPhone());
        sysUserService.saveOrUpdate(sysUser);

        // 编辑家庭成员子表数据
        familyService.executeSaveOrUpdate(person.getId(), person.getFamilyList());

        return updateById(person);
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean del(Long id) {
        log.info("BcPersonServiceService - del id:{}", id);

        BcPersonService person = getById(id);
        if (ObjectUtil.isNull(person)) {
            throw new CustomException("删除数据不存在");
        }
        person.setIsDelete(YesOrNoState.YES.getState());
        person.setDeleteBy(SecurityUtil.getUserId());
        person.setDeleteTime(new Date());

        // 删除用户
        sysUserService.del(CollectionUtil.newArrayList(person.getId()), "人员删除");

        // 删除家庭成员
        familyService.delByPersonId(person.getId());

        return updateById(person);
    }

    /**
     * 详情
     */
    public BcPersonService get(Long id) {
        log.info("BcPersonServiceService - get id:{}", id);

        BcPersonService person = getById(id);

        // 查询家庭成员
        List<BcPersonFamily> familyList = familyService.listByPersonId(id);

        person.setFamilyList(familyList);

        return person;
    }

    /**
     * 列表查询
     */
    public List<BcPersonService> queryList(BcPersonService person) {
        log.info("BcPersonServiceService - queryList person:{}", person);

        List<BcPersonService> list = baseMapper.queryList(person);
        for (BcPersonService personVO : list) {
            if (null != personVO.getJobs()) {
                personVO.setJobsName(sysDataDictionaryItemService.findDictonaryBydictonaryCode("0050", personVO.getJobs()));
            }
        }
        return list;
    }
}
