package com.zehong.web.controller.supervise;

import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.zehong.common.core.domain.entity.SysUser;
import com.zehong.common.core.domain.model.LoginUser;
import com.zehong.common.utils.SecurityUtils;
import com.zehong.common.utils.ServletUtils;
import com.zehong.framework.web.service.TokenService;
import com.zehong.system.domain.TDetectorUserCount;
import com.zehong.system.domain.vo.UserManageGasUserExportVo;
import com.zehong.system.domain.vo.GasUserAndSafetyDeviceVo;
import com.zehong.system.domain.vo.TDetectorUserInspectVo;
import com.zehong.system.domain.vo.UserManageSafetyDeviceExportVo;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.zehong.common.annotation.Log;
import com.zehong.common.core.controller.BaseController;
import com.zehong.common.core.domain.AjaxResult;
import com.zehong.common.enums.BusinessType;
import com.zehong.system.domain.TDetectorUser;
import com.zehong.system.service.ITDetectorUserService;
import com.zehong.common.utils.poi.ExcelUtil;
import com.zehong.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

/**
 * 燃气用户Controller
 *
 * @author zehong
 * @date 2022-02-07
 */
@RestController
@RequestMapping("/supervise/user")
public class TDetectorUserController extends BaseController
{
    @Autowired
    private ITDetectorUserService tDetectorUserService;
    @Autowired
    private TokenService tokenService;

    @Autowired
    Environment environment;

    /**
     * 查询燃气用户列表
     */
    @GetMapping("/list")
    public TableDataInfo list(TDetectorUser tDetectorUser)
    {
        //获取用户信息
        SysUser user = SecurityUtils.getLoginUser().getUser();
        tDetectorUser.setBeyondEnterpriseId(user.getDeptId());
        startPage();
        List<TDetectorUser> list = tDetectorUserService.selectTDetectorUserList(tDetectorUser);
        return getDataTable(list);
    }

    /**
     * 查询用户安检状态
     * @param tDetectorUser
     * @return
     */
    @GetMapping("/liststatus")
    public TableDataInfo liststatus(TDetectorUser tDetectorUser)
    {
        //获取用户信息
        SysUser user = SecurityUtils.getLoginUser().getUser();
        tDetectorUser.setBeyondEnterpriseId(user.getDeptId());
        startPage();
        List<TDetectorUser> list = tDetectorUserService.selectTDetectorListstatus(tDetectorUser);
        return getDataTable(list);
    }

    /**
     * 获取燃气用户统计信息
     */
    @GetMapping("/userStatistics")
    public AjaxResult userStatistics()
    {
        //获取当前登录用户信息
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        TDetectorUserCount tDetectorUserCount = tDetectorUserService.userStatistics(user.getDeptId());
        return AjaxResult.success(tDetectorUserCount);
    }

    /**
     * 获取探测器用户列表
     * @return
     */
    @GetMapping("/detectorUserList")
    public AjaxResult detectorUserList(TDetectorUser tDetectorUser){
        return AjaxResult.success(tDetectorUserService.detectorUserList(tDetectorUser));
    }

    /**
     * 获取探测器用户列表 大屏地图 massMarks 标注的方式
     * @return ajaxResult
     */
    @GetMapping("/massMarksDetectorUserList")
    public AjaxResult massMarksDetectorUserList(TDetectorUser tDetectorUser){
        return AjaxResult.success(tDetectorUserService.detectorUserList(tDetectorUser));
    }

    /**
     * 获取探测器用户列表 大屏地图 labelsLayer 标注的方式
     * @return ajaxResult
     */
    @GetMapping("/labelsLayerMarksDetectorUserList")
    public AjaxResult labelsLayerMarksDetectorUserList(TDetectorUser tDetectorUser){
        return AjaxResult.success(tDetectorUserService.labelsLayerMarksDetectorUserList(tDetectorUser));
    }


    /**
     * 获取探测器用户列表 大屏地图 labelsLayer 标注的方式 分页查询 居民用户
     * @param tDetectorUser t
     * @return r
     */
    @GetMapping("/pageQueryLabelsLayerMarksDUser")
    public TableDataInfo pageQueryLabelsLayerMarksDUser(TDetectorUser tDetectorUser) {
        return tDetectorUserService.pageQueryLabelsLayerMarksDUser(tDetectorUser);
    }

    /**
     * 获取探测器用户列表 大屏地图 labelsLayer 标注的方式
     * @return ajaxResult
     */
    @GetMapping("/labelsLayerMarksDUserVillageSafDevInfoMap")
    public AjaxResult labelsLayerMarksDUserVillageSafDevInfoMap(TDetectorUser tDetectorUser){
        return AjaxResult.success(tDetectorUserService.labelsLayerMarksDUserVillageSafDevInfoMap(tDetectorUser));
    }

