/**
 * Copyright 2018 人人开源 https://www.renren.io
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see .
 */
package com.epmet.controller;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.enums.WriteDirectionEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.excel.write.metadata.fill.FillWrapper;
import com.alibaba.fastjson.JSON;
import com.epmet.commons.tools.annotation.LoginUser;
import com.epmet.commons.tools.aop.NoRepeatSubmit;
import com.epmet.commons.tools.constant.NumConstant;
import com.epmet.commons.tools.dto.result.CustomerStaffInfoCacheResult;
import com.epmet.commons.tools.exception.EpmetErrorCode;
import com.epmet.commons.tools.exception.ExceptionUtils;
import com.epmet.commons.tools.exception.RenException;
import com.epmet.commons.tools.page.PageData;
import com.epmet.commons.tools.redis.common.CustomerStaffRedis;
import com.epmet.commons.tools.security.dto.TokenDto;
import com.epmet.commons.tools.utils.ConvertUtils;
import com.epmet.commons.tools.utils.Result;
import com.epmet.commons.tools.validator.ValidatorUtils;
import com.epmet.dto.IcResiUserDTO;
import com.epmet.dto.form.*;
import com.epmet.dto.result.*;
import com.epmet.feign.OperCustomizeOpenFeignClient;
import com.epmet.service.IcResiUserImportService;
import com.epmet.service.IcResiUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
/**
 * 用户基础信息
 *
 * @author generator generator@elink-cn.com
 * @since v1.0.0 2021-10-26
 */
@Slf4j
@RestController
@RequestMapping("icresiuser")
public class IcResiUserController {
    private static final String BASE_TABLE_NAME = "ic_resi_user";
    private Path IC_RESI_UPLOAD_DIR;
    @Autowired
    private OperCustomizeOpenFeignClient operCustomizeOpenFeignClient;
    @Autowired
    private IcResiUserService icResiUserService;
    @Autowired
    private IcResiUserImportService icResiUserImportService;
    {
        // 初始化上传目录
        String home = System.getProperty("user.home");
        Path importDir = Paths.get(home, "epmet_files", "ic_user_import");
        if (Files.notExists(importDir)) {
            try {
                Files.createDirectories(importDir);
            } catch (IOException e) {
                log.error("创建数字赋能平台上传目录失败");
            }
        }
        IC_RESI_UPLOAD_DIR = importDir;
    }
    @PostMapping("delete")
    public Result delete(@LoginUser TokenDto tokenDto,@RequestBody DelIcResiUserFormDTO formDTO){
        formDTO.setCustomerId(tokenDto.getCustomerId());
        ValidatorUtils.validateEntity(formDTO,DelIcResiUserFormDTO.IdGroup.class);
        icResiUserService.delete(formDTO);
        return new Result();
    }
    /**
     * @Author sun
     * @Description 党建互联平台--保存居民信息
     **/
    @PostMapping("add")
    public Result add(@LoginUser TokenDto tokenDto, @RequestBody List formDTO) {
        icResiUserService.add(tokenDto, formDTO);
        return new Result();
    }
    /**
     * @Author sun
     * @Description 党建互联平台--修改居民信息
     **/
    @PostMapping("edit")
    public Result edit(@LoginUser TokenDto tokenDto, @RequestBody List formDTO) {
        icResiUserService.edit(tokenDto, formDTO);
        return new Result();
    }
    /**
     * @Description 根据房间号查人
     * @Param formDTO
     * @Return {@link Result>}
     * @Author zhaoqifeng
     * @Date 2021/11/1 11:04
     */
    @PostMapping("getpeoplebyroom")
    public Result> getPeopleByRoom(@RequestBody IcResiUserDTO formDTO) {
        return new Result>().ok(icResiUserService.getPeopleByRoom(formDTO.getHomeId()));
    }
    @PostMapping("listresi")
    public Result>> queryListResi1(@LoginUser TokenDto tokenDto, @RequestBody IcResiUserPageFormDTO pageFormDTO) {
        //pageFormDTO.setCustomerId("45687aa479955f9d06204d415238f7cc");
        pageFormDTO.setCustomerId(tokenDto.getCustomerId());
        pageFormDTO.setStaffId(tokenDto.getUserId());
        ValidatorUtils.validateEntity(pageFormDTO, IcResiUserPageFormDTO.AddUserInternalGroup.class);
        return new Result>>().ok(icResiUserService.pageResiMap(pageFormDTO));
    }
    /**
     * 编辑页面,显示居民信息详情
     *
     * @param pageFormDTO
     * @return com.epmet.commons.tools.utils.Result
     * @author yinzuomei
     * @date 2021/10/28 10:29 上午
     */
    @PostMapping("detail")
    public Result queryIcResiDetail(@LoginUser TokenDto tokenDto, @RequestBody IcResiDetailFormDTO pageFormDTO) {
        //pageFormDTO.setCustomerId("45687aa479955f9d06204d415238f7cc");
        pageFormDTO.setCustomerId(tokenDto.getCustomerId());
        ValidatorUtils.validateEntity(pageFormDTO, IcResiDetailFormDTO.AddUserInternalGroup.class);
        return new Result().ok(icResiUserService.queryIcResiDetail(pageFormDTO));
    }
    /**
     * desc :备用 easypoi
     * @param customerId
     * @param pageFormDTO
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/exportExcel2")
    public void exportExcel(@RequestHeader String customerId,@LoginUser TokenDto tokenDto, @RequestBody IcResiUserPageFormDTO pageFormDTO, HttpServletResponse response) throws Exception {
        CustomerStaffInfoCacheResult staffInfoCacheResult = CustomerStaffRedis.getStaffInfo(customerId, tokenDto.getUserId());
        String staffOrgPath = null;
        if (StringUtils.isNotBlank(staffInfoCacheResult.getAgencyPIds()) && !NumConstant.ZERO_STR.equals(staffInfoCacheResult.getAgencyPIds())) {
            staffOrgPath = staffInfoCacheResult.getAgencyPIds().concat(":").concat(staffInfoCacheResult.getAgencyId());
        }else{
            staffOrgPath=staffInfoCacheResult.getAgencyId();
        }
        pageFormDTO.setCustomerId(customerId);
        pageFormDTO.setPageFlag(false);
        CustomerFormResultDTO resiFormItems = getResiFormAddItems(pageFormDTO.getCustomerId());
        Map> otherSheetItems = buildItemMap(resiFormItems);
        Map> resiMainList = icResiUserService.getDataForExport(otherSheetItems.get(BASE_TABLE_NAME),new HashMap<>(), pageFormDTO.getCustomerId(), pageFormDTO.getFormCode(), BASE_TABLE_NAME, pageFormDTO.getConditions(),staffInfoCacheResult.getAgencyId(),staffOrgPath);
        //resiMainList = (List