package com.ruoyi.web.controller.zdsz;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.ruoyi.common.convert.ExcelBigNumberConvert;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.zdsz.domain.vo.GExportsVo;
import com.ruoyi.zdsz.domain.vo.GImportVo;
import com.ruoyi.zdsz.service.*;
import lombok.RequiredArgsConstructor;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.*;

import cn.dev33.satoken.annotation.SaCheckPermission;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.core.validate.QueryGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.zdsz.domain.vo.ZAreaVo;
import com.ruoyi.zdsz.domain.bo.ZAreaBo;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 小区管理
 *
 * @author ruoyi
 * @date 2023-12-27
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/zdsz/area")
public class ZAreaController extends BaseController {

    private String bfb="0";
    private String message;

    private final IZAreaService iZAreaService;
    @Resource
    private IZBuildingService buildingService;
    @Resource
    private IZEngineeringCivilService civilService;
    @Resource
    private IZEngineeringMaterialsResetsService materialsResetsService;
    /**
     * 小区下拉
     *
     * @return
     */
    @GetMapping("/getAreaList")
    public R getArea(String district) {
        return R.ok(iZAreaService.getArea(district));
    }


    /**
     * 查询小区管理列表
     */
    @SaCheckPermission("zdsz:area:list")
    @GetMapping("/list")
    public TableDataInfo<ZAreaVo> list(ZAreaBo bo, PageQuery pageQuery) {
        return iZAreaService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出小区管理列表
     */
    @SaCheckPermission("zdsz:area:export")
    @Log(title = "小区管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response,ZAreaBo bo) {
        List<GImportVo> gExportsVos = iZAreaService.selectList(bo);
        ExcelUtil.exportExcel(gExportsVos, "小区管理", GImportVo.class, response);
    }

    /**
     * 获取小区管理详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("zdsz:area:query")
    @GetMapping("/{id}")
    public R<ZAreaVo> getInfo(@NotNull(message = "主键不能为空") @PathVariable String id) {
        return R.ok(iZAreaService.queryById(id));
    }

    /**
     * 新增小区管理
     */
    @SaCheckPermission("zdsz:area:add")
    @Log(title = "小区管理", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody ZAreaBo bo) {
        return toAjax(iZAreaService.insertByBo(bo));
    }

    /**
     * 修改小区管理
     */
    @SaCheckPermission("zdsz:area:edit")
    @Log(title = "小区管理", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody ZAreaBo bo) {
        return toAjax(iZAreaService.updateByBo(bo));
    }

    /**
     * 删除小区管理
     *
     * @param ids 主键串
     */
    @SaCheckPermission("zdsz:area:remove")
    @Log(title = "小区管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R remove(@NotEmpty(message = "主键不能为空") @PathVariable String[] ids) {
        //是否需要校验
//        int i = buildingService.getBuildingListByAreaId(Arrays.asList(ids));
//        if (i>0){
//            return R.fail("小区已关联楼栋不能删除!");
//        }
////        int j = civilService.getCivilByAreaId(Arrays.asList(ids));
////        if (j>0){
////            return R.fail("小区已关联民用工程不能删除!");
////        }
//        int k = materialsResetsService.getMaterialByAreaId(Arrays.asList(ids));
//        if (k>0){
//            return R.fail("小区已关联用料统计不能删除!");
//        }
        return toAjax(iZAreaService.deleteWithValidByIds(Arrays.asList(ids), true));
    }

    @GetMapping("/importTemplate")
    @Log(title = "下载导入模板", businessType = BusinessType.EXPORT)
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil.exportExcel(new ArrayList<>(), "小区", GImportVo.class, response);
    }

    /**
     * 批量下载生成文件夹打压缩包
     */
    @GetMapping("/upload")
    @Log(title = "批量下载生成文件夹打压缩包", businessType = BusinessType.EXPORT)
    public void upload(HttpServletRequest request, HttpServletResponse response, @RequestParam String id) throws Exception {
        iZAreaService.upload(request, response, id);
    }

    /**
     * 导出所属包功能
     */
    @Log(title = "导出所属包功能", businessType = BusinessType.EXPORT)
    @GetMapping("/exports")
    public void exports(@Validated ZAreaBo bo, HttpServletResponse response) {
        String filename = iZAreaService.getDictNameOfAffiliatedPackage(bo);
        List<GExportsVo> list = iZAreaService.getExport(bo);
        try {
            response.reset();
            FileUtils.setAttachmentResponseHeader(response, filename+ ".xlsx");
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8");
            ServletOutputStream os = response.getOutputStream();
            EasyExcel.write(os, GExportsVo.class)
                .autoCloseStream(false)
                // 自动适配
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                // 大数值自动转换 防止失真
                .registerConverter(new ExcelBigNumberConvert())
                .sheet(filename).doWrite(list);
        } catch (IOException e) {
            throw new RuntimeException("导出Excel异常");
        }

    }
    @Log(title = "导入小区列表", businessType = BusinessType.EXPORT)
    @PostMapping("/importData")
    public synchronized R<Void> importData(@RequestPart("file") MultipartFile file, boolean updateSupport) throws Exception {
        List<GImportVo> listVo = ExcelUtil.importExcel(file.getInputStream(), GImportVo.class);
        List<GImportVo> list = BeanUtil.copyToList(listVo, GImportVo.class);
        String operName = getUsername();
        if(Double.valueOf(bfb)<=0){
            forImportData(list,true,operName,0,0);
        }
        return  R.ok(message);
    }

    private void forImportData(List<GImportVo> list, Boolean isUpdateSupport, String operName,int n,int successNum) throws Exception
    {
        try{
            Map<String,Object> ret = iZAreaService.importUser(list, isUpdateSupport, operName,n,successNum);//list, updateSupport, operName，第几条
            if(Boolean.valueOf(ret.get("is_success").toString())){
                bfb = ret.get("bfb").toString();
                forImportData(list,isUpdateSupport,operName,Integer.valueOf(ret.get("n").toString()),Integer.valueOf(ret.get("successNum").toString()));
            }else{
                message = ret.get("successMsg").toString();
            }
        } catch (Exception e) {
            message = e.getMessage();
        }
    }
    /**
     * 进度条刷新，
     */
    @GetMapping(value = "/flushProgress")
    public R<Map> flushProgress() throws Exception
    {
        Map<String,String> ret = new HashMap<>();
        ret.put("bfb",bfb);
        ret.put("message",message);
        return R.ok(ret);
    }
    /**
     * 结束进度条刷新，
     */
    @GetMapping(value = "/clearFlushProgress")
    public R<Void> clearFlushProgress() throws Exception
    {
        bfb="0";
        message="";
        return R.ok();
    }
}