    /**
     * 获取探测器用户列表
     * @return
     */
    @GetMapping("/getDetectorUserAlarmList")
    public AjaxResult getDetectorUserAlarmList(){
        return AjaxResult.success(tDetectorUserService.getDetectorUserAlarmList());
    }

    /**
     * 导出燃气用户列表
     */
    @Log(title = "燃气用户", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TDetectorUser tDetectorUser)
    {
        //获取用户信息
        SysUser user = SecurityUtils.getLoginUser().getUser();
        tDetectorUser.setBeyondEnterpriseId(user.getDeptId());
        //老的导出把居住区隐藏
        ExcelUtil.hiddencolumns.add(10);
        List<TDetectorUser> list = tDetectorUserService.selectTDetectorUserList(tDetectorUser);
        ExcelUtil<TDetectorUser> util = new ExcelUtil<TDetectorUser>(TDetectorUser.class);
        AjaxResult ajaxResult = util.exportExcel(list, "燃气用户数据");
        ExcelUtil.hiddencolumns.clear();
        return ajaxResult;
    }

    /**
     * 导出燃气用户列表-new 有居住区的导出
     */
    @Log(title = "燃气用户", businessType = BusinessType.EXPORT)
    @GetMapping("/newExport")
    public AjaxResult newExport(TDetectorUser tDetectorUser)
    {
        //获取用户信息
        SysUser user = SecurityUtils.getLoginUser().getUser();
        tDetectorUser.setBeyondEnterpriseId(user.getDeptId());
        List<TDetectorUser> list = tDetectorUserService.newSelectTDetectorUserList(tDetectorUser);
        ExcelUtil<TDetectorUser> util = new ExcelUtil<TDetectorUser>(TDetectorUser.class);
        return util.exportExcel(list, "燃气用户数据");
    }
    /**
     * 获取燃气用户详细信息
     */
    @GetMapping(value = "/{userId}")
    public AjaxResult getInfo(@PathVariable("userId") Long userId)
    {
        return AjaxResult.success(tDetectorUserService.selectTDetectorUserById(userId));
    }

    /**
     * 新增燃气用户
     */
    @Log(title = "燃气用户", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TDetectorUser tDetectorUser)
    {
        //获取用户信息
        //SysUser user = SecurityUtils.getLoginUser().getUser();
        //tDetectorUser.setBeyondEnterpriseId(user.getDeptId());
        return toAjax(tDetectorUserService.insertTDetectorUser(tDetectorUser));
    }

    /**
     * 新增燃气用户和安全装置
     */
    @PostMapping("/addUserAndSafetyDevice")
    public AjaxResult addUserAndSafetyDevice(@RequestBody GasUserAndSafetyDeviceVo gasUserAndSafetyDeviceVo) {
        return toAjax(tDetectorUserService.addUserAndSafetyDevice(gasUserAndSafetyDeviceVo));
    }

    /**
     * 修改燃气用户和安全装置
     */
    @PostMapping("/updateUserAndSafetyDevice")
    public AjaxResult updateUserAndSafetyDevice(@RequestBody GasUserAndSafetyDeviceVo gasUserAndSafetyDeviceVo) {
        return toAjax(tDetectorUserService.updateUserAndSafetyDevice(gasUserAndSafetyDeviceVo));
    }
    /**
     * 修改燃气用户
     */
    @Log(title = "燃气用户", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TDetectorUser tDetectorUser)
    {
        return toAjax(tDetectorUserService.updateTDetectorUser(tDetectorUser));
    }

