package com.infoepoch.pms.dispatchassistant.domain.basic.role;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.infoepoch.pms.dispatchassistant.common.exception.ValidationException;
import com.infoepoch.pms.dispatchassistant.common.utils.StringUtils;
import com.infoepoch.pms.dispatchassistant.domain.basic.user.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Service
public class RoleFileService {

    @Autowired
    private IRoleRepository roleRepository;
    @Autowired
    IUserRoleRepository userRoleRepository;

    /**
     * 角色关联用户导出
     *
     * @param roleId
     * @param departmentId
     * @param request
     * @param response
     */
    public void roleExport(String roleId, String departmentId, HttpServletRequest request, HttpServletResponse response) {
        Role role = roleRepository.selectById(roleId);
        if (role == null)
            throw new ValidationException("角色标识不合法");
        if (StringUtils.isBlank(departmentId))
            departmentId = "5262";//根组织
        List<User> userList = userRoleRepository.selectSelectedUserByRoleId(roleId, departmentId);
        List<RoleExcelData> dataList = new ArrayList<>();
        for (User user : userList) {
            RoleExcelData data = new RoleExcelData(
                    roleId,
                    role.getName(),
                    user.getId(),
                    user.getFullname()
            );
            dataList.add(data);
        }
        roleExport(dataList, request, response);
    }

    /**
     * 角色关联用户导出
     *
     * @param dataList
     * @param request
     * @param response
     */
    public void roleExport(List<RoleExcelData> dataList, HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("UTF-8");
            String fileName = URLEncoder.encode("角色关联用户列表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream())
                    .head(RoleExcelData.class)
                    .sheet("sheet1")
                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                    .doWrite(dataList);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ValidationException("导出角色关联用户列表失败");
        }
    }

}
