package com.jpsoft.shinestar.modules.base.controller;

import com.github.pagehelper.Page;
import com.jpsoft.shinestar.config.OSSConfig;
import com.jpsoft.shinestar.modules.base.dto.EmployeeInfoDTO;
import com.jpsoft.shinestar.modules.common.utils.OSSUtil;
import com.jpsoft.shinestar.modules.common.utils.PojoUtils;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.base.entity.EmployeeInfo;
import com.jpsoft.shinestar.modules.base.service.EmployeeInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

@Controller
@RequestMapping("/base/employeeInfo")
@Api(description = "employeeInfo")
public class EmployeeInfoController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private OSSConfig ossConfig;

    @Autowired
    private EmployeeInfoService employeeInfoService;

    @ApiOperation(value="创建空记录")
    @GetMapping("create")
    @ResponseBody
    public MessageResult<EmployeeInfo> create(){
        MessageResult<EmployeeInfo> msgResult = new MessageResult<>();

        EmployeeInfo employeeInfo = new EmployeeInfo();

        msgResult.setData(employeeInfo);
        msgResult.setResult(true);

        return msgResult;
    }

    @ApiOperation(value="编辑信息")
    @GetMapping("edit/{id}")
    @ResponseBody
    public MessageResult<EmployeeInfo> edit(@PathVariable("id") Long id){
        MessageResult<EmployeeInfo> msgResult = new MessageResult<>();

        try {
            EmployeeInfo employeeInfo = employeeInfoService.get(id);

            if (employeeInfo != null) {
                msgResult.setResult(true);
                msgResult.setData(employeeInfo);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库不存在该记录!");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value="更新用户")
    @PostMapping("update")
    @ResponseBody
    public MessageResult<EmployeeInfo> update(@RequestBody EmployeeInfo employeeInfo,@RequestAttribute String subject){
        MessageResult<EmployeeInfo> msgResult = new MessageResult<>();

        try {
            employeeInfo.setUpdateBy(subject);
            employeeInfo.setUpdateTime(new Date());
            
            int affectCount = employeeInfoService.update(employeeInfo);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(employeeInfo);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库更新失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

	@ApiOperation(value="删除")
    @PostMapping("delete/{id}")
    @ResponseBody
    public MessageResult<Integer> delete(@PathVariable("id") Long id,@RequestAttribute String subject){
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            EmployeeInfo employeeInfo = employeeInfoService.get(id);
            employeeInfo.setDelFlag(true);
            employeeInfo.setUpdateBy(subject);
            employeeInfo.setUpdateTime(new Date());

            int affectCount = employeeInfoService.update(employeeInfo);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(affectCount);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("删除失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }


    @ApiOperation(value="批量删除")
    @PostMapping("batchDelete")
    @ResponseBody
    public MessageResult<Integer> batchDelete(@RequestBody List<Long> idList,@RequestAttribute String subject){
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            int affectCount = 0;

            for (Long id : idList) {
                EmployeeInfo employeeInfo = employeeInfoService.get(id);

                if(employeeInfo!=null) {
                    employeeInfo.setDelFlag(true);
                    employeeInfo.setUpdateBy(subject);
                    employeeInfo.setUpdateTime(new Date());

                    affectCount += employeeInfoService.update(employeeInfo);
                }
            }

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(affectCount);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("删除失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }


    @ApiOperation(value="分页列表")
    @RequestMapping(value = "pageList",method = RequestMethod.POST)
    @ResponseBody
    public MessageResult<Map> pageList(
            String employeeName,
            String companyId,
            Boolean exportStatus,
            @RequestParam(value="pageIndex",defaultValue="1") int pageIndex,
            @RequestParam(value="pageSize",defaultValue="20") int pageSize,
            @RequestAttribute String subject){

        //当前用户ID
        System.out.println(subject);

        MessageResult<Map> msgResult = new MessageResult<>();

        Map<String,Object> searchParams = new HashMap<>();

        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort("c.sort_no","asc"));
        sortList.add(new Sort("e.id_","asc"));

        if (StringUtils.isNotEmpty(employeeName)) {
            searchParams.put("employeeName","%" + employeeName + "%");
        }

        if (StringUtils.isNotEmpty(companyId)) {
            searchParams.put("companyId",companyId);
        }

        if (exportStatus!=null){
            searchParams.put("exportStatus",exportStatus);
        }

        Page<EmployeeInfo> page = employeeInfoService.pageSearch(searchParams,pageIndex,pageSize,sortList);

        msgResult.setResult(true);
        msgResult.setData(PojoUtils.pageWrapper(page));

        return msgResult;
    }

    @ApiOperation(value="根据openId获取员工信息")
    @GetMapping("mobile/findByOpenId")
    @ResponseBody
    public MessageResult<EmployeeInfoDTO> findByOpenId(String openId){
        MessageResult<EmployeeInfoDTO> msgResult = new MessageResult<>();

        try {
            EmployeeInfo employeeInfo = employeeInfoService.findByOpenId(openId);

            if (employeeInfo != null) {
                msgResult.setResult(true);

                EmployeeInfoDTO dto = new EmployeeInfoDTO();
                PojoUtils.map(employeeInfo,dto);

                msgResult.setData(dto);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库不存在该记录!");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value="保存信息")
    @PostMapping("mobile/save")
    @ResponseBody
    public MessageResult<String> save(EmployeeInfoDTO employeeInfoDTO){
        MessageResult<String> msgResult = new MessageResult<>();

        try {
            int affectCount = 0;

            EmployeeInfo employeeInfo = employeeInfoService.findByOpenId(employeeInfoDTO.getOpenId());

            if(employeeInfo==null) {
                employeeInfo = new EmployeeInfo();

                PojoUtils.map(employeeInfoDTO,employeeInfo);
                employeeInfo.setExportStatus(false);
                employeeInfo.setDelFlag(false);
                employeeInfo.setCreateTime(new Date());
                affectCount = employeeInfoService.insert(employeeInfo);
            }
            else{
                PojoUtils.map(employeeInfoDTO,employeeInfo);
                employeeInfo.setExportStatus(false);
                employeeInfo.setDelFlag(false);
                employeeInfo.setUpdateTime(new Date());

                affectCount = employeeInfoService.update(employeeInfo);
            }

            if (affectCount > 0) {
                msgResult.setResult(true);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("保存失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }


    @PostMapping("mobile/upload")
    @ResponseBody
    @ApiOperation(value="员工照片上传")
    @ApiImplicitParams({
            @ApiImplicitParam(name="photoName",value = "照片名称",required = true,paramType = "form"),
            @ApiImplicitParam(name = "photoFile",value = "员工照片", required = true,paramType="form", dataType = "__file")
    })
    public MessageResult<String> upload(String photoName,MultipartFile photoFile){
        MessageResult<String> messageResult = new MessageResult<>();

        try {
            String retFileUrl = OSSUtil.upload(ossConfig,"/employee",photoName,photoFile.getInputStream());

            messageResult.setResult(true);
            messageResult.setData(retFileUrl);
            messageResult.setCode(200);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);

            messageResult.setResult(false);
            messageResult.setMessage(e.getMessage());
        }

        return messageResult;
    }

    @PostMapping("mobile/uploadBase64")
    @ResponseBody
    @ApiOperation(value="员工照片上传")
    @ApiImplicitParams({
            @ApiImplicitParam(name="photoName",value = "照片名称",required = true,paramType = "form"),
            @ApiImplicitParam(name = "photoBase64Data",value = "员工照片base64编码", required = true,paramType="form")
    })
    public MessageResult<String> uploadBase64(String photoName,String photoBase64Data){
        MessageResult<String> messageResult = new MessageResult<>();

        try {
            BASE64Decoder decoder = new BASE64Decoder();

            byte[] imgData = decoder.decodeBuffer(photoBase64Data);

            for (int i = 0; i < imgData.length; ++i) {
                if (imgData[i] < 0) {// 调整异常数据
                    imgData[i] += 256;
                }
            }

            ByteArrayInputStream inputStream = new ByteArrayInputStream(imgData);

            String retFileUrl = OSSUtil.upload(ossConfig,"/employee",photoName,inputStream);

            messageResult.setResult(true);
            messageResult.setData(retFileUrl);
            messageResult.setCode(200);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);

            messageResult.setResult(false);
            messageResult.setMessage(e.getMessage());
        }

        return messageResult;
    }

    @ApiOperation(value="打包下载员工资料")
    @RequestMapping(value = "downloadZip",method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name="ids",value = "选中用户编号",required = true,paramType = "query"),
            @ApiImplicitParam(name="localPath",value = "压缩包解压后文件夹所在路径",required = true,paramType = "query"),
    })
    public void downloadZip(String ids,String localPath, HttpServletRequest request, HttpServletResponse response){
        try {
            String path = request.getContextPath();
            String basePath = request.getScheme() + "://" + request.getServerName()+":"+request.getServerPort()+path+"/";

            response.setCharacterEncoding("utf-8");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);

            //设置编码  为了解决中文名称乱码问题
            String fileName = "员工资料";
            String zipFileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
            response.setHeader("Content-Disposition", "attachment;fileName=" + zipFileName + ".zip");

            //打包文件
            List<Map<String,Object>> fileList = new ArrayList<>();

            //读取模板
            InputStream inputStream = this.getClass().getResourceAsStream("/src/main/resources/static/template.csv");
            byte[] bytes = new byte[inputStream.available()];
            inputStream.read(bytes);
            inputStream.close();

            StringBuilder csvBuilder = new StringBuilder();
            csvBuilder.append(new String(bytes,"GBK"));

            List<EmployeeInfo> employeeInfos = employeeInfoService.findByArray(ids.split(","));

//            String tmpdir = System.getProperty("java.io.tmpdir");
//            String tmpFilePath = tmpdir + File.separator + DateTime.now().toString("yyyyMMhddHHmmssSSS") + ".csv";

//            File tmpFile = new File(tmpFilePath);

            if(employeeInfos.size()>0) {
                for (EmployeeInfo employeeInfo : employeeInfos) {
                    if (StringUtils.isNotEmpty(employeeInfo.getPhoto())) {
                        csvBuilder.append(employeeInfo.getId() + ",");
                        csvBuilder.append(employeeInfo.getName() + ",");

                        String url = employeeInfo.getPhoto();
                        String photoExt = url.substring(url.lastIndexOf("."));
                        String photoFileName = employeeInfo.getCompanyName() + "-" + employeeInfo.getName() + "-" + employeeInfo.getId() + photoExt;

                        csvBuilder.append(localPath + "\\照片\\" + photoFileName + "\r\n");
                    }
                }

//                FileOutputStream fileOutput = new FileOutputStream(tmpFile);
//                byte[] data = csvBuilder.toString().getBytes("UTF-8");
//                fileOutput.write(data,0,data.length);
//                fileOutput.close();

                Map<String, Object> fileMap = new HashMap<>();
                fileMap.put("fileData", csvBuilder.toString().getBytes("GBK"));
                fileMap.put("fileName", "人员名单.csv");

                fileList.add(fileMap);
            }

            //身份证
            for (EmployeeInfo employeeInfo : employeeInfos) {
                if (StringUtils.isNotEmpty(employeeInfo.getPhoto())){
                    employeeInfo.setExportStatus(true);
                    employeeInfo.setUpdateTime(new Date());
                    employeeInfoService.update(employeeInfo);

                    String url = employeeInfo.getPhoto();
                    String photoExt = url.substring(url.lastIndexOf("."));
                    String photoFileName = employeeInfo.getCompanyName() + "-" + employeeInfo.getName() + "-" + employeeInfo.getId() + photoExt;

                    Map<String,Object> fileMap = new HashMap<>();
                    fileMap.put("fileUrl",url + "?x-oss-process=image/resize,l_800,limit_1");
                    fileMap.put("filePath", "照片/");
                    fileMap.put("fileName", photoFileName);

                    fileList.add(fileMap);
                }
            }

            OutputStream output = response.getOutputStream();

            OSSUtil.batchDownload(fileList,output);

//            if (tmpFile.exists()){
//                tmpFile.delete();
//            }

            output.flush();
            output.close();
        }
        catch (Exception ex){
            logger.error(ex.getMessage(),ex);
        }
    }
}
