package com.nantian.cloud.jljc.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nantian.cloud.jljc.dto.AuditorDto;
import com.nantian.cloud.jljc.entity.EnterpriseInfo;
import com.nantian.cloud.jljc.entity.RecordCertificateManager;
import com.nantian.cloud.jljc.entity.RecordPersonManager;
import com.nantian.cloud.jljc.service.EnterpriseInfoService;
import com.nantian.cloud.jljc.service.RecordCertificateManagerService;
import com.nantian.cloud.jljc.service.RecordPersonManagerService;
import com.nantian.cloud.jljc.vo.util.FileUtil;
import com.nantian.sc.cloud.common.core.util.R;
import com.nantian.sc.cloud.common.log.annotation.SysLog;
import com.nantian.sc.cloud.common.security.annotation.Inner;
import com.nantian.sc.cloud.common.security.service.ScUser;
import com.nantian.sc.cloud.common.security.util.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.xmlbeans.impl.piccolo.io.FileFormatException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;
import org.springframework.core.io.ClassPathResource;


/**
 * 备案管理-能源管理人员
 *
 * @date 2020-09-03
 */
@Slf4j
@CrossOrigin
@RestController
@AllArgsConstructor
@RequestMapping("/recordPersonManager")
@Api(value = "recordPersonManager", tags = "备案管理-能源管理人员")
public class RecordPersonManagerController {
    private final RecordPersonManagerService recordPersonManagerService;
    private final RecordCertificateManagerService recordCertificateManagerService;
    private final EnterpriseInfoService enterpriseInfoService;

