package com.testor.module.emergency.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.testor.biz.sys.dict.data.model.domain.SysDictData;
import com.testor.biz.sys.dict.data.service.SysDictDataService;
import com.testor.biz.sys.org.model.domain.SysOrg;
import com.testor.biz.sys.org.service.SysOrgService;
import com.testor.common.util.excel.LocalDateTimeConverter;
import com.testor.ddd.safetyControl.infrastructure.repository.space.dao.TSafeSpaceDao;
import com.testor.ddd.safetyControl.infrastructure.uitls.SpaceExcelTemplate.TemplateEntity;
import com.testor.ddd.safetyControl.interfaces.model.dto.space.TSafeSpaceDTOParam;
import com.testor.ddd.safetyControl.interfaces.model.vo.space.TSafeSpaceVO;
import com.testor.module.emergency.model.dto.TEmergencyGoodsDTO;
import com.testor.module.emergency.model.dto.TEmergencysDTO;
import com.testor.module.emergency.model.execl.ExportTemplate;
import com.testor.module.emergency.model.vo.TEmergencyGoodsVO;
import com.testor.module.emergency.model.vo.TEmergencyVO;
import com.testor.module.emergency.service.TEmergencyGoodsService;
import com.tongtech.tfw.backend.common.biz.models.BaseResponse;
import com.tongtech.tfw.backend.common.biz.models.BizGeneralResponse;
import com.tongtech.tfw.backend.common.context.ContextUtils;
import com.tongtech.tfw.backend.common.models.supers.SuperController;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import com.tongtech.tfw.backend.core.helper.TypeHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 应急物资Controller
 *
 * @author testor-framework
 * @date 2022-10-08 17:31:31
 */
@Validated
@RestController
@RequestMapping("/emergency/goods")
@Api(value = "TEmergencyGoods", tags = "应急物资")
@Slf4j
public class TEmergencyGoodsController extends SuperController {
    @Autowired
    private TEmergencyGoodsService tEmergencyGoodsService;

    @Autowired
    private TSafeSpaceDao tSafeSpaceDao;

    @Value("${ureport.path}")
    private String path;

    @Resource
    private HttpServletResponse response;

    @Autowired
    private SysOrgService sysOrgService;

    @Autowired
    private SysDictDataService sysDictDataService;

    @Resource
    private HttpServletRequest request;

    /* Generated Method*/
    @ApiOperation(value = "新增 应急物资", notes = "Add TEmergencyGoods")
    @PostMapping(value = "/add")
    public BaseResponse<BizGeneralResponse> addEntity(@Valid @RequestBody TEmergencysDTO tEmergencysDTO) {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
        Boolean aBoolean = tEmergencyGoodsService.addEntity(tEmergencysDTO);
        baseResponse.setData(
                BizGeneralResponse.builder().result(TypeHelper.castToString(aBoolean)).build());
        return baseResponse;
    }

    @ApiOperation(value = "获取应急物资详情 ", notes = "Get TEmergencyGoods By Id")
    @GetMapping(value = "/get/particulars")
    public BaseResponse<TEmergencyVO> getParticulars(String id) {
        BaseResponse<TEmergencyVO> baseResponse = new BaseResponse<>();
        if (StringHelper.isNotEmpty(id)) {
            // TODO 按需求添加业务异常判断
            TEmergencyVO data = tEmergencyGoodsService.getParticulars(id);
            baseResponse.setData(data);
        }
        return baseResponse;
    }

