/*
*  Copyright 2019-2025 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package com.aircraft.modules.system.service.impl;

import com.aircraft.base.BaseEntity;
import com.aircraft.modules.security.service.UserCacheManager;
import com.aircraft.modules.system.domain.EmEmployees;
import com.aircraft.modules.system.domain.vo.EmEmployeesDetailVo;
import com.aircraft.modules.system.domain.vo.EmEmployeesVo;
import com.aircraft.modules.system.service.EmAreaService;
import com.aircraft.modules.system.service.EmScenicService;
import com.aircraft.utils.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.aircraft.modules.system.service.EmEmployeesService;
import com.aircraft.modules.system.domain.dto.EmEmployeesQueryCriteria;
import com.aircraft.modules.system.mapper.EmEmployeesMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;

/**
* @description 服务实现
* @author lhb
* @date 2025-07-08
**/
@Service
@RequiredArgsConstructor
public class EmEmployeesServiceImpl extends ServiceImpl<EmEmployeesMapper, EmEmployees> implements EmEmployeesService {

    private final EmEmployeesMapper emEmployeesMapper;
    private final EmAreaService areaService;
    private final EmScenicService scenicService;
    private final PasswordEncoder passwordEncoder;
    private final UserCacheManager userCacheManager;

    @Override
    public PageResult<EmEmployees> queryAll(EmEmployeesQueryCriteria criteria, Page<Object> page){
        return PageUtil.toPage(emEmployeesMapper.findAll(criteria, page));
    }

    @Override
    public List<EmEmployees> queryAll(EmEmployeesQueryCriteria criteria){
        return emEmployeesMapper.findAll(criteria);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(EmEmployeesVo resources) {
        EmEmployees emEmployees = this.findByUsername(resources.getUsername());
        if (emEmployees != null) {
            throw new RuntimeException("用户名已存在！");
        }
        emEmployees = new EmEmployees();
        BeanUtils.copyProperties(resources, emEmployees);
        emEmployees.setPassword(passwordEncoder.encode("123456"));
        emEmployees.setDelFlag(0);
        emEmployees.setStatus("1");
        emEmployeesMapper.insert(emEmployees);
    }

    public EmEmployees findByUsername(@NotBlank String username) {
        QueryWrapper<EmEmployees> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(EmEmployees::getUsername,username)
                .eq(BaseEntity::getDelFlag,0);
        return emEmployeesMapper.selectOne(queryWrapper);
    }

    @Override
    public List<EmEmployees> obtainEmployeesByIds(List<Long> orderInitiatorIds) {
        return this.list(Wrappers.lambdaQuery(EmEmployees.class).in(EmEmployees::getId,orderInitiatorIds));
    }

    @Override
    public EmEmployees findByUserName(String currentUsername) {
        QueryWrapper<EmEmployees> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(EmEmployees::getUsername,currentUsername)
                .eq(EmEmployees::getDelFlag,0);
        return this.emEmployeesMapper.selectOne(queryWrapper);
    }

    @Override
    public void updatePass(String username, String encryptPassword) {
        emEmployeesMapper.updatePass(username, encryptPassword);
        userCacheManager.cleanEmployeesCache(username);
    }

    @Override
    public List<EmEmployees> list(EmEmployees example) {
        return this.list(buildWrapper(example));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(EmEmployees resources) {
        EmEmployees emEmployees = getById(resources.getId());
        emEmployees.copy(resources);
        emEmployeesMapper.updateById(emEmployees);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(List<Long> ids) {
        emEmployeesMapper.deleteBatchIds(ids);
    }

    @Override
    public void download(List<EmEmployees> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (EmEmployees emEmployees : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("姓名", emEmployees.getName());
            map.put("电话", emEmployees.getPhone());
            map.put("员工状态", emEmployees.getStatus());
            map.put("创建时间", emEmployees.getCreateTime());
            map.put("更新时间", emEmployees.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public PageResult<EmEmployeesDetailVo> page(EmEmployeesDetailVo example, Page page) {
        page.setOptimizeCountSql(false);
        return PageUtil.toPage(this.baseMapper.findByExample(buildWrapper(example),page));
    }

    /**
     * 构建查询
     *
     * @param example
     * @return
     */
    private QueryWrapper<EmEmployeesDetailVo> buildWrapper(EmEmployeesDetailVo example) {
        String name = example.getName();
        QueryWrapper<EmEmployeesDetailVo> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .like(StringUtils.isNotEmpty(name), EmEmployees::getName, name)
                .eq(BaseEntity::getDelFlag,0);
        return wrapper;
    }

    /**
     * 构建查询
     *
     * @param example
     * @return
     */
    private QueryWrapper<EmEmployees> buildWrapper(EmEmployees example) {
        String name = example.getName();
        Long areaId = example.getAreaId();
        QueryWrapper<EmEmployees> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .like(StringUtils.isNotEmpty(name), EmEmployees::getName, name)
                .eq(null!=areaId,EmEmployees::getAreaId,example.getAreaId())
                .eq(BaseEntity::getDelFlag,0);
        return wrapper;
    }

    @Override
    public List<EmEmployees> findByScenicId(Long areaId) {
        QueryWrapper<EmEmployees> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(EmEmployees::getAreaId, areaId)
                .eq(EmEmployees::getDelFlag, 0);
        return super.list(wrapper);
    }

    @Override
    public EmEmployeesDetailVo findById(Integer id) {
        EmEmployeesDetailVo emEmployeesDetailVo = new EmEmployeesDetailVo();
        EmEmployees emEmployees = getById(id);
        BeanUtils.copyProperties(emEmployees, emEmployeesDetailVo);
        if (emEmployees.getAreaId()!=null){
            emEmployeesDetailVo.setAreaName(areaService.findById(emEmployees.getAreaId()).getName());
            if (emEmployees.getScenicId() != null) {
                emEmployeesDetailVo.setScenicName(scenicService.getById(emEmployeesDetailVo.getScenicId()).getName());
            }
        }
        return emEmployeesDetailVo;
    }

}