    /**
     * 企业端根据查询条件获取能源管理人员信息
     */
    @GetMapping("/comp/selectAll")
    @SysLog("企业端根据查询条件获取能源管理人员信息")
    @ApiOperation(value = "企业端根据查询条件获取能源管理人员信息", notes = "企业端根据查询条件获取能源管理人员信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "epc", value = "企业社会信用代码", required = true, dataType = "string", paramType = "path"),
            @ApiImplicitParam(name = "year", value = "年度", required = false, dataType = "string", paramType = "path"),
            @ApiImplicitParam(name = "page", value = "分页对象", required = false, dataType = "json", paramType = "path")
    })
    public R getCompInfo(String epc, String year, Page page) {
       /* if (epc == null) {
            return R.failed("企业社会信用编码不能为空");
        } else {*/
            ScUser u = SecurityUtils.getUser();
            IPage personManagers = recordPersonManagerService.getCompInfoByCodeAndYear(page, u.getEnterpriseCode(), year);
            return personManagers != null ? R.ok(personManagers) : R.failed("获取能源管理人员信息失败！");

    }

    /**
     * 政府端根据查询条件获取能源管理人员信息
     */
    @GetMapping("/gov/selectAll")
    @SysLog("政府端根据查询条件获取能源管理人员信息")
    @ApiOperation(value = "政府端根据查询条件获取能源管理人员信息", notes = "政府端根据查询条件获取能源管理人员信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "姓名关键字", required = false, dataType = "string", paramType = "path"),
            @ApiImplicitParam(name = "enterpriseStr", value = "企业名称关键字", required = false, dataType = "string", paramType = "path"),
            @ApiImplicitParam(name = "year", value = "年度", required = false, dataType = "string", paramType = "path"),
            @ApiImplicitParam(name = "area", value = "地区编码", required = false, dataType = "json", paramType = "path"),
            @ApiImplicitParam(name = "trade", value = "行业编码", required = false, dataType = "json", paramType = "path"),
            @ApiImplicitParam(name = "Page", value = "分页对象", required = false, dataType = "json", paramType = "path")
    })
    public R getGovInfo( Page page,String name, String enterpriseStr, String year,String area, String trade) {
        //政府端获取能源人员信息，增加数据权限
        IPage personManagers = recordPersonManagerService.getGovInfoByCodeAndYear(page,name, enterpriseStr,year,area,trade);
        return personManagers != null ? R.ok(personManagers) : R.failed("获取能源管理人员信息失败！");
    }

    /**
     * 根据id获取能源管理人员信息
     */
    @GetMapping("/getById/{id}")
    @SysLog("根据id获取能源管理人员信息")
    @ApiOperation(value = "根据id获取能源管理人员信息", notes = "根据id获取能源管理人员信息")
    @ApiImplicitParam(name = "id", value = "能源管理人员信息id", required = true, dataType = "int", paramType = "path")
    public R getById(@PathVariable("id") Long id) {
        //人员信息
        RecordPersonManager personManager = recordPersonManagerService.getPersonById(id);
        //证书信息
        List<RecordCertificateManager> certificateList = recordCertificateManagerService.getCertificateByPersonId(id);
        Map<String, Object> map = new HashMap();
        map.put("personManager", personManager);
        map.put("certificateList", certificateList);
        return map != null ? R.ok(map) : R.failed("获取能源管理人员信息失败！");
    }

    /**
     * 新增能源管理人员信息（企业端）
     */
    @PostMapping("add")
    @SysLog("新增能源管理人员信息（企业端）")
    @ApiOperation(value = "新增能源管理人员信息（企业端）", notes = "新增能源管理人员信息（企业端）")
    @ApiImplicitParam(name = "RecordPersonManager", value = "能源管理人员信息对象", required = true, dataType = "json", paramType = "path")
    public R save(@RequestBody RecordPersonManager recordPersonManager) {
        recordPersonManager.setUpdateDate(new Date());
        recordPersonManager.setDeleteFlag("1");
        ScUser u= SecurityUtils.getUser();
        if (u.getId() != null) {
            recordPersonManager.setUpdateId(u.getId());
        }
        //获取企业信息
        EnterpriseInfo info = enterpriseInfoService.getInfoByCode(u.getEnterpriseCode());
        //企业端新增能源管理信息，添加deptid
        recordPersonManager.setDeptId(info != null && info.getRegionCode()!=null ? Integer.parseInt(info.getRegionCode()) : u.getDeptId());
        boolean flag = recordPersonManagerService.save(recordPersonManager);
        return flag ? R.ok("新增能源管理人员信息成功") : R.failed("新增能源管理人员信息失败");
    }

    /**
     * 下载模板文件
     */
    @GetMapping(value = "/download")
    @SysLog("下载能源管理人员模板文件")
    @ApiOperation(value = "下载模板文件", notes = "下载模板文件")
    public R download(HttpServletRequest request, HttpServletResponse response) {
        try {
            //URL url = getClass().getClassLoader().getResource("mouldFile/RecordPersonManagerMouldFile.xls");
            URL url = new ClassPathResource("mouldFile/RecordPersonManagerMouldFile.xls").getURL();
            log.info("获取文件url:" + url);
            // 通过url获取File的绝对路径
            File f = new File(url.getFile());
            if (!f.exists()) {
                return R.failed("路径有误，文件不存在！");
            }
            log.info("获取文件的绝对路径:" + f + "，文件长度：" + f.length());
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/x-download;charset=utf-8");
            response.setHeader("Content-disposition", URLEncoder.encode(f.getName(), "UTF-8"));
            //mime类型
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(f.getName(), "UTF-8"));
            response.setHeader("Pragma", "No-cache");
            //从内存中写出来
            OutputStream outputStream = response.getOutputStream();
            outputStream.write(FileUtil.file2byte(f));
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.ok("导出模板文件成功");
    }

    /**
     * 导出excel
     */
    @Inner(value = false)
    @GetMapping("excelExport")
    @SysLog("导出能源管理人员")
    @ApiOperation(value = "导出excel", notes = "导出excel（企业名称关键字和社会信用编码二选一），企业端导出填写企业编码；政府端导出填写企业名称关键字")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "enterpriseStr", value = "企业名称关键字", required = false, dataType = "string", paramType = "path"),
            @ApiImplicitParam(name = "enterpriseCode", value = "企业社会信用编码", required = false, dataType = "string", paramType = "path"),
            @ApiImplicitParam(name = "year", value = "年度", required = false, dataType = "string", paramType = "path"),
            @ApiImplicitParam(name = "area", value = "地区编码", required = false, dataType = "json", paramType = "path"),
            @ApiImplicitParam(name = "trade", value = "行业编码", required = false, dataType = "json", paramType = "path"),
    })
    public R excelExport(HttpServletResponse response, String enterpriseStr, String enterpriseCode, String year, String area, String trade) throws
            Exception {
        return recordPersonManagerService.excelExport(response, enterpriseStr, enterpriseCode, year, area, trade);
    }

    /**
     * 导入excel
     */
    @PostMapping("excelImport")
    @SysLog("导入能源管理人员")
    @ApiOperation(value = "导入excel", notes = "导入excel")
    @ApiImplicitParam(name = "file", value = "文件", required = true, dataType = "file", paramType = "path")
    public R excelImport(@RequestParam MultipartFile file) throws FileFormatException {
        return recordPersonManagerService.excelImport(file);
    }

    /**
     * 根据id修改能源管理人员信息
     */
    @PutMapping("update")
    @SysLog("根据id修改能源管理人员信息")
    @ApiOperation(value = "根据id修改能源管理人员信息", notes = "根据id修改能源管理人员信息")
    @ApiImplicitParam(name = "RecordPersonManager", value = "能源管理人员信息对象", required = true, dataType = "json", paramType = "path")
    public R updateById(@RequestBody RecordPersonManager recordPersonManager) {
        if(recordPersonManager.getUpdateDate() == null){
            recordPersonManager.setUpdateDate(new Date());
        }
        ScUser u= SecurityUtils.getUser();
        if (u.getId() != null) {
            recordPersonManager.setUpdateId(u.getId());
        }
        boolean flag = recordPersonManagerService.updateById(recordPersonManager);
        return flag ? R.ok("修改能源管理人员信息成功") : R.failed("修改能源管理人员信息失败");
    }

    /**
     * 根据id审核能源管理人员信息
     */
    @PutMapping("audit")
    @SysLog("根据id审核能源管理人员信息")
    @ApiOperation(value = "根据id审核能源管理人员信息", notes = "根据id审核能源管理人员信息")
    @ApiImplicitParam(name = "AuditorDto", value = "审核对象", required = true, dataType = "json", paramType = "path")
    public R updateById(@RequestBody AuditorDto auditorDto) {
        if(auditorDto.getAuditDate()==null){
            auditorDto.setAuditDate(new Date());
        }
        ScUser u= SecurityUtils.getUser();
        if (u.getId() != null) {
            auditorDto.setAuditorId((long)u.getId());
        }
        boolean flag = recordPersonManagerService.updateByAudit(auditorDto);
        return flag ? R.ok("审核能源管理人员信息成功") : R.failed("审核能源管理人员信息失败");
    }

    /**
     * 根据id删除能源管理人员信息
     */
    @DeleteMapping("delete")
    @SysLog("根据id删除能源管理人员信息")
    @ApiOperation(value = "根据id删除能源管理人员信息", notes = "根据id删除能源管理人员信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", required = false, dataType = "int", paramType = "path"),
            @ApiImplicitParam(name = "id", value = "能源管理人员信息id", required = true, dataType = "int", paramType = "path")
    })
    public R removeById(Long userId, Long id) {
        RecordPersonManager recordPersonManager = new RecordPersonManager();
        if (id == null) {
            return R.failed("能源管理人员信息id不能为空！");
        } else {
            recordPersonManager.setId(id);
        }
        ScUser u= SecurityUtils.getUser();
        if (u.getId() != null) {
            recordPersonManager.setUpdateId(u.getId());
        }
        if(recordPersonManager.getUpdateDate() == null){
            recordPersonManager.setUpdateDate(new Date());
        }
        recordPersonManager.setDeleteFlag("4");
        boolean flag = recordPersonManagerService.removeByPersonId(recordPersonManager);
        //删除人员相关证书
        RecordCertificateManager certificateManager = new RecordCertificateManager();
        certificateManager.setDeleteFlag("4");
        certificateManager.setUpdateDate(new Date());
        if (u.getId() != null) {
            certificateManager.setUpdateId((long)u.getId());
        }
        certificateManager.setRecordPersonId(id);
        boolean flag2 = recordCertificateManagerService.removeByPersonId(certificateManager);

        return R.ok("删除能源管理人员信息成功");
    }
}