    /**
     * 删除燃气用户
     */
    @Log(title = "燃气用户", businessType = BusinessType.DELETE)
	@DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds)
    {
        return toAjax(tDetectorUserService.deleteTDetectorUserByIds(userIds));
    }

    /**
     * 获取用户安检信息
     * @param inspectVo
     * @return
     */
    @GetMapping("/getDetectorUserInspectInfo")
    public TableDataInfo getDetectorUserInspectInfo(TDetectorUserInspectVo inspectVo){
        //获取用户信息
        SysUser user = SecurityUtils.getLoginUser().getUser();
        inspectVo.setBeyondEnterpriseId(user.getDeptId());
        startPage();
        return  getDataTable(tDetectorUserService.getDetectorUserInspectInfo(inspectVo));
    }


    /**
     * 导出用户安检信息导出
     */
    @Log(title = "用户安检信息导出", businessType = BusinessType.EXPORT)
    @GetMapping("/detectorUserExport")
    public AjaxResult detectorUserExport(TDetectorUserInspectVo inspectVo)
    {
        //获取用户信息
        SysUser user = SecurityUtils.getLoginUser().getUser();
        inspectVo.setBeyondEnterpriseId(user.getDeptId());
        List<TDetectorUserInspectVo> list = tDetectorUserService.getDetectorUserInspectInfo(inspectVo);
        ExcelUtil<TDetectorUserInspectVo> util = new ExcelUtil<>(TDetectorUserInspectVo.class);
        return util.exportExcel(list, "用户安检数据");
    }



    /**
     * 模版下载
     * @return r
     */
    @GetMapping("/importTemplate")
    public AjaxResult importTemplate()
    {
        ExcelUtil<UserManageGasUserExportVo> util = new ExcelUtil<>(UserManageGasUserExportVo.class);
        return util.importTemplateExcel("燃气用户数据");
    }

    /**
     * 文件导入
     * @param file f
     * @param updateSupport u
     * @return r
     * @throws Exception r
     */
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport, HttpServletResponse response) throws Exception
    {
        ExcelUtil<UserManageGasUserExportVo> util = new ExcelUtil<>(UserManageGasUserExportVo.class);
        List<UserManageGasUserExportVo> XmbhList = util.importExcel(file.getInputStream());
        String operName = SecurityUtils.getLoginUser().getUsername();
        String message = tDetectorUserService.importEmployedPeopleInfo(XmbhList, updateSupport, operName,response);
        return AjaxResult.success(message);
    }

    /**
     * 自定义-模版下载-正确数据导出
     * @param response r
     * @param tDetectorUser t
     */
    @GetMapping("/exportSuccessData")
    public void exportSuccessData(HttpServletResponse response,TDetectorUser tDetectorUser) {

        //获取用户信息
        SysUser user = SecurityUtils.getLoginUser().getUser();
        tDetectorUser.setBeyondEnterpriseId(user.getDeptId());
        List<TDetectorUser> tDetectorUsers = tDetectorUserService.selectForExportTDetectorUserList(tDetectorUser);

        //判断是否是 windows环境，
        String osName = System.getProperty("os.name").toLowerCase();

        try {
            File file;

            //如果是本地或测试环境
            if (osName.contains("windows")) {

                String filePath = "importTemplate/燃气用户导出模版.xlsx";

                //用来读取resources下的文件
                Resource resource = new ClassPathResource(filePath);
                file = resource.getFile();
            } else {
                file = ResourceUtils.getFile("/data/java/baseversion/importTemplate/燃气用户导出模版.xlsx");
            }

            List<UserManageSafetyDeviceExportVo> userManageSafetyDeviceExportVoList = new ArrayList<>();
            for (TDetectorUser tDetectorUserDb : tDetectorUsers) {
                List<UserManageSafetyDeviceExportVo> userManageSafetyDeviceExportVos = tDetectorUserDb.getUserManageSafetyDeviceExportVos();
                if (userManageSafetyDeviceExportVos != null && userManageSafetyDeviceExportVos.size() > 0) {
                    userManageSafetyDeviceExportVoList.addAll(userManageSafetyDeviceExportVos);
                }
            }

            TemplateExportParams params = new TemplateExportParams(file.getAbsolutePath(), true);
            Map<String, Object> total = new HashMap<>();
            total.put("gasUserMaplist",tDetectorUsers);
            if(userManageSafetyDeviceExportVoList.size() > 0) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                for (UserManageSafetyDeviceExportVo userManageSafetyDeviceExportVo : userManageSafetyDeviceExportVoList) {
                    if (userManageSafetyDeviceExportVo.getDeviceInstallTime() != null) {
                        String format = sdf.format(userManageSafetyDeviceExportVo.getDeviceInstallTime());
                        userManageSafetyDeviceExportVo.setDeviceInstallTimeStr(format);
                    }
                }
            }
            total.put("safetyDeviceMaplist",userManageSafetyDeviceExportVoList);
            Workbook workbook = ExcelExportUtil.exportExcel(params, total);

            String fileName = "燃气用户数据.xlsx";
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

            OutputStream outputStream = response.getOutputStream();

            workbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
            workbook.close();

        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 自定义-模版下载-带有错误数据
     * @param response r
     * @throws IOException i
     */
    @GetMapping("/exportErrorData")
    public void exportErrorData(HttpServletResponse response) throws IOException {

        //判断是否是 windows环境，
        String osName = System.getProperty("os.name").toLowerCase();

        try {
            File file;

            //如果是本地或测试环境
            if (osName.contains("windows")) {

                String filePath = "importTemplate/燃气用户错误导入数据模版.xlsx";

                //用来读取resources下的文件
                Resource resource = new ClassPathResource(filePath);
                file = resource.getFile();
            } else {
                file = ResourceUtils.getFile("/data/java/baseversion/importTemplate/燃气用户错误导入数据模版.xlsx");
            }

            List<TDetectorUser> tDetectorUsers = tDetectorUserService.queryErrorDetectorUserList();

            List<UserManageGasUserExportVo> userManageGasUserExportVos = new ArrayList<>();
            for (TDetectorUser tDetectorUser : tDetectorUsers) {
                UserManageGasUserExportVo userManageGasUserExportVo = new UserManageGasUserExportVo();
                BeanUtils.copyProperties(tDetectorUser,userManageGasUserExportVo);
                userManageGasUserExportVos.add(userManageGasUserExportVo);
            }

            TemplateExportParams params = new TemplateExportParams(file.getAbsolutePath(), true);
            Map<String, Object> total = new HashMap<>();
            total.put("maplist",userManageGasUserExportVos);
            Workbook workbook = ExcelExportUtil.exportExcel(params, total);

            String fileName = "燃气用户错误导入数据模版.xlsx";
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

            OutputStream outputStream = response.getOutputStream();

            workbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
            workbook.close();

        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 自定义-模版下载
     * @param response r
     * @throws IOException i
     */
    @GetMapping("/downloadTemplate")
    public void downloadTemplate(HttpServletResponse response) throws IOException {

        //判断是否是 windows环境，
        String osName = System.getProperty("os.name").toLowerCase();

        try {
            File file;

            //如果是本地或测试环境
            if (osName.contains("windows")) {

                String filePath = "importTemplate/燃气用户导入模版.xlsx";

                //用来读取resources下的文件
                Resource resource = new ClassPathResource(filePath);
                file = resource.getFile();
            } else {
                file = ResourceUtils.getFile("/data/java/baseversion/importTemplate/燃气用户导入模版.xlsx");
            }

            // 获取文件名
            String filename = file.getName();

            // 将文件写入输入流
            FileInputStream fileInputStream = new FileInputStream(file);
            InputStream fis = new BufferedInputStream(fileInputStream);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();

            // 清空response
            response.reset();
            // 设置response的Header
            response.setCharacterEncoding("UTF-8");
            //Content-Disposition的作用：告知浏览器以何种方式显示响应返回的文件，用浏览器打开还是以附件的形式下载到本地保存
            //attachment表示以附件方式下载   inline表示在线打开   "Content-Disposition: inline; filename=文件名.mp3"
            // filename表示文件的默认名称，因为网络传输只支持URL编码的相关支付，因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
            // 告知浏览器文件的大小
            response.addHeader("Content-Length", "" + file.length());
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            outputStream.write(buffer);
            outputStream.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }


    /**
     * 自定义模版的导入
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("/importCustom")
    public AjaxResult importData(MultipartFile file,boolean updateSupport) throws Exception {
        List<UserManageGasUserExportVo> dataInfos = ExcelUtil.importExcel(file, 1, 2, UserManageGasUserExportVo.class);
        if(dataInfos != null && dataInfos.size() > 0) {
            tDetectorUserService.handleCustomImportData(dataInfos,updateSupport);
        }
        return AjaxResult.success();
    }

    /**
     * 自定义模版的多sheet导入
     * @param file f
     * @return r
     * @throws Exception e
     */
    @PostMapping("/moreSheetImportExcel")
    public AjaxResult moreSheetImportExcel(MultipartFile file,boolean updateSupport) throws Exception {

        String originalFilename = file.getOriginalFilename();
        if (originalFilename != null && originalFilename.contains("错误")) {
            List<UserManageGasUserExportVo> userManageGasUserobjects = ExcelUtil.moreSheetImportExcel(file, 1, 2, UserManageGasUserExportVo.class, 0);
            tDetectorUserService.handleCustomMoreSheetImportData(userManageGasUserobjects,null,updateSupport,true);

            return AjaxResult.success();
        } else{
            List<UserManageGasUserExportVo> userManageGasUserobjects = ExcelUtil.moreSheetImportExcel(file, 1, 2, UserManageGasUserExportVo.class, 0);
            List<UserManageSafetyDeviceExportVo> userManageSafetyobjects = ExcelUtil.moreSheetImportExcel(file, 1, 2, UserManageSafetyDeviceExportVo.class, 1);
            tDetectorUserService.handleCustomMoreSheetImportData(userManageGasUserobjects,userManageSafetyobjects,updateSupport,false);

            return AjaxResult.success();
        }
    }

    /**
     * 查询当前用户导入 燃气用户错误的数据
     * @return i
     */
    @GetMapping("/countImportError")
    public AjaxResult countImportError()
    {
        int i = tDetectorUserService.countByBeyondEnterpriseId();
        return AjaxResult.success(i);
    }

    /**
     * 清除当前用户导入 燃气用户错误的数据
     */
    @Log(title = "燃气用户错误导入记录", businessType = BusinessType.EXPORT)
    @GetMapping("/clearImportError")
    public AjaxResult clearImportError()
    {
        return AjaxResult.success(tDetectorUserService.clearImportErrorByEnterpriseId());
    }
}