    @ApiOperation(value = "确认点检 ", notes = "Get TEmergencyGoods By Id")
    @GetMapping(value = "/confirmSpotChecks")
    public BaseResponse<BizGeneralResponse> confirmSpotChecks(String id) {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
        if (StringHelper.isNotEmpty(id)) {
            String[] array = id.split(",");
            List<String> list = new ArrayList<>(Arrays.asList(array));
            for (String s : list) {
                Boolean result = tEmergencyGoodsService.confirmSpotChecks(s);
                baseResponse.setData(
                        BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
            }
        }
        return baseResponse;
    }

    @ApiOperation(value = "获取应急物资列表 ", notes = "")
    @PostMapping(value = "/page")
    public BaseResponse<Page<TEmergencyGoodsVO>> getPage(@RequestBody TEmergencyGoodsDTO tEmergencyGoodsDTO) {
        BaseResponse<Page<TEmergencyGoodsVO>> baseResponse = new BaseResponse<>();
        if (ObjectUtil.isNotEmpty(tEmergencyGoodsDTO)) {
            Page<TEmergencyGoodsVO> data = tEmergencyGoodsService.pages(tEmergencyGoodsDTO);
            baseResponse.setData(data);
        }
        return baseResponse;
    }

    @ApiOperation(value = "修改 应急物资 ", notes = "Update TEmergencyGoods By Id")
    @PutMapping(value = "/update")
    public BaseResponse<BizGeneralResponse> updateEntity(@Valid @RequestBody TEmergencysDTO tEmergencysDTO) {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();

        boolean result = tEmergencyGoodsService.updateEntity(tEmergencysDTO);
        baseResponse.setData(
                BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());

        return baseResponse;
    }

    @ApiOperation(value = "删除 应急物资 ", notes = "delete TEmergencyGoods By Id")
    @GetMapping(value = "/delete")
    public BaseResponse<BizGeneralResponse> deleteEntity(String id) {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();

        boolean result = tEmergencyGoodsService.deleteEntity(id);
        baseResponse.setData(
                BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());

        return baseResponse;
    }

    @ApiOperation(value = "导入应急物资", notes = "")
    @PostMapping("/importGoods")
    public BaseResponse<String> importGoods(@RequestParam("file") MultipartFile file) throws Exception {
        return tEmergencyGoodsService.importGoods(file);
    }

    @ApiOperation(value = "应急物资模板下载", notes = "")
    @PostMapping("/importTemplate")
    public BaseResponse<String> importTemplate(HttpServletResponse response) throws Exception {
        String orgId = ContextUtils.getLoginUser().getOrgId();
        List<TemplateEntity> orgList = findOrgList(orgId);
        List<SysDictData> list = sysDictDataService.list(new QueryWrapper<SysDictData>()
                .eq("dict_id", "518cfb65ca4944378fd40c3f66c0276d").eq("status", "0").eq("parent_id", "0"));
        List<ExportTemplate> exportTemplates = new ArrayList<>();
        for (SysDictData sysDictData : list) {
            List<Object> sysDictDataList = sysDictDataService.listObjs(new QueryWrapper<SysDictData>().select("dict_value").eq("parent_id", sysDictData.getDictDataId()).eq("status", "0"));
            if (sysDictDataList.size() > 0) {
                List<String> names = (List<String>) (List) sysDictDataList;
                for (String name : names) {
                    ExportTemplate exportTemplate = new ExportTemplate();
                    exportTemplate.setType(sysDictData.getDictValue());
                    exportTemplate.setName(name);
                    exportTemplates.add(exportTemplate);
                }
            }
        }
        TSafeSpaceDTOParam tSafeSpaceDTOParam = new TSafeSpaceDTOParam();
        tSafeSpaceDTOParam.setOrgId(orgId);
        tSafeSpaceDTOParam.setLevel(2);
        List<TSafeSpaceVO> tSafeSpaceVOS = tSafeSpaceDao.listPageByWorkArea(tSafeSpaceDTOParam);

        String fileName = URLEncoder.encode("应急物资导入模板", "utf-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/x-download;charset=utf-8");
        response.setHeader("Content-disposition", URLEncoder.encode(fileName, "UTF-8"));
//mime类型
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".xlsx");
        response.setHeader("Pragma", "No-cache");

        ExcelWriter excelWriter = null;
        ServletOutputStream outputStream = null;

        try (InputStream templatePathName = this.getClass().getClassLoader().getResourceAsStream("excel/yjwzdrmb.xlsx")) {
            outputStream = response.getOutputStream();
            excelWriter = EasyExcel.write(outputStream).registerConverter(new LocalDateTimeConverter()).withTemplate(templatePathName).build();
            WriteSheet writeSheet2 = EasyExcel.writerSheet(2).build();
            excelWriter.write(orgList, writeSheet2);
            WriteSheet writeSheet3 = EasyExcel.writerSheet(3).build();
            excelWriter.write(exportTemplates, writeSheet3);
            WriteSheet writeSheet4 = EasyExcel.writerSheet(4).build();
            excelWriter.fill(tSafeSpaceVOS, writeSheet4);
        } catch (IOException e) {
            // 处理异常
        } finally {
            if (excelWriter != null) {
                excelWriter.finish();
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    // 处理异常
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 获取企业信息
     * @return
     */
    public List<TemplateEntity> findOrgList(String orgId){
        List<SysOrg> orgList;
        if(!StrUtil.isBlank(orgId)) {
            SysOrg org = sysOrgService.getById(orgId);
            orgList = new ArrayList<>();
            orgList.add(org);
        } else {
            orgList = sysOrgService.list();
        }
//        List<SysOrg> orgList = orgService.list();
//        if(orgList == null || orgList.size() == 0) {
//            return null;
//        }
        List<TemplateEntity> templateEntityList = orgList.stream().map(p -> new TemplateEntity(p.getOrgName(), p.getOrgCode())).collect(Collectors.toList());
        return templateEntityList;
    }



    @ApiOperation(value = "导出应急物资", notes = "")
    @PostMapping("/exportGoods")
    public void exportGoods(@RequestBody TEmergencyGoodsDTO tEmergencyGoodsDTO) throws Exception {
        tEmergencyGoodsService.exportGoods(response, tEmergencyGoodsDTO);
    }
}
