package com.zehong.web.controller.system;

import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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.utils.SecurityUtils;
import com.zehong.system.domain.vo.GasUserAndSafetyDeviceVo;
import com.zehong.system.domain.vo.UserManageGasUserExportVo;
import com.zehong.system.domain.vo.YeHuaqiUserManageSafetyDeviceExportVo;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.beans.factory.annotation.Autowired;
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.TYehuaqiUser;
import com.zehong.system.service.ITYehuaqiUserService;
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-09-14
 */
@RestController
@RequestMapping("/system/yehuaqiUser")
public class TYehuaqiUserController extends BaseController
{
    @Autowired
    private ITYehuaqiUserService tYehuaqiUserService;

    /**
     * 查询燃气用户列表
     */
    @GetMapping("/list")
    public TableDataInfo list(TYehuaqiUser tYehuaqiUser)
    {
        startPage();
        List<TYehuaqiUser> list = tYehuaqiUserService.selectTYehuaqiUserList(tYehuaqiUser);
        return getDataTable(list);
    }

    /**
     * 导出燃气用户列表
     */
    @Log(title = "燃气用户", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TYehuaqiUser tYehuaqiUser)
    {
        List<TYehuaqiUser> list = tYehuaqiUserService.selectTYehuaqiUserList(tYehuaqiUser);
        ExcelUtil<TYehuaqiUser> util = new ExcelUtil<TYehuaqiUser>(TYehuaqiUser.class);
        return util.exportExcel(list, "燃气用户数据");
    }

    /**
     * 获取燃气用户详细信息
     */
    @GetMapping(value = "/{userId}")
    public AjaxResult getInfo(@PathVariable("userId") Long userId)
    {
        return AjaxResult.success(tYehuaqiUserService.selectTYehuaqiUserById(userId));
    }

    /**
     * 新增燃气用户
     */
    @Log(title = "燃气用户", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TYehuaqiUser tYehuaqiUser)
    {
        return toAjax(tYehuaqiUserService.insertTYehuaqiUser(tYehuaqiUser));
    }

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

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

    /**
     * 删除燃气用户
     */
    @Log(title = "燃气用户", businessType = BusinessType.DELETE)
	@DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds)
    {
        return toAjax(tYehuaqiUserService.deleteTYehuaqiUserByIds(userIds));
    }
    @GetMapping("/allList")
    public TableDataInfo allList(TYehuaqiUser tYehuaqiUser)
    {
        List<TYehuaqiUser> list = tYehuaqiUserService.selectAllUserList(tYehuaqiUser);
        return getDataTable(list);
    }


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

    /**
     * 自定义-模版下载
     * @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 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<TYehuaqiUser> yehuaqiUsers = tYehuaqiUserService.queryErrorDetectorUserList();

            List<UserManageGasUserExportVo> userManageGasUserExportVos = new ArrayList<>();
            for (TYehuaqiUser yehuaqiUser : yehuaqiUsers) {
                UserManageGasUserExportVo userManageGasUserExportVo = new UserManageGasUserExportVo();
                BeanUtils.copyProperties(yehuaqiUser,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();
        }
    }

    /**
     * 自定义模版的多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);
            tYehuaqiUserService.handleCustomMoreSheetImportData(userManageGasUserobjects,null,updateSupport,true);

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

            return AjaxResult.success();
        }
    }


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

        //获取用户信息
        SysUser user = SecurityUtils.getLoginUser().getUser();
        yehuaqiUser.setBeyondEnterpriseId(user.getDeptId());
        List<TYehuaqiUser> yehuaqiUsers = tYehuaqiUserService.selectForExportTYehuaqiUserList(yehuaqiUser);

        //判断是否是 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<YeHuaqiUserManageSafetyDeviceExportVo> userManageSafetyDeviceExportVoList = new ArrayList<>();
            for (TYehuaqiUser  yehuaqiUser1 : yehuaqiUsers) {
                List<YeHuaqiUserManageSafetyDeviceExportVo> userManageSafetyDeviceExportVos = yehuaqiUser1.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",yehuaqiUsers);
            if(userManageSafetyDeviceExportVoList.size() > 0) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                for (YeHuaqiUserManageSafetyDeviceExportVo userManageSafetyDeviceExportVo : userManageSafetyDeviceExportVoList) {
                    if (userManageSafetyDeviceExportVo.getfDeviceInstallTime() != null) {
                        String format = sdf.format(userManageSafetyDeviceExportVo.getfDeviceInstallTime());
                        userManageSafetyDeviceExportVo.setfDeviceInstallTimeStr(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();
        }
    }

}